简体   繁体   中英

Python: 2-input-variable loop that operates until the user tells it to stop?

The loop starts with two variables, let's call them X and Y, both at 0. The user is prompted to enter a number to add to X, then a number to add to Y. The loop repeats itself, letting the user continue to add to both variables, until the user wants it to stop -- I guess they could enter 'add' as one of the inputs?

I also need it to ask for the input again if the user inputs anything other than a digit, but only if it's also not 'add'. If it's 'add', the loop ends, and both totals are displayed. If the input is a float or int, the loop proceeds. Otherwise, it prompts the input again. And this is for each of the two inputs.

I can do either of these things separately, but I'm having trouble incorporating both requirements into the same loop structure.

So far, my code basically looks like this:

while (x != 'add') and (y != 'add'):
    # ask input for x
    if x != 'add':
        #ask input for y
        if (x != 'add') and (y != 'add'):
            # operations that add inputs to running variables
        else:
            pass
    else:
        pass
# print both variable totals here

My first issue is that the user is supposed to be entering digits, while the code is also checking for a string. How would I resolve that? My second issue is that I'm not sure how to reprompt each input if the input is not either a digit or 'add'.

Welcome to SO!

You've generally got the right idea, here's how you might translate that into code.

x_total = 0
y_total = 0

while True:
    first_input = input('Enter the next value of x: ')
    if first_input == 'add':
        break
    x_total += float(first_input)

    second_input = input('Enter the next value of y: ')
    if second_input == 'add':
        break
    y_total += float(second_input)

print('x = ', x_total)
print('y = ', y_total)

Note that in Python we can convert a string number_string = '1239' into a float by calling the type float as number = float(number_string ) . The same applies to int for integers. The documentation contains useful recipes and usage examples and is typically where I start when I'm unsure what I need.

Since you mentioned that you're new to Python, I'll mention that more than other languages, strong idioms exist in Python. The Zen of Python is a sort of introduction to this idea. It's frequently useful to ask 'is this Pythonic?' when you first begin, as there are probably established ways to do whatever you're doing which will be clearer, less error-prone, and may run faster.

This slide deck is a good look at some Pythonisms, it's tailored to Python 2.x so some syntax is different, but the ideas are just as relevant in 3.x.

A more Pythonic, (though possibly less understandable way to new Python users) of fulfilling your original request is to use any unexpected value or escape character to quit the adding process.

x_total = 0
y_total = 0

while True:

    try:

        first_input = input('Enter the next value of x: ')
        x_total += float(first_input)

        second_input = input('Enter the next value of y: ')
        y_total += float(second_input)
    except (ValueError, EOFError):
        break
    except KeyboardInterrupt:
        print()
        break

print('x =', x_total)
print('y =', y_total)

Now users of your program can type any non-float value to exit, or even use the key interrupts (ctrl + Z or ctrl + C for example). I ran it in PowerShell to give you some usage examples:

With exit, a common idiom:

Enter the next value of x: 1
Enter the next value of y: 2
Enter the next value of x: 3
Enter the next value of y: exit
x = 4.0
y = 2.0

Your original case, with add:

Enter the next value of x: 1
Enter the next value of y: 2
Enter the next value of x: 3
Enter the next value of y: add
x = 4.0
y = 2.0

With ctrl + Z:

Enter the next value of x: 1
Enter the next value of y: 2
Enter the next value of x: 3
Enter the next value of y: ^Z
x = 4.0
y = 2.0

With ctrl + C:

Enter the next value of x: 1
Enter the next value of y: 2
Enter the next value of x: 3
Enter the next value of y:
x = 4.0
y = 2.0

You can apply an "endless" loop, and break it with a string input,eg "add" or any other, or pressing Enter:

while True:
         try:
            x=float(input("give x or enter to stop: "))
            X+=x
            y=float(input("give y or enter to stop: "))
            Y+=y
         except ValueError:
             print(X,Y)
             break

I know you asked to output the results after the loop but I decided to do it before Python breaks the loop. This is the code:

print("If you want to end the program input 'add'.")
x_value = 0
y_value = 0
while True:
    x_input = str(input("Value of X:"))
    if x_input != 'add':
        y_input = str(input("Value of Y:"))
        if (x_input != 'add') and (y_input != 'add'):
            x_value += int(x_input)
            y_value += int(y_input)
        elif y_input == "add":
            x_value += int(x_input)
            print("Value of X:", str(x_value))
            print("Value of Y:", str(y_value))
            break
    elif x_input == "add":
       print("Value of X:", str(x_value))
       print("Value of Y:", str(y_value))
       break

Hope it helps :)

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