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!")
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+
This is the code:
print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))
guess_limit = 5
guess_counter = 1
out_of_guesses = False
print("You have", str(guess_limit - guess_counter), "tries left")
while not out_of_guesses:
guess = int(input("Enter guess: "))
if guess == Magic_number:
print("Well done you got it!!")
exit(0)
elif guess < Magic_number:
print("That number is too small, try again")
elif guess > Magic_number:
print("That number is too high try again")
guess_counter += 1
print("You have", str(guess_limit - guess_counter), "tries left")
# exit clause
if guess_limit == guess_counter:
out_of_guesses = True
print("Game over, sorry")
And even if I get it correct on the first try it does something like this:
Welcome to my guessing game can you get the magic number
hint,
it's between 1 and 100
47
Enter your guess: 47
You have 4 tries left
Enter guess: 47
Well done you got it!!
As you can see even though i was correct on the first try it wasn't counted. Ps.(That is what shows up at the bottom of my screen where the code is executed.)
You do not check if guess == Magic_number after reading input on line 4.
Like this
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))
if guess == Magic_number:
print ("You won")
exit(0)
You don't need all those variables, check this.
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess_limit = 5
guess_counter = 0
while True:
guess = int(input("Enter guess: "))
if guess == Magic_number:
print("Well done you got it!!")
exit(0)
elif guess < Magic_number:
print("That number is too small, try again")
elif guess > Magic_number:
print("That number is too high try again")
guess_counter += 1
print(f"You have {guess_limit - guess_counter} tries left")
if guess_counter == guess_limit:
print("Game over, sorry")
exit(0)
My problem with the program is that i it will tell me my variable called "guess" isnI will
Here is the n of saying "Guess lower".
Traceback (most recent call last):
F
guess = int(input("Guess a number: "))
ValueError: invalid literal for int() with base 10: 'hfdg'
And here is the code for the program
import random
random_number = random.randint(1, 10)
tries = 0
print ("Enter yes, or no")
saysalse
while not says_yes or not says_no:
player_input = input("Would you like to play a game?: ")
player_input = player_input.lower()
if player_input == "yes":
says_yes = True
break
elif player_input == "no":
says_no = True
print("See you next time.")
exit()
if says_yes:
print("Ok, great.")
print("How this game works is that you are going to guess a number ranging from 1-10 \
and if you guess it right then you win")
guess = int(input("Guess a number: "))
choose a number between 1-10.")
guess = int(input("Guess a number: "))
while int(guess) != int(random_number):
tries to guess the number.")
Look here:
if says_yes:
print("Ok, great.")
print("How this game works is that you are going to guess a number ranging from 1-10 \
and if you guess it right then you win")
guess = int(input("Guess a number: "))
while guess > 10 or guess < 1:
print("Please choose a number between 1-10.")
guess = int(input("Guess a number: "))
Pycharm says that error, because it can happen that "says_yes" ist False and the input will noch appear, then guess is not defined, i know you have an exit() but pycharm is pernickety.
HERE YOUR FULL CODE:
import random
random_number = random.randint(1, 10)
tries = 0
print("Enter yes, or no")
says_yes = False
says_no = False
while not says_yes or not says_no:
player_input = input("Would you like to play a game?: ")
player_input = player_input.lower().strip()
if player_input == "yes":
says_yes = True
break
elif player_input == "no":
says_no = True
print("See you next time.")
exit()
else:
print("You have to think about it again!")
if says_yes:
print("Ok, great.")
print("How this game works is that you are going to guess a number ranging from 1-10 and if you guess"
" it right then you win")
while True:
raw_guess = input("Guess a number: ")
try:
guess = int(raw_guess)
except ValueError:
print("Try it again, this was not a number!")
else:
if guess > 10 or guess < 1:
print("Please choose a number between 1-10.")
elif guess > random_number:
print("Guess lower")
tries += 1
elif guess < random_number:
print("Guess higher")
tries += 1
else:
break
print("It took you " + str(tries) + " tries to guess the number.")
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()
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