Waseem Munir
Waseem Munir

Reputation: 60

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))

Upvotes: 0

Views: 53

Answers (3)

Harsha Biyani
Harsha Biyani

Reputation: 7268

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")

Upvotes: 1

shaik moeed
shaik moeed

Reputation: 5785

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.

Upvotes: 1

Mansur
Mansur

Reputation: 1829

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))

Upvotes: 0

Related Questions