Python Forum
what's wrong with the loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
what's wrong with the loop
#2
the problems show up best with print statements, and setting except to only capture ValueError:

largest = None
smallest = None
while True:
    num = input("Enter a number: ")
    # with following (2) statements largest, smallest, and num will always be equal
    largest=num
    smallest=num
    # show all values
    print('num: {}, largest: {}, smallest: {}'.format(num, largest, smallest))
    try:
        # 
        for n, values in enumerate([num]):
            print('iteration number: {}, values: {} largest: {}, float(): {}'.format(n, values, largest, float(num)))
            # following line causes exception and would never be true even if both were of same type
            # largest is a string float(num) is a float this is a TypeError exception
            if largest < float(num):
                largest=float(num)
    # Look for specific exception, so others will fail and show why
    except ValueError:
        print("Invalid input")

    # This line should fall immediately after the input statement, and (PEP8) should be written:
    # if num == "done":
    #     break
    if num == "done" : break
     
 
print("Maximum is",largest)
print("Minimum is",smallest)
results:
Output:
Enter a number: 1234 num: 1234, largest: 1234, smallest: 1234 iteration number: 0, values: 1234 largest: 1234, float(): 1234.0 Traceback (most recent call last): File "/media/larz60/Data-2TB/Projects/TryStuff/src/numstuff.py", line 16, in <module> if largest < float(num): TypeError: '<' not supported between instances of 'str' and 'float'
There are numerous issues with this code,
start by fixing those pointed out, remove lines 6 and 7,
loop: 'for n, values in enumerate([num]):' wrong, look at printout
do 'done' check immediately after input, and
do conversion to float immediately after that
There are more issues, but fix these first (read comments that I have put in code.),
try to figure out remaining errors (print is your friend)
then come back for more help
Reply


Messages In This Thread
what's wrong with the loop - by lielz - Dec-06-2018, 11:33 AM
RE: what's wrong with the loop - by Larz60+ - Dec-06-2018, 03:08 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020