简体   繁体   中英

User-input variable has incorrect value at end of loop

I am new to programming and I am writing a program to find the smallest and largest number in inputs made by the user.

The user enters numbers one at a time and ends by entering "done". If the user enters a non-numeric input other than "done", an error message should be displayed.

When I run my code, it appears that the word "done" which is supposed to be the one that terminates the code seems to be the input the computation is performed on.

How can I let the program accept inputs and only execute the computation on integer variables without string variables?

Below is my code:

largest = None
smallest = None
while True:
    num = input("Enter a number: ")

    if num == "done":
        break

for value in num:
    try:
        imp = int(num)
    except:
        print ("Invalid input")

        continue

    smallest = min(num)

    largest = max(num)

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

On each iteration of the while loop, you overwrite the value of num . Thus when the user enters "done" to end the loop the current value of num is "done" .

Consider using a list to store each input from the user (as long as that input is not the value "done" ).

For example:

nums = []

while True:
    num = input("Enter a number: ")

    if num == "done":
        break

    nums.append(num)

Then iterate over the values in nums , like so:

for num in nums:
    # ...

Also you might consider doing input validation as the user inputs each value, rather than waiting for all values to be entered and then skipping any invalid values. This would create a better user experience.

For example:

nums = []

while True:
    num = input("Enter a number: ")

    if num == "done":
        break

    try:
        num_int = int(num)
    except ValueError:
        print("Invalid value, please enter a valid integer.")
        continue

    nums.append(num_int)

# no loop necessary:
smallest = min(nums)
largest = max(nums)

In case you want the user to enter multiple numbers separated by a space and hit enter at the end instead of typing "done" (which is tedious wrt user experience), here is a code that will do that for you:

nums = list(map(str, input().rstrip().split()))

When you print nums, it will be a list of all the numbers. This is a easy and " pythonic " way of taking multiple inputs from user.

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