help me simple code result min and max number - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: help me simple code result min and max number (/thread-38689.html) |
help me simple code result min and max number - abrahimusmaximus - Nov-12-2022 I have the following code: largest = None smallest = None while True: num = input('enter a num ') if num == "done": break try: val = float(num) except: print("Invalid input") continue if largest is None or num > largest: print("setting largest to ", num) largest = num print("largest: ", largest) print('***********') if smallest is None or num < smallest: print("setting smallest to ", num) smallest = num print("smallest: ", smallest) print('***********') print("Maximum is", largest) print("Minimum is", smallest)which produces the following output in the terminal two questions:1. If I remove the continue than the largest is set to bob? Why? Why do I even need the continue? I would never expect bob to be set to the largest as largest has already been set to 7 previously (it can not be None) and bob can not be greater than largest if largest is None or num > largest: 7 is None || "bob" > 7 False || False I do not understand how that statement can be truthy 2. How does the final smallest get set to 10 ? it was last set to 2 is 10 less than 2? please explain these things In my language the below image works exactly as expected so why isnt the above code working as expected? [attachment=2095] RE: help me simple code result min and max number - deanhystad - Nov-12-2022 The main problem with the code is that it doesn't compare numbers. It compares number strings. It doesn't use "val" anywhere. You can verify by doing this: > python test.py enter a num 5 setting largest to 5 largest: 5 *********** setting smallest to 5 smallest: 5 *********** enter a num 1234567 setting smallest to 1234567 smallest: 1234567 ***********Numerically 1234567 is greater than 5, but as a string, "5" > "1", so "5" > "1234567". Since you are comparing strings, this makes perfect sense and is True (ord("b") > ord("7")). if "7" is None || "bob" > "7":If you compare "bob" and the number 7 you get a TypeError. RE: help me simple code result min and max number - buran - Nov-12-2022 (Nov-12-2022, 04:45 AM)abrahimusmaximus Wrote: Why do I even need the continue? continue returns the execution at the start of the loop, i.e. if you get error, when trying to convert e.g. bob to float value it will ask for user input again till get valid input. Also, bare except is bad practice, be specific, in this case except TypeError:
|