def interact():
while True:
try:
num = int(input("Please input an integer: "))
if (num % 2) == 0:
print ("{0} is even".format(num))
else:
print("{0} is odd".format(num))
num_two = int(input('Do you want to play again n/Y:'))
except:
if num_input == "y":
continue
finally:
print("Goodbye")
print(num_two)
Making a program than would ask the user for an integer then will asked if they wish to loop or quit
127 Views Asked by Beginner to everything At
4
There are 4 best solutions below
1
On
The play-again prompt expects a string, not a number, to be entered. Don't try to treat it as a number. Restrict the try statement to testing the number input: if you get a ValueError, restart the loop immediately, instead of trying to test if it is even or odd.
When you get the response to play again, use break to exit the loop if the response isn't y.
Print "Good bye" after the loop exits.
def interact():
while True:
try:
num = int(input("Please input an integer: "))
except ValueError:
continue # Ask for a number again
if num % 2 == 0:
print("{0} is even".format(num))
else:
print("{0} is odd".format(num))
response = input("Play again? (n/Y) ")
if response != "y":
break
print("Good bye")
0
On
I don't fully understand what you are after, but maybe try something like this:
def interact():
while True:
try:
num = int(input("Please input an integer: "))
if (num % 2) == 0:
print ("{0} is even".format(num))
else:
print("{0} is odd".format(num))
except:
continue
if input("Would you like to play again? Y/N: ").lower() == "y":
continue
else:
print("goodbye")
break
I believe this will give the effect your are after.
0
On
A more compact approach:
def interact():
want_continue = "Y"
while want_continue == "Y":
try:
num = int(input("Please input an integer: "))
print ("{0} is {1}".format(num, "even" if num % 2 == 0 else "odd"))
want_continue = input('Do you want to play again (n/Y):').upper()
except ValueError:
print("Please enter a number")
print("Goodbye")
Use a break statment after your Goodbye: