Why wont this stop when 'n' is entered?
I've tried using break on the bottom else but I get errors doing that. That's a common problem I have with break. I have no idea why I'm thrown off with break.
import random
def game():
secret_num = random.randint(1, 10)
guesses = []
while len(guesses) < 5:
try:
guess = int(input("Guess a number between 1 and 10: "))
except ValueError:
print("{} isn't a number".format(guess))
else:
if guess == secret_num:
print("You got it! The number was {}.".format(secret_num))
break
elif guess < secret_num:
print("My number is higher than {}".format(guess))
else:
print("My number is lower than {}".format(guess))
guesses.append(guess)
else:
print("You didn't get it! My number was {}".format(secret_num))
play_again = input("Do you want to play again? Y/n ")
if play_again.lower() != 'Y':
game()
else:
print("Bye!")
game()
You convert play_again to a lower-case letter but compare it to an upper-case letter.
You could simply change it to:
if play_again.lower() != 'n': # 'y' was wrong, right?
game()
else:
print("Bye!")
return # works also without the explicit return but it makes the intention clearer.
Related
def set_number():
import random
return random.randint(1,500)
#This function plays the game
def number_guessing_game(number):
guess_counter = 0
guess = int(input("Enter a number between 1 and 500."))
while guess != number:
guess_counter += 1
if guess > number:
print(f"You guessed too high. Try Again!")
guess = int(input("Enter a number between 1 and 500."))
elif guess < number:
print(f"You guessed too low. Try Again!")
guess = int(input("Enter a number between 1 and 500."))
if guess == number:
print(f"You guessed the number! Good Job.!")
again = str(input("would you like to play again? Enter 'y' for yes or 'n' to close the game."))
def main():
print(f"Welcome to the Number Guessing Game!\n" +
f"You will have unlimited guesses. The number is between 1 and 500.\n" +
f"Good Luck!")
number = set_number()
guess_count = number_guessing_game(number)
main()
I am working on a simple game project for my coding class. I am not good at coding at all. I came up with this part of the program, I just cannot figure out how to loop the entire number_guessing_game function until the user enters 'n' to stop it, I can't use a break because we did not learn it in the class and I will receive a 0 if I use a break.
I tried nesting a while loop inside of the function but I know I did it wrong.
Instead of using break use return.
def main():
print(f"Welcome to the Number Guessing Game!\n" +
f"You will have unlimited guesses. The number is between 1 and 500.\n" +
f"Good Luck!")
while True:
number = set_number()
number_guessing_game(number)
again = input("would you like to play again? Enter 'y' for yes or 'n' to close the game.")
if again == 'n':
return
main()
You will probably want to remove the last line of the number_guessing_game function if you use this approach
First, your code is assuming the return of input is an integer that can be converted with int(). If you were to give it 'n' your program will crash.
Instead you could use the string class method isdigit() to see if the input was an integer value and then make a logical decision about it. Also note you do not need to convert the return from input to a str() as it is already a str type. You can confirm this with a print(type(input("give me something")))
guess = input("Enter a number between 1 and 500. 'n' to quit"))
if guess.isdigit():
[your code to check the value]
elif ('n' == guess):
return
else:
print(f"You entered an invalid entry: {guess}. Please re-enter a valid value")
If you dont like the idea of using 'return' you could change your while loop to look something like:
while(('n' != guess) or (guess != number)):
If you want the function body looping continuously you could have some code like:
def number_guessing_game(number):
exit_game = False
guess_counter = 0
while(exit_game != True):
guess = input("Enter a number between 1 and 500.))
guess_counter += 1
if guess.isdigit():
if int(guess) > number:
print("You guessed too high. Try Again!")
elif int(guess) < number:
print("You guessed too low. Try Again!")
elif int(guess) == number:
print("You guessed the number! Good Job.!")
again = input("would you like to play again? Enter 'y' for yes or 'n' to close)
if ('n' == again):
exit_game = True
else:
print("Error, please enter a valid value")
I'm making a guess the number game. My code is almost complete but I need to make it so that the program asks the player if they want to play again and then restarts. Could someone help me with how I should go about that? I tried making a new function ex. def game_play_again and then call the game_play() function but it's not reseting the attempts which leads to it not looping correctly.
This is my code right now
import random
MIN = 1
MAX = 100
attempts = 5
win = False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
#print game instructions
def game_start():
print(f"Im thinking of a number between {MIN} and {MAX}. Can you guess it within
{attempts} attempts? ")
input("Press enter to start the game ")
#process user input
def game_play():
global number, attempts, last_hint, win
while attempts > 0:
print()
print(f"You have {attempts} {'attempts' if attempts > 1 else 'attempt'} left.")
if attempts == 1:
print(f"This is your last chance. So i'll give you one more hint. Its's an {last_hint} number.")
while True:
try:
guess = int(input("Try a lucky number: "))
if guess in range(MIN, MAX+1):
break
else:
print(f"Please enter numbers between {MIN} and {MAX} only!")
except ValueError:
print("Plese enter numbers only!")
if guess == number:
win = True
break
if attempts == 1:
break
if guess > number:
if guess-number > 5:
print("Your guess is too high. Try something lower.")
else:
print("Come on you are very close. Just a bit lower.")
else:
if number-guess > 5:
print("Your guess is too low. Try something higher.")
else:
print("Come on you are very close. Just a bit higher.")
attempts -= 1
#print game results
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
game_start()
game_play()
game_finish(win)
You can simply reset your variables to initial values and then call game_play()
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
want_play_again = int(input("Want play again? [1-Yes / 2-No]"))
if want_play_again == 1:
game_play_again()
else:
print("Bye")
/
def game_play_again():
attempts = 0
win = False
game_play()
Within a while(True) loop, write a menu driven statement asking the user if they want to repeat. If they do, initialise values and call game methods. If they do not, break the loop.
pseudocode:
while(True):
choice = input('play again? y/n)
if choice=='y':
attempts, win = 5, False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
game_start()
game_play()
game_finish()
elif choice=='n':
break
else:
print('invalid input')
The above code should be in main, with all methods within its scope.
Better yet, in place of all the initializations, add an init() method declaring them and call them when necessary.
The indentation in the code you have submitted is faulty, so I'm not sure if a related error is involved.
How should I get the below loop to replay if the user types in an invalid response after being asked if they want to roll the dice again?
I can't get it to work without messing with the while loop. Here's what I have so far
# Ask the player if they want to play again
another_attempt = input("Roll dice again [y|n]?")
while another_attempt == 'y':
roll_guess = int(input("Please enter your guess for the roll: "))
if roll_guess == dicescore :
print("Well done! You guessed it!")
correct += 1
rounds +=1
if correct >= 4:
elif roll_guess % 2 == 0:
print("No sorry, it's", dicescore, "not", roll_guess)
incorrect += 1
rounds +=1
else:
print("No sorry, it's ", dicescore, " not ", roll_guess, \
". The score is always even.", sep='')
incorrect += 1
rounds +=1
another_attempt = input('Roll dice again [y|n]? ')
if another_attempt == 'n':
print("""Game Summary""")
else:
print("Please enter either 'y' or 'n'.")
I would suggest you do it with two while loops, and use functions to make the code logic more clear.
def play_round():
# Roll dice
# Compute score
# Display dice
# Get roll guess
def another_attempt():
while True:
answer = input("Roll dice again [y|n]?")
if answer == 'y':
return answer
elif answer == 'n':
return answer
else:
print("Please enter either 'y' or 'n'.")
def play_game():
while another_attempt() == 'y':
play_round()
# Print game summary
I finally got it working! But for some reason the program prints out the previous error statement (too high or too low or please enter values between...), along with the value error message if the user enters in something that the try catches. Could anyone explain why? Any shortening/cleanup is also welcome. Sorry for any errors. Thanks!
'''
This is a guessing game that finds a random number, and then
Tells the user if their guess is too low or too high. It will also give
Error messages for any numbers outside of the accepted range, and will also
Give errors for anything not an integer.
At the end (if the user guesses correctly) it will ask if the
User would like to play again or quit.
'''
import random
def start_here():
print("Welcome to the guessing game!")
play_game()
def play_game():
random_number = random.randrange(1, 100)
correct = False
user_guess = True
while not correct:
try:
user_guess = int(input("Enter your guess: "))
except ValueError:
print("Please only use integers")
if user_guess > 100 or user_guess < 1:
print("Please only enter numbers between 1 and 100!")
elif user_guess > random_number:
print("Too high, try again. ")
elif user_guess < random_number:
print("Too low, try again! ")
elif user_guess == random_number:
break
if user_guess == random_number:
replay = (input("Great! You guessed it! would you like to play again? y or n"))
if replay == "y":
start_here()
else:
print("See ya later!")
start_here()
Keep in mind that the code after the try-except block gets executed irrespective of whether an exception was thrown or not. If the except block gets invoked you want your code to skip through the rest of the statements in the while loop and continue at the next iteration of the loop, where the user is prompted for input again. This can be achieved by using the continue keyword in the except block like so:
try:
user_guess = int(input("Enter your guess: "))
except ValueError:
print("Please only use integers")
continue
The continue statement directs the interpreter to skip the remaining statements in the current iteration of the loop. The flow of control can then re-enter the loop or exit, depending on the loop condition.
Now that your code runs the way it is intended to, here is how you can make it more concise:
Firstly, there is a neat feature in Python which allows you to write conditions like not 1 <= user_guess <= 100. These conditions are much quicker to read, and you can replace this in your code.
Secondly, the start_here() function is redundant. You can easily replace play_game() in its place with a few modifications like so:
import random
def play_game():
print("Welcome to the guessing game!") #Modification here
random_number = random.randrange(1, 100)
correct = False
user_guess = True
while not correct:
try:
user_guess = int(input("Enter your guess: "))
except ValueError:
print("Please only use integers")
continue #Modification here
if not 1<=user_guess<=100: #Modification here
print("Please only enter numbers between 1 and 100!")
elif user_guess > random_number:
print("Too high, try again. ")
elif user_guess < random_number:
print("Too low, try again! ")
elif user_guess == random_number:
break
if user_guess == random_number:
replay = (input("Great! You guessed it! would you like to play again? y or n"))
if replay == "y":
play_game() #Modification here
else:
print("See ya later!")
play_game() #Modification here
or you could entirely replace the play_game() function with a while loop like so:
import random
replay = 'y' #Modification here
while replay == 'y': #Modification here
print("Welcome to the guessing game!")
random_number = random.randrange(1, 100)
correct = False
user_guess = True
while not correct:
try:
user_guess = int(input("Enter your guess: "))
except ValueError:
print("Please only use integers")
continue
if not 1<=user_guess<=100 :
print("Please only enter numbers between 1 and 100!")
elif user_guess > random_number:
print("Too high, try again. ")
elif user_guess < random_number:
print("Too low, try again! ")
elif user_guess == random_number:
break
if user_guess == random_number: #Modification here
replay = input("Great! You guessed it! would you like to play again? y or n")
print("See ya later!") #Modification here
Here:
while not correct:
try:
user_guess = int(input("Enter your guess: "))
except ValueError:
print("Please only use integers")
if user_guess > 100 or user_guess < 1:
# etc
If the user input is not a valid int, you display an error message but still proceed with testing the value against the random number. You should instead skip the rest of the loop, or extract the part getting the user input into it's own loop. As a general rule, one function should do only one thing, then you use another function to control the whole program's flow:
def get_num():
while True:
try:
user_guess = int(input("Enter your guess: ").strip())
except ValueError:
print("Please only use integers")
continue
if user_guess > 100 or user_guess < 1:
print("Please only enter numbers between 1 and 100!")
continue
return user_guess
def again():
replay = input("would you like to play again? y or n"))
return replay.strip().lower() == "y"
def play_game():
random_number = random.randrange(1, 100)
while True:
user_guess = get_num()
if user_guess > random_number:
print("Too high, try again. ")
elif user_guess < random_number:
print("Too low, try again! ")
else:
# if it's neither too high nor too low then it's equal...
break
# no need to test again, we can only get here when the user
# found the number
print("Great! You guessed it!")
def main():
print("Welcome to the guessing game!")
while True:
play_game()
if not again():
break
if __name__ == "__main__":
main()
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)?: ")