简体   繁体   中英

A code in Python evaluating numbers integer to float problem with iterations

I am new to programming so this might be funny to you guys but I need help. I need to write a program in Python that lets users input numbers, returns an error message, and continues if someone inputs something besides numbers and in the end writes all the numbers and says which is the smallest and which is the largest number. The problem is that I can't get it to write numbers but only digits. So if I write 56, 77, and 17 it returns that the smallest is 1 and the biggest is 7. Here is my code:

largest = None
smallest = None
while True:
    num = input("Enter a number: ")
    if num == "done":
        break
    try:
        fnum = float(num)
    except:
        print("Invalid input")
        continue

    print(num)

    for value in num:
        if smallest is None:
            smallest = value
        elif value < smallest:
            smallest = value

    for value in num:
        if largest is None:
            largest = value
        elif value > largest:
            largest = value

print("Maximum is", largest)
print("Minimum is", smallest)

Thank you for your help!

Two reasons why your program didn't work:

  • num only holds one value (not a list).
  • The value of num is a string because you obtained it directly from input. So you are iterating over characters in a string when you did for value in num

You can keep a list of floats instead, for example:

num_list = []

largest = None 
smallest = None 
while True: 
    user_input = input("Enter a number: ") 
    if user_input == "done": 
        break 
    try: 
        fnum = float(user_input) 
        num_list.append(fnum)
    except: 
        print("Invalid input") 
        continue

for value in num_list:
    if smallest is None:
        smallest = value
    elif value < smallest:
        smallest = value

for value in num_list:
    if largest is None:
        largest = value
    elif value > largest:
        largest = value

print("Largest:", largest)
print("Smallest:", smallest)

use int() for the variables ex) smallest = int(value)

print(f'maximum is {largest}, minimum is {smallest}')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM