Ask the user if they want to repeat the same task again - python

If the user gets to the end of the program I want them to be prompted with a question asking if they wants to try again. If they answer yes I want to rerun the program.
import random
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value.\n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.")
print("--------------------")
total = 0
final_coin = random.randint(1, 99)
print("Enter coins that add up to", final_coin, "cents, on per line")
user_input = int(input("Enter first coin: "))
total = total + user_input
if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
print("invalid input")
while total != final_coin:
user_input = int(input("Enter next coin: "))
total = total + user_input
if total > final_coin:
print("Sorry - total amount exceeds", (final_coin))
if total < final_coin:
print("Sorry - you only entered",(total))
if total== final_coin:
print("correct")

You can enclose your entire program in another while loop that asks the user if they want to try again.
while True:
# your entire program goes here
try_again = int(input("Press 1 to try again, 0 to exit. "))
if try_again == 0:
break # break out of the outer while loop

This is an incremental improvement on the accepted answer:
Used as is, any invalid input from the user (such as an empty str, or the letter "g" or some such) will cause an exception at the point where the int() function is called.
A simple solution to such a problem is to use a try/except- try to perform a task/ code and if it works- great, but otherwise (except here is like an else:) do this other thing.
Of the three approaches one might try, I think the first one below is the easiest and will not crash your program.
Option 1: Just use the string value entered with one option to go again
while True:
# your entire program goes here
try_again = input("Press 1 to try again, any other key to exit. ")
if try_again != "1":
break # break out of the outer while loop
Option 2: if using int(), safeguard against bad user input
while True:
# your entire program goes here
try_again = input("Press 1 to try again, 0 to exit. ")
try:
try_again = int(try_again) # non-numeric input from user could otherwise crash at this point
if try_again == 0:
break # break out of this while loop
except:
print("Non number entered")
Option 3: Loop until the user enters one of two valid options
while True:
# your entire program goes here
try_again = ""
# Loop until users opts to go again or quit
while (try_again != "1") or (try_again != "0"):
try_again = input("Press 1 to try again, 0 to exit. ")
if try_again in ["1", "0"]:
continue # a valid entry found
else:
print("Invalid input- Press 1 to try again, 0 to exit.")
# at this point, try_again must be "0" or "1"
if try_again == "0":
break

Related

Code not printing what I seek

For the first bit, as I print out the "ask2", it prints out "exit" as opposed to the licence plate that it's supposed to be printing.
ask = input("-Would you like to 1 input an existing number plate\n--or 2 view a random number\n1 or 2: ")
ask2 = ""
plate = ""
if int(ask) == 1:
ask2 = ""
print("========================================================================")
while ask2 != 'exit':
ask2 = input ("Please enter it in such form (XX00XXX): ").lower()
# I had no idea that re existed, so I had to look it up.
# As your if-statement with re gave an error, I used this similar method for checking the format.
# I cannot tell you why yours didn't work, sorry.
valid = re.compile("[a-z][a-z]\d\d[a-z][a-z][a-z]\Z")
#b will start and end the program, meaning no more than 3-4 letters will be used.
# The code which tells the user to enter the right format (keeps looping)
# User can exit the loop by typing 'exit'
while (not valid.match(ask2)) and (ask2 != 'exit'):
print("========================================================================")
print("You can exit the validation by typing 'exit'.")
time.sleep(0.5)
print("========================================================================")
ask2 = input("Or stick to the rules, and enter it in such form (XX00XXX): ").lower()
if valid.match(ask2):
print("========================================================================\nVerification Success!")
ask2 = 'exit' # People generally try to avoid 'break' when possible, so I did it this way (same effect)
**print("The program, will determine whether or not the car "+str(plate),str(ask)+" is travelling more than the speed limit")**
Also I am looking for a few good codes that are good for appending (putting the data in a list), and printing.
This is what I've done;
while tryagain not in ["y","n","Y","N"]:
tryagain = input("Please enter y or n")
if tryagain.lower() == ["y","Y"]:
do_the_quiz()
if tryagain==["n","N"]:
cars.append(plate+": "+str(x))
print(cars)
When you print ask2 it prints 'exit' because you set it to exit with ask2 = 'exit', and your loop cannot terminate before ask2 is set to 'exit'.
You could use ask2 for the user's input, and another variable loop to determine when to exit the loop. For example:
loop = True
while loop:
# ...
if valid.match(ask2) or ask2 == 'exit':
loop = False
I am not quite sure what your other block of code is trying to achieve, but the way that you test tryagain is incorrect, it will never be equal to a two element list such as ["y","Y"], perhaps you meant to use in?, This change shows one way to at least fix that problem:
while tryagain not in ["y","n","Y","N"]:
tryagain = input("Please enter y or n")
if tryagain.lower() == "y":
do_the_quiz()
else:
cars.append(plate+": "+str(x))
print(cars)

