-3

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

1 Answers1

0

You are looking for a while loop:

num1 = None
while num1 is None:
    try:
        num1 = int(input('Enter a number: '))
    except ValueError:
        print('Invalid, input must be an integer!')
    else:
       # Examples of further tests you could add.
       # code here in the try-else block is only executed if the "try-part" was successful
       if num1 < 0:
           print('Number might not be negative')
           num1 = None
       elif:
           ...



Note: Please, consider searching the forum first for similar questions, before you post your own, otherwise people might downvote you and mark it as duplicate.

Snow bunting
  • 1,120
  • 8
  • 28
  • why did you use num1=None ? – Waseem Munir May 30 '19 at 05:32
  • One needs to initialise the variable first before we check the condition in the `while` statement, and `None` seems to be a good value to me :) Note that saying `num1 = None` is not the same as not defining `num1` at all, since `None` is an existing Python object. – Snow bunting May 30 '19 at 07:03
  • thank you,i am having another problem in same code,i want to put error check on operation,like if someone give wrong selection of operation it take the input again by saying "Please enter correct operation",i have tried following but didn't work – Waseem Munir May 30 '19 at 07:19
  • while True: try: operation=input('1.Add\n2.Subtract\n3.Multiply\n4.Divide\nSelect:') operation=operation.lower() except: if operation in ["1","Add","2","Subtract","3","Multiply","4","Divide"]: break else: print("Please enter the correct operator") – Waseem Munir May 30 '19 at 07:21
  • ok so inside the `except` block you write could in case the try fails, i.e. what happens if you cannot call `operation.lower()` (which will newer throw an error). Inside the `else` block you put code that happens if the `try` was successful... Put your `if ... in ['Add', ...]`in there – Snow bunting May 30 '19 at 07:24