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

Viewed 53
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 :)

3 Answers

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

You can use while loop, which will look something like this:

while True:
    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)
        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")
def funcation(c,num1,num2):

    if c==1:
        m = num1+num2
        return m
    elif c==2:
        return num1*num2
        
    elif c==3:
        return num1/num2
        
    elif c==4:
        return num1-num2
        
        
        


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 & c != 2 & c != 3 & c != 4:
        print(funcation(c,num1,num2))
        print("Choose 1/2/3/4 only")
    else:
        print(funcation(c,num1,num2))
Related