so I am trying to make a guessing game on my own and when the game ends I hope it will prompt the player if he wants to play again by typing yes or no like this:
Guess a number between 1 to 10: 7
YOU WON!!!!
Do you want to continue playing? (y/n) y
Guess a number between 1 to 10: 7
YOU WON!!!!
Do you want to continue playing? (y/n) n
Thank you for playing!
I managed to get the game working but I can't play the game again. I am stuck here:
guess = int(input("Guess a number between 1 and 10: "))
while True:
if guess > num:
print("Too high, try again!")
guess = int(input("Guess a number between 1 and 10: "))
elif guess < num:
print("Too low, try again!")
guess = int(input("Guess a number between 1 and 10: "))
else:
print("You guessed it! You won!")
replay = input("Do you want to continue playing? (y/n) ")
if replay == "y":
**what to insert here???**
else:
break
I don't know what to type inside the if statement that will return my code to the top of the loop if the user press "y" and allows me to restart the game.
Any help will be appreciated! Please do not give me the entire solution but try to give me hints so I can solve this by myself! Thank you!
you can use the continue statement as it returns the control to the beginning of the while loop, in python.
You have to use two while loops. The first one to decide whether the player wants to play again or not and the second one is to get guess from the user until the user does the correct guess.
while True:
guess = int(input("Guess a number between 1 and 10: "))
wantToPlay = False
while True:
if guess > num:
print("Too high, try again!")
guess = int(input("Guess a number between 1 and 10: "))
elif guess < num:
print("Too low, try again!")
guess = int(input("Guess a number between 1 and 10: "))
else:
print("You guessed it! You won!")
replay = input("Do you want to continue playing? (y/n) ")
if replay == "y":
wantToPlay = True
else:
break
if wantToPlay == False:
break
Related
So I have been watching various videos online with regards to a python3 guessing game, but I can't get it to work. I think the logic is sound, but it just won't work as intended. I keep getting the same error. For example, if the number_guess is 90 and I type in 100 for the user_guess, then I receive a message telling me the number is too high, as intended. But if I then enter a follow up number of 8 for example, it will still tell me the user_guess is too high. Similarly, if I entered 90 which is the number_guess, I still receive an error that the number is too high.
here's the code
number_guess = int(input("Enter the integer for the player to guess:"))
user_guess = int(input("Enter your guess."))
count = 1
while user_guess != number_guess:
count += 1
if user_guess == number_guess:
print("You guessed it in", count, "tries")
elif user_guess < number_guess:
int(input("Too low - try again:"))
elif user_guess > number_guess:
int(input("Too high - try again:"))
On line 9 and 11, you're not saving the new guess into the variable user_guess(the variable that you're checking).
so for every while loop it will keep checking against the same number over and over again.
solution:
user_guess = int(input("Too low - try again:"))
Another thing to look at is your while function. It runs while a certain condition is met. It runs when user_guess is not equal to number_guess. Becuase of this, if you guess the number corrrectly, the line saying "you guessed it in x tries" will never execute.
Here's my final code. I had to make some edits for formatting. Thank you again!
print("Enter the integer for the player to guess.")
number_guess = int(input())
print("Enter your guess.")
user_guess = int(input())
count = 1
while user_guess != number_guess:
count += 1
if user_guess < number_guess:
print("Too low - try again:")
user_guess = int(input())
elif user_guess > number_guess:
print("Too high - try again:")
user_guess = int(input())
if user_guess == number_guess:
print("You guessed it in", count, "tries.")
Could you, please, help me to understand how should I use try/except block and count tries at the same time.
Here is the code without try/except block (it seems it's working fine):
import random
number = random.randint(1, 10)
tries = 3
name = input('Hi! What is your name?\n')
answer = input(f'{name}, let\'s play a game! Yes or No?\n')
if answer == 'Yes':
print(f'But be aware: you have only {tries} tries!\nReady?')
chat = input('')
print('Ok, guess a number from 1 to 10!')
while tries != 0:
choice = int(input('Your choice: '))
tries -= 1
if choice > number:
print('My number is less!')
elif choice < number:
print('My number is higher!')
else:
print('Wow! You won!')
break
print(f'You have {tries} tries left.')
if tries == 0 and choice != number:
print(f'Sorry, {name}, you lost... It was {number}. Try next time. Good luck!')
else:
print('No problem! Let\'s make it another time...')
This one is with try/except block.. Not sure where should I place 'choice' variable and where count 'tries', it keeps looping and looping:
import random
number = random.randint(1, 10)
tries = 3
name = input('Hi! What is your name?\n')
answer = input(f'{name}, let\'s play a game! Yes or No?\n')
if answer == 'Yes':
print(f'But be aware: you have only {tries} tries!\nReady?')
chat = input('')
print('Ok, guess a number from 1 to 10!')
while True:
try:
choice = int(input('Your choice: '))
if 0 < choice < 11:
while tries != 0:
tries -= 1
if choice > number:
print(f'My number is less!')
elif choice < number:
print(f'My number is higher!')
else:
print('Wow! You won!')
break
print(f'You have {tries} tries left.')
if tries == 0 and choice != number:
print(f'Sorry, {name}, you lost... It was {number}. Try next time. Good luck!')
else:
print(f'Hey {name}, I said, print a number from 1 to 10!')
except ValueError:
print('Please, enter a number!')
else:
print('No problem! Let\'s make it another time...')
Thanks!
I am trying to make a simple guess the number program in python. When I run this code,an error generates saying that,"local variable 'chance' referenced before assignment". I looked up for a solution on internet but I could not rectify my error. Please help with this problem. How can I use the variable globally which is declared inside a function?
I am beginner in programming, so plese explain in simple words.
Here is the code..
Since I am a beginner,I will be pleased if my code can be rectified
import random
def Random():
chance = 3
number = random.randint(0,20)
return chance
return number
def main():
while chance > 0:
UserInput = int(input('Guess the number: '))
if UserInput == number:
print('You have guesses the secret number!')
elif UserInput > 20 and UserInput < 0:
print('Your guess is out of range!\n Try again!')
else:
chance -= 1
if chance == 1:
print('You are out of chances!')
print('Wrong Guess!\nTry again!')
print(f'You have {chance} chances left!')
Random()
main()
playAgain = input('Want to play again? ')
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
Random()
main()
else:
print('Thanks for playing!')
You can return a list or a tuple to the outside word:
import random
def example():
chance = 3
number = random.randint(0,20)
return (chance, number) # return both numbers as a tuple
chance, randNr = example() # decomposes the returned tuple
print(chance, randNr)
prints:
3, 17
There are more bugs in your program, f.e.:
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
is always True and you'll never be able to leave the game. Better would be
if playAgain.lower() in {'yes', 'yeah'}:
etc.
Here is a working example for your programs purpose:
import random
while True:
chances = 3
number = random.randint(0,20)
while chances > 0:
guess = int(input("Guess number: "))
if guess == number:
print("Correct")
break
else:
chances -= 1
print("Wrong, ", chances, " more tries to get it right.")
if chances == 0:
print ("You failed")
if not input("Play again? ")[:1].lower() == "y":
break
print("Bye.")
Read about tuples
Output:
Guess number: 1
Wrong, 2 more tries to get it right.
Guess number: 4
Correct
Play again? y
Guess number: 1
Wrong, 2 more tries to get it right.
Guess number: 2
Wrong, 1 more tries to get it right.
Guess number: 3
Wrong, 0 more tries to get it right.
You failed
Play again? n
Bye.
import random
def Random():
chance = 3
number = random.randint(0,20)
main(chance,number)
def main(chance,number):
while chance > 0:
UserInput = int(input('Guess the number: '))
if UserInput == number:
print('You have guesses the secret number!')
elif UserInput > 20 and UserInput < 0:
print('Your guess is out of range!\n Try again!')
else:
chance -= 1
if chance == 1:
print('You are out of chances!')
print('Wrong Guess!\nTry again!')
print('You have',chance,'chances left!')
Random()
playAgain = input('Want to play again? ')
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
Random()
else:
print('Thanks for playing!')
So I am making a guess the number game in Python 3
After the whole process, I want my while loop to generate another number so that I can start the game again without running the program again.
Please let me know what I'm doing wrong, and if you could provide me with some insight on how to use the while loop, it'll be much appreciated.
Here's the code :
import random
while True:
number = random.randint(1, 1000)
count = 0
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
Not sure if the code you pasted was a typo (on indentation), but I may have accidentally changed your implementation.
Regardless, you should just add another while loop, and a break condition when the user gets it right.
import random
while True:
number = random.randint(1, 1000)
count = 0
while True: # Added, and added another layer of indentation
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
break # Added
In doing so, the code will keep looping to guess the correct number until they are correct. And then generate a new number to guess. However this code will never end unless you add another breaking condition (such as setting a flag the while loop will check to break out of the outer loop.
I wrote some quick code that prompts the user if they want to continue playing or not and then loops through and continues the game with a new number if they want to. I also fixed some minor bugs. Your count kept getting reset in the loop so it would always say you found it in 1 try.
import random
def promptUser():
user_continue = input("Do you want to continue playing? y/n")
if (user_continue == 'y'):
number = random.randint(1, 10)
game(0, number)
def game(count, number):
while True:
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
promptUser()
break
promptUser()
I am a real newbie to Python, I am taking it for GCSE at my school and I have been given an assignment to complete. I completed all of the requirements for this simple code but am not sure how to repeat it. Could someone please show me a simple way of repeating the code?
Thanks
import random
Random = random.randint(1,100)
Guess = int(input("Please guess a number between 1 and 100: "))
counter = 1
while Guess != Random:
if Guess > Random:
print("Too high")
Guess = int(input("Please guess the number: "))
else:
print("Too low")
Guess = int(input("Please guess the number: "))
counter += 1
print("Well Done:")
print("You took:",counter, "Guesses")
Easiest way of doing it would be to put it in a while True loop with a conditional break:
import random
while True:
Random = random.randint(1,100)
Guess = int(input("Please guess a number between 1 and 100: "))
counter = 1
while Guess != Random:
if Guess > Random:
print("Too high")
Guess = int(input("Please guess the number: "))
else:
print("Too low")
Guess = int(input("Please guess the number: "))
counter += 1
print("Well Done:")
print("You took:",counter, "Guesses")
choice = input("Would you like to continue? y/n")
if choice == "n":
break
Note, randint(1,100) will return a number from 1-99 inclusive, and you are actually asking the user for a guess 2-99 inclusive the way you have phrased it.