简体   繁体   中英

repeating input

I want to program it like that so while taking input of num1,num2 and operation if user doesn't give input in appropriate type it ask the user again for input.

operation=(input('1.add\n2.subtract\n3.multiply\n4.divide'))
num1 =int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if operation == "add" or operation == '1' :
   print(num1,"+",num2,"=", (num1+num2))
elif operation =="subtract" or operation == '2':
   print(num1,"-",num2,"=", (num1-num2))
elif operation =="multiply" or operation == '3':
   print(num1,"*",num2,"=", (num1*num2))
elif operation =="divide" or operation == '4':
   print(num1,"/",num2,"=", (num1/num2))

You can use in keyword.

Ex:

>>> "1" in ["1","add"]
True
>>> "add" in ["1","add"]
True

Modify code like:

 operation=(input('1.add\n2.subtract\n3.multiply\n4.divide'))

    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))

    if operation in ["1","add"] :
       print(num1,"+",num2,"=", (num1+num2))
    elif operationi in ["2", "subtract"]:
       print(num1,"-",num2,"=", (num1-num2))
    elif operation in ["3", "multiply"]:
       print(num1,"*",num2,"=", (num1*num2))
    elif operation in ["4", "divide"]:
       print(num1,"/",num2,"=", (num1/num2))
    else:
        print("Invalid Input")

Try this,

 operation=(input('1.add\n2.subtract\n3.multiply\n4.divide'))

    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))

    if operation == "1" or operation == "add" :
       print(num1,"+",num2,"=", (num1+num2))
    elif operation == "2" or operation == "subtract":
       print(num1,"-",num2,"=", (num1-num2))
    elif operation == "3" or operation == "multiply":
       print(num1,"*",num2,"=", (num1*num2))
    elif operation == "4" or operation == "divide":
       print(num1,"/",num2,"=", (num1/num2))
    else:
        print("Invalid Input")

Explanation:

In your code, IF will check condition-1 or condition-2 are True or False

if operation == "1" or operation == "add" 

here,

condition-1: operation == "1"

condition-2: operation == "add"

if operation == "1" or operation == "add" 

here,

condition-1: operation == "1"

condition-2: "add" # Always True as string contains elements.

This code is valid because in Python values are either truthy and falsy. However, the syntax for multicondition if clause is wrong. It should be if a == something and b == anotherthing .

So it will be as follows.

if operation == "1" or operation == "add" :
    print(num1,"+",num2,"=", (num1+num2))

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