How to stop the beginning of my function's loop from repeating

I have created a code in which the user will input their choice which will continue in a loop if the variable 'contin' equals "yes". When the user enters the choice "no" or any other input it will print their overall answers or the error message and end the loop. Instead it then repeats the beginning of the function (in this case it's whether the user wanted to continue or not). Is there a way for me to prevent this from happening?
This is the code:
def userinput():
while True:
contin = input("Do you wish to continue the game? If so enter 'yes'. If not enter 'no'.")
if contin == 'yes':
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"']
guess = input("What symbol do you wish to change? ")
symbol_dictionary[guess] = input("Input what letter you wish to change the symbol to.(Make sure the letter is in capitals.) ")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
elif contin == ('no'):
print ("These were your overall answers:")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
if symbol_dictionary == {"#": "A","+":"C", "/":"Q", "0":"U", "8":"I",
"4":"R", "&":"E",'"':'D', "3":"L", "*":"M",
"%":"N", "2":"S", ":":"T", "1":"O",",":"J",
"$":"K", "!":"H", "7":"Z", "-":"Y", ".":"G",
"'":"W",")":"F", "6":"B", "5":"X", "9":"V"}:
print("Well done! You have completed the game!")
else:
print("Please enter a valid input.")
All you need to do is exit the function; add a return in your no branch:
elif contin == ('no'):
print ("These were your overall answers:")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
if symbol_dictionary == {"#": "A","+":"C", "/":"Q", "0":"U", "8":"I",
"4":"R", "&":"E",'"':'D', "3":"L", "*":"M",
"%":"N", "2":"S", ":":"T", "1":"O",",":"J",
"$":"K", "!":"H", "7":"Z", "-":"Y", ".":"G",
"'":"W",")":"F", "6":"B", "5":"X", "9":"V"}:
print("Well done! You have completed the game!")
# exit the function
return
Just add a break or a return at the end of the elif statement:
print("Well done! You have completed the game!")
break # or return
This will exit the loop. Break makes more sense in this context.

PYTHON: Unable to loop properly

EDIT: Thank you, the question has been answered!
The program works properly, asides from the fact that it does not loop to allow the user to play a new game. ie, after entering too many, too few, or the perfect amount of change, the program asks "Try again (y/n)?: " as it should. But I can't find out why it doesn't loop... And when it loops, it doesn't need to include the large paragraph about explaining the game. Just the line about "Enter coins that add up to "+str(number)+" cents, one per line." Any tips?
#Setup
import random
playagain = "y"
#Main Loop
if (playagain == "y"):
number = random.randint(1,99) #Generation of how many cents
total = 0 #Running sum of guessed coins.
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value. \n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.\n")
print("Enter coins that add up to "+str(number)+" cents, one per line.\n")
while (True):
if (total == 0):
word = "first"
else:
word = "next"
guess = str(input("Enter "+str(word)+" number: ")) #Records coin value
#Entry Validation
if (guess == ""): #When user is done guessing.
if (total < number):
print("Sorry - you only entered "+str(total)+" cents.\n")
break
elif (total > number):
print("Sorry - total amount exceeds "+str(number)+" cents.\n")
break
else:
print("Correct!")
break
elif (int(guess) == 1) or (int(guess) == 5) or (int(guess) == 10) or (int(guess) == 25):
total = total + int(guess)
else:
print("Invalid entry")
playagain = str(input("Try again (y/n)?: ")) #BRETT: I can't seem to get this to loop properly.
By using break, you're completely leaving the while loop and never checking the playagain condition. If you want to see if the user wants to play again put the 'playagain' check in another while loop.
#Setup
import random
playagain = "y"
#Main Loop
while (playagain == "y"):
number = random.randint(1,99) #Generation of how many cents
total = 0 #Running sum of guessed coins.
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value. \n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.\n")
print("Enter coins that add up to "+str(number)+" cents, one per line.\n")
while (True):
if (total == 0):
word = "first"
else:
word = "next"
guess = str(input("Enter "+str(word)+" number: ")) #Records coin value
#Entry Validation
if (guess == ""): #When user is done guessing.
if (total < number):
print("Sorry - you only entered "+str(total)+" cents.\n")
break
elif (total > number):
print("Sorry - total amount exceeds "+str(number)+" cents.\n")
break
else:
print("Correct!")
break
elif (int(guess) == 1) or (int(guess) == 5) or (int(guess) == 10) or (int(guess) == 25):
total = total + int(guess)
else:
print("Invalid entry")
playagain = str(input("Try again (y/n)?: ")) #BRETT: I can't seem to get this to loop properly.
You set playagain to y/n, but the code doesn't go back around to the beginning if playagain is equal to 'y'. Try making if playagain == "y" into while playagain == "y". That way, it goes through the first time and keeps going back to the beginning if playagain is still set to "y".
Also, indent your last line (playagain = str(....)) so it's part of the while playagain == "y" loop. If it's not, then the code will be stuck in an infinite loop because playagain isn't being changed inside the while loop.
Indent the last line as far as the while True line. And change the if (playagain == "y"): to a
while (playagain == "y"):
Your "Main loop" is not a loop, it is just an if statement. Also it is better to use raw_input because input will eval your input. Try something along the lines of this:
playagain = 'y'
#Main loop
while playagain == 'y':
print "do gamelogic here..."
playagain = raw_input("Try again (y/n)?: ")
Inside your gamelogic, you could use a boolean to check wether you need to print the game explanation:
show_explanation = True
while playagain == 'y':
if show_explanation:
print "how to play is only shown once..."
show_explanation = False
print "Always do this part of the code"
...
playagain = raw_input("Try again (y/n)?: ")

how to implement empty string in python

I need to be able to prompt the user to enter an empty string so it can check if the answer is correct. but every time I do that I can error saying invalid literal for int()
so I need to change my user_input so it can accept int() and strings(). how do I make that possible ?
# program greeting
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value.\n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.")
print("--------------------")
#print("Enter coins that add up to 81 cents, one per line.")
import sgenrand
#prompt the user to start entering coin values that add up to 81
while True:
total = 0
final_coin= sgenrand.randint(1,99)
print ("Enter coins that add up to", final_coin, "cents, on per line")
user_input = int(input("Enter first coin: "))
if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
print("invalid input")
else:
total = total + user_input
while total <= final_coin:
user_input = int(input("Enter next coin:"))
if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
print("invalid input")
else:
total = total + user_input
if total > final_coin :
print("Sorry - total amount exceeds", (final_coin))
elif total < final_coin:
print("Sorry - you only entered",(total))
else:
print("correct")
goagain= input("Try again (y/n)?:")
if goagain == "y":
continue
elif goagain == "n":
print("Thanks for playing ... goodbye!" )
break
Store the value returned by input() in a variable.
Check that the string is not empty before calling int().
if it's zero, that's the empty string.
otherwise, try int()ing it.

How to break the program if there's a loop in a loop?

I have been trying to make a logarithm calculator on Python. I am just one step away from finishing it. Here is the code:
import math
print("Welcome to logarithm calculator")
while True:
try:
inlog = int(input("Enter any value greater than zero to lookup its logarithm to the base 10\n"))
outlog = math.log(inlog, 10)
print(outlog)
# Here, the program will ask the user to quit or to continue
print("Want to check another one?")
response = input("Hit y for yes or n for no\n")
if response == ("y" or "Y"):
pass
elif response == ("n" or "N"):
break
else:
#I don't know what to do here so that the program asks the user to quit or continue if the response is invalid?
except ValueError:
print("Invalid Input: Make sure your number is greater than zero and no alphabets. Try Again.")
After the else statement, I want the program to ask the user to respond again and again until it is a valid response as "y" or "Y" and "n" or "N". If I add another while loop here, it would work good to with pass statement if user enters "y". But it won't break the program when the user responds as "n" since it would land us in the outer loop.
So how to sort this out?
You can move that test to a different function:
def read_more():
while True:
print("Want to check another one?")
response = input("Hit y for yes or n for no\n")
if response == ("y" or "Y"):
return True
elif response == ("n" or "N"):
return False
else:
continue
And then in your function, just test the return type of this method:
while True:
try:
inlog = int(input("Enter any value greater than zero to lookup its logarithm to the base 10\n"))
outlog = math.log(inlog, 10)
print(outlog)
if read_more():
continue
else:
break
Note that, you can go into infinite loop, if the user keeps on entering wrong input. You can restrict him to upto some maximum attempts.
You can do something like this:
stop=False
while True:
try:
inlog = int(input("Enter any value greater than zero to lookup its logarithm to the base 10\n"))
outlog = math.log(inlog, 10)
print(outlog)
# Here, the program will ask the user to quit or to continue
print("Want to check another one?")
while True:
response = input("Hit y for yes or n for no\n")
if response == ("y" or "Y"):
stop = False
break
elif response == ("n" or "N"):
stop = True
break
else:
continue
if stop:
break
except ValueError:
print("Invalid Input: Make sure your number
you can define a boolean parameter outside the value with an initial value of 'false'. at the beginning of each run of the outer loop, you can check for this boolean value, if it is true, then also break the outer loop. after that, when you want to end outer loop inside the inner loop, just make the value true before breaking inner loop. this way outer loop will also break.
Try this:
import math
class quitit(Exception):
pass
print("Welcome to logarithm calculator")
while True:
try:
inlog = int(input("Enter any value greater than zero to lookup its logarithm to the base 10\n"))
outlog = math.log(inlog, 10)
print(outlog)
# Here, the program will ask the user to quit or to continue
print("Want to check another one?")
while True:
response = input("Hit y for yes or n for no\n")
if response == ("y" or "Y"):
break
elif response == ("n" or "N"):
raise quitit
except quitit:
print "Terminated!"
except ValueError:
print("Invalid Input: Make sure your number is greater than zero and no alphabets. Try Again.")
If the user inputs a number less than or equal to zero, this will produce an exception that you have not accounted for.
As far as breaking out of the loop, it isn't too nested that you cannot already break out. If you had a deeper nesting then I would suggest using the following template for breaking out of nested loops.
def loopbreak():
while True:
while True:
print('Breaking out of function')
return
print('This statement will not print, the function has already returned')
stop=False
while not stop:
try:
inlog = int(input("Enter any value greater than zero to lookup its logarithm to the base 10\n"))
outlog = math.log(inlog, 10)
print(outlog)
# Here, the program will ask the user to quit or to continue
print("Want to check another one?")
while True:
response = raw_input("Hit y for yes or n for no\n")
if response == ("y" or "Y"):
break
elif response == ("n" or "N"):
stop = True
break
except ValueError:
print("Invalid Input: Make sure your number")

Categories

Resources