I want this program to allow users to restart the game when they are through or exit it if they do not want to play the game again, but I cant figure out how to do it. Can you please help me with the code that makes the program do that?
Please correct me if I mistype the code below.
Below is the code of the game I have written using python:
import random
secret_number = random.randrange(1, 101)
guess = 0
tries = 0
while guess != secret_number:
guess = int(input("Guess a number: "))
tries = tries + 1
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print("You got it!")
print("Number of tries: ", tries)
userInput = input("Enter 'R' to restart or 'X' to exit").capitalize()
if userInput == "R":
#code to restart the game goes here
elif gameReply == "X":
#code to exit the game goes here
Your indentation was wrong.
You can try to use a smaller random.randrange() while you are testing your program.
After the game finishes, what do you want to do if user inputs, say, hello? In the following program, you basically continue if it is not x or X and play again.
Here is the fixed version:
import random
import sys
while True: # outer game loop
print('Welcome to the game.')
secret_number = random.randrange(1, 5)
guess = 0
tries = 0
while guess != secret_number:
guess = int(input("Guess a number: "))
tries = tries + 1
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print("You got it!")
print("Number of tries: ", tries)
userInput = input("Enter 'R' to restart or 'X' to exit").capitalize()
if userInput == "X":
print('Goodbye.')
sys.exit(-1) # exits the program
To restart the game: Well, you can declare a function that initializes the game, and then you call it if you want to restart.
To exit:
sys.exit()
I have a similar game already coded: you can have a look at it HERE. It was my first python code
For restart, you can just set tries to zero and continue since you are in a loop.
if userInput == "R":
tries = 0
continue
For exit, sys.exit() is a winner.
elif gameReply == "X":
sys.exit()
You can use sys.exit() to stop the script and wrap your code into a method so you can call it again when the user wants to restart. Also, use raw_input rather than input as input is expecting Python code.
For example:
import random
import sys
def my_game():
secret_number = random.randrange(1, 101)
guess = 0
tries = 0
while guess != secret_number:
guess = int(input("Guess a number: "))
tries = tries + 1
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print("You got it!")
print("Number of tries: ", tries)
userInput = raw_input("Enter 'R' to restart or 'X' to exit").capitalize()
if userInput == "R":
my_game()
elif userInput == "X":
sys.exit()
my_game()
Related
I am creating a python random counting game. I'm having some difficulties with certain parts. Can anyone here review my code? I'm having difficulty with trying to implement a try/except and a tries function that counts the user's attempts. I also have to verify that the number is a legitimate input and not a variable. So far I've gotten this far and its coming along good. I just need alittle help ironing out a few things. Thanks guys you rock.
Here is the code below:
import random
def main():
start_game()
play_again()
tries()
print("Welcome to the number guessing game")
print("I'm thinking of a number between 1 and 50")
def start_game():
secret_number = random.randint(1,50)
user_attempt_number = 1
user_guess = 0
while user_guess != secret_number and user_attempt_number < 5:
print("---Attempt", user_attempt_number)
user_input_text = input("Guess what number I am thinking of: ")
user_guess = int(user_input_text)
if user_guess > secret_number:
print("Too high")
elif user_guess < secret_number:
print("Too low")
else:
print("Right")
user_attempt_number += 1
if user_guess != secret_number:
print("You ran out of attempts. The correct number was"
+str(secret_number)+ ".")
def play_again():
while True:
play_again = input("Do you want to play again?")
if play_again == 'yes':
main()
if play_again =='no':
print("Thanks for playing")
break
def tries():
found= False
max_attempts=50
secret_number = random.randint(1, 50)
while tries <= max_attempts and not found:
user_input_text = start_game()
user_guess_count=+1
if user_input_text == secret_number:
print("It took you {} tries.".format(user_guess_count))
found = True
main()
Try this method:
def play_game():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
count = 1 #new line
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
count = count+
i recently started learning python and my friend from work who is a programmer gave me a simple challenge to write a "guess the number" style game.
So i came up with something as follows:
import random
print("Hello, welcome to GUESS THE NUMBER game")
run = True
def again():
global run
playagain = str(input("Would you like to play again? Type y/n for yes or no: "))
if playagain == "y":
run = True
elif playagain == "n":
run = False
while run:
guess = int(input("Guess the number between 1 and 10: "))
num1 = random.randint(1, 10)
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
again()
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")
My problem is that after the user has chosen to play again, the numbers sometimes dont register and go out of whack. For example you input 5 and it says too low, but if you input 6 it says too high! I don't seem to be dealing in float numbers so they should be whole, any ideas where i went wrong?
Thanks in advance and very excited to learn more on the subject
Your problem is that you're regenerating the random number every time.
num1 = random.randint(1, 10)
Instead, maybe put the guess and check logic inside it's own loop.
while True:
guess = int(input("Guess the number between 1 and 10: "))
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
break # leave the while True loop
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")
again()
You are calculating the random number on each iteration of the loop. Therefore every time you guess the random number changes.
import random
print("Hello, welcome to GUESS THE NUMBER game")
run = True
def again():
global run
playagain = str(input("Would you like to play again? Type y/n for yes or no: "))
if playagain == "y":
run = True
elif playagain == "n":
run = False
num1 = random.randint(1, 10)
while run:
guess = int(input("Guess the number between 1 and 10: "))
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
again()
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")
sorry if the formatting is a little screwy. first question asked on here.
from random import randint
num=randint(1,9) #generates random number
print("welcome to the guessing game! the number is between 1 and 9.")
tries=0
player_input=int(input("enter your guess"))
while num != player_input:
if player_input == " ":
print("Invalid entry.")
player_input=int(input("please entera valid number between 1 and 9"))
if player_input < num:
tries = tries +1
print("too low")
print(" ")
player_input=int(input("guess again "))
if player_input > num:
tries = tries +1
print("too high!")
print(" ")
player_input = int(input("guess again "))
if player_input == num:
tries = tries +1
print("You Got It!!")
print(" ")
print("you have tried",tries,"times")
next
newg=("yes") # = new game
endg=("no") # = stop game
print("To start a new game enter ", newg, ". Or to stop the game, enter ", endg)
user=(input("Y/N")
# the syntax error shows up here. i have tries different variable instead of ui3 such as new_game_a, ng, U_I, ui, etc.i have fixed that problem, but now it is the " : " at the end of the line. i tried many variations in spacing. but still no lee-way with error.
if user == "no":
print("close window")
else user == "yes":
tries=0
player_input=int(input("enter your guess"))
while num != player_input:
if player_input == " ":
print("Invalid entry.")
player_input=int(input("please enter valid number between 1 and 9"))
if player_input < num:
tries = tries +1
print("too low")
print(" ")
player_input=int(input("guess again "))
if player_input > num:
tries = tries +1
print("too high!")
print(" ")
player_input = int(input("guess again "))
if player_input == num:
tries = tries +1
print("You Got It!!")
print(" ")
print("you have tried",tries,"times")
PLEASE help me if possible, thanks.
an example of the error message!!
There's most likely more than this (the extra closing parentheses required which may have just been a typo), but I see that your syntax is incorrect.
else user == "yes":
Should be replaced with:
elif user == "yes":
You're missing a closing ) on the line defining user and else doesn't take another condition:
user=(input("Y/N"))
if user == "no":
print("close window")
else:
tries=0
player_input=int(input("enter your guess"))
I'm making a guessing game where you have the option of an easy medium and hard mode but when I adjusted my code so that the display changes from 100 to 1,000,000 I get an error saying:
File "C:/Users/Zach Hirschman/AppData/Local/Programs/Python/Python35-32/GuessGame.py", line 38, in main
if guess > randomNumber:
UnboundLocalError: local variable 'randomNumber' referenced before assignment
I can't seem to figure out how I can fix this, any help would be appreciated.
"""
Zach Hirschman
12/20/2017
GuessGame.py
This program asks the user to guess a number
"""
import random
def main():
difficulty = input("Enter a difficulty level: 'easy','medium', or 'hard'
: ")
print("At any time, type 'hint' to get a hint")
if difficulty == "easy":
randomNumber = random.randint(1,100)
elif difficulty == "medium":
randumNumber = random.randint(1,10000)
elif difficulty == "hard":
randomNumber = random.randint(1,1000000)
found = False
while not found:
if difficulty == "easy":
guess = int(input("Guess a number between 1 and 100"))
if guess > randomNumber:
print("Too high")
elif guess == randomNumber:
print("Thats correct!!")
found = True
else :
print("Too Low")
elif difficulty == "medium":
guess = int(input("Guess a number between 1 and 10000"))
if guess > randomNumber:
print("Too high")
elif guess == randomNumber:
print("Thats correct!!")
found = True
else :
print("Too Low")
elif difficulty == "hard":
guess = int(input("Guess a number between 1 and 1000000"))
if guess > randomNumber:
print("Too high")
elif guess == randomNumber:
print("Thats correct!!")
found = True
else :
print("Too Low")
x = input("would you like to play again? Type 'yes' or 'no': ")
if x == "yes":
main()
else:
print("See you later!")
main()
I think it was just a scoping issue. For randomNumber variable to be available in the while loop, the while loop has to be within the same function that the variable is declared in (eg. main()): then they have the same "scope".
Initialising randomNumber before the if statements is not needed and will make no difference. That is usually done before for or while loops (as you did with found = False). randomNumber was not being initialised because it depended on "difficulty", which was out of scope.
Note that after defining it, the function has to be called by main(). In your code main() wasn't running, only the ifs/while parts were as they were written outside the function.
import random
def main():
difficulty = input("Enter a difficulty level: 'easy','medium', or 'hard' : ")
print("At any time, type 'hint' to get a hint")
if difficulty == "easy":
randomNumber = random.randint(1,100)
elif difficulty == "medium":
randomNumber = random.randint(1,10000)
elif difficulty == "hard":
randomNumber = random.randint(1,1000000)
found = False
while not found:
if difficulty == "easy":
guess = int(input("Guess a number between 1 and 100"))
if guess > randomNumber:
print("Too high")
elif guess == randomNumber:
print("Thats correct!!")
found = True
else :
print("Too Low")
main()
The other options are:
moving everything out of the function, which will work fine by gets complicated for longer programs
adding a return value to main() and binding it to randomNumber. This would also require the same for the difficulty variable, so would be better to refactor into multiple smaller functions.
Finally, randomNumber had a typo - that didn't cause the problem though.
Another approach which simplifies a little your solution:
import random
difficulty_thresholds = {
"easy" : 100,
"medium" : 10000,
"hard" : 1000000
}
wants_to_continue = True
while wants_to_continue:
difficulty = input("Enter a difficulty level: 'easy','medium', or 'hard': ")
maximum_number = difficulty_thresholds.get(difficulty, 100)
randomNumber = random.randint(1, maximum_number)
found = False
while not found:
guess = int(input("Guess a number between 1 and {}: ".format(maximum_number)))
if guess > randomNumber:
print("Too high")
elif guess == randomNumber:
print("That's correct!!!")
found = True
else:
print("Too Low")
do_we_continue = input("Would you like to play again? Type 'yes' or 'no': ")
wants_to_continue = do_we_continue == "yes"
print("See you later!")
This question already has answers here:
Ask the user if they want to repeat the same task again
(2 answers)
Closed 4 years ago.
Basically it's a guessing game and I have literally all the code except for the last part where it asks if the user wants to play again. how do I code that, I use a while loop correct?
heres my code:
import random
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
while guess == number:
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == yes:
guess= eval(input("Enter your guess between 1 and 1000 "))
if again == no:
break
One big while loop around the whole program
import random
play = True
while play:
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
play = False
separate your logic into functions
def get_integer_input(prompt="Guess A Number:"):
while True:
try: return int(input(prompt))
except ValueError:
print("Invalid Input... Try again")
for example to get your integer input and for your main game
import itertools
def GuessUntilCorrect(correct_value):
for i in itertools.count(1):
guess = get_integer_input()
if guess == correct_value: return i
getting_close = abs(guess-correct_value)<10
if guess < correct_value:
print ("Too Low" if not getting_close else "A Little Too Low... but getting close")
else:
print ("Too High" if not getting_close else "A little too high... but getting close")
then you can play like
tries = GuessUntilCorrect(27)
print("It Took %d Tries For the right answer!"%tries)
you can put it in a loop to run forever
while True:
tries = GuessUntilCorrect(27) #probably want to use a random number here
print("It Took %d Tries For the right answer!"%tries)
play_again = input("Play Again?").lower()
if play_again[0] != "y":
break
Don't use eval (as #iCodex said) - it's risky, use int(x). A way to do this is to use functions:
import random
import sys
def guessNumber():
number=random.randint(1,1000)
count=1
guess= int(input("Enter your guess between 1 and 1000: "))
while guess !=number:
count+=1
if guess > (number + 10):
print("Too high!")
elif guess < (number - 10):
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = int(input("Try again "))
if guess == number:
print("You rock! You guessed the number in ", count, " tries!")
return
guessNumber()
again = str(input("Do you want to play again (type yes or no): "))
if again == "yes":
guessNumber()
else:
sys.exit(0)
Using functions mean that you can reuse the same piece of code as many times as you want.
Here, you put the code for the guessing part in a function called guessNumber(), call the function, and at the end, ask the user to go again, if they want to, they go to the function again.
I want to modify this program so that it can ask the user whether or not they want to input another number and if they answer 'no' the program terminates and vice versa. This is my code:
step=int(input('enter skip factor: '))
num = int(input('Enter a number: '))
while True:
for i in range(0,num,step):
if (i % 2) == 0:
print( i, ' is Even')
else:
print(i, ' is Odd')
again = str(input('do you want to use another number? type yes or no')
if again = 'no' :
break