Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Python 

Print minimum and maximum of user input

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.
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.
(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.
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.
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


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Shell] by Emre_Nov 3, 2020 10:03 AM 2 217 Nov 3, 2020 10:03 AM
Last Post: Emre_
[Python] by SIM-1866423Apr 28, 2020 02:59 PM 0 96 Apr 28, 2020 02:59 PM
Last Post: SIM-1866423
[C] by ShallowMEFeb 17, 2020 07:08 PM 20 525 Feb 17, 2020 07:08 PM
Last Post: 0xDEAD10CC