Reputation: 3
Im new to python and wrote a programm that does a+b=c and the question is, how do i do that the programm go back to the top?
This is what i have tried but it wont open
#def start():
a = int(input("num1: "))
b = int(input("num2: "))
c = a + b
print("sum of {0} + {1} = {2}" .format(a, b, c))
restart = input("Exit or Again?: ")
if restart == "Again" or "again":
start()
if restart == "Exit" or "exit":
exit
Had looked up a few tutorials but none of them helped. Thank you in advance.
Upvotes: 0
Views: 104
Reputation: 2123
Be careful with your condition restart == "Again" or "again"
because it is equivalent to (restart == "Again") or "again"
. The boolean value of a string (here again
) is True unless this string is empty. So this condition will always be True
.
If you want to keep the same structure :
def start():
a = int(input("num1: "))
b = int(input("num2: "))
c = a + b
print("sum of {0} + {1} = {2}" .format(a, b, c))
restart = input("Exit or Again?: ")
if restart in ["Again", "again"]:
start()
else:
print("Bye !")
start()
If you prefer to achieve it with a while loop
:
restart = "again"
while restart in ["Again", "again"]:
a = int(input("num1: "))
b = int(input("num2: "))
c = a + b
print("sum of {0} + {1} = {2}" .format(a, b, c))
restart = input("Exit or Again?: ")
Upvotes: 2
Reputation: 634
Your code only defines a function. If you want to run it from command line, you need to add some code to do so.
The 2 lines I added at the bottom detect if you're running this file directly and then invoke your function. If you imported this module, the if
would be false and the logic within the if
would not be run.
def start():
a = int(input("num1: "))
b = int(input("num2: "))
c = a + b
print("sum of {0} + {1} = {2}" .format(a, b, c))
restart = input("Exit or Again?: ")
if restart in ["Again", "again"]:
start()
else
exit()
if __name__ == '__main__':
start()
Upvotes: -1
Reputation: 10727
You need a loop.
again = True
while again:
...
if restart.lower() == 'exit':
again = False
Upvotes: 0