Hack Forums
[Python] Print minimum and maximum of user input - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Python] Print minimum and maximum of user input (/showthread.php?tid=4722111)



Print minimum and maximum of user input - Amazing - Mar 8, 2015

I need to create a loop that asks for users to input integers until entering the string "done", then the loop breaks and prints out the lowest and highest integer the user has entered.

This is what I have so far but I can't seem to get it work properly...

Any help? I'm just starting to learn Python. 🙂

Code
largest = None
smallest = None

while True:
    num = raw_input("Enter an integer: ")
    
    if num == "done" :
        break
    elif largest is None :
        largest = num
    elif smallest is None :
        smallest = num
    elif num > largest :
        largest = num
    elif num < smallest :
        smallest = num
    print num

print "Minimum", smallest
print "Maximum", largest

When I run this, it works, but it will print out the wrong numbers. Sometimes the smallest is actually the larges, or vice versa, and sometimes it takes multiple times to enter "done" for the loop to actually break. I'm not sure what's wrong.


* - Misingnoglic - Mar 8, 2015

remember whatever you get from raw_input will be a string. But also this is designed pretty spaggetti like, so try to make it more concise.


* - Hopeful Goods - Mar 8, 2015

(Mar 8, 2015 09:35 PM)Misingnoglic Wrote:  remember whatever you get from raw_input will be a string. But also this is designed pretty spaggetti like, so try to make it more concise.

At first I was like what does he mean spaghetti, but then I got you.


* - Misingnoglic - Mar 8, 2015

http://en.wikipedia.org/wiki/Spaghetti_code

Yeah, it's not very bad, but a while True with a break statement probably isn't how you want to go about this.


* - Pythonis - Mar 9, 2015

You might wanna take a look at the min() and max() functions that come with python to make this better

https://docs.python.org/2/library/functions.html#min
https://docs.python.org/2/library/functions.html#max