Skip to content
Advertisement

how to restart a else if loop if a user enters a wrong number

num1= int(input("Choose a number:"))
num2= int(input("Choose another number:"))
c=int(input("Type '1' for addition, '2' for muiplication, '3' for division, '4' for subsctraction:"))
if c==1:
 result=num1+num2
 print('Answer = ', result)
elif c==2:
 result=num1*num2
 print('Answer = ', result)
elif c==3:
 result=num1/num2
 print('Answer = ', result)
elif c==4:
 result=num1-num2
 print('Answer = ', result)
else:
 print("Choose 1/2/3/4 only")

So I wrote this simple calculator code but I dont know how to make user repeat the whole cycle if they enter a wrong number I thought of doing it using while loop and boolean is valid i have no idea how to do it a little help would be appreciated :)

Advertisement

Answer

Here’s your answer:
just simply put that calculator code in a infinite loop for wrong entry.

num1= int(input("Choose a number:"))
num2= int(input("Choose another number:"))
while(True):
    c=int(input("Type '1' for addition, '2' for muiplication, '3' for division, '4' for subsctraction:"))
    if c==1:
        result=num1+num2
        print('Answer = ', result)
        break
    elif c==2:
        result=num1*num2
        print('Answer = ', result)
        break
    elif c==3:
        result=num1/num2
        print('Answer = ', result)
        break
    elif c==4:
        result=num1-num2
        print('Answer = ', result)
        break
    else:
        print("Choose 1/2/3/4 only")
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement