Guessing Game - Prompt the user to play again - python

I'm making a guessing game, but I want to add another line of code where the user can play again after, but I don't know where to start.
print ("Welcome to the Number Guessing Game in Python!")
# Initialize the number to be guessed
number_to_guess = 7
# Initialize the number of tries the player has made
count_number_of_tries = 1
# Obtain their initial guess
guess = int (input ("Please guess a number between 1 and 10: "))
while number_to_guess != guess:
print ("Sorry wrong number!")
# Check to see they have not exceeded the maximum number of attempts if so break out of loop
if count_number_of_tries == 3:
break
elif guess < number_to_guess:
print ("Your guess was lower than the number.")
else:
print ("Your guess was higher than the number.")
# Obtain their next guess and increment number of attempts
guess = int(input ("Please guess again: "))
count_number_of_tries += 1
# Check to see if they did guess the correct number
if number_to_guess == guess:
print ("Well done you won!")
print ("You took" + str(count_number_of_tries) + "attempts to complete the game.")
else:
print ("Sorry, you lose")
print ("The number you needed to guess was " + str(number_to_guess) + "." )
print ("Game Over.")
I dont know if the code should be at the bottom or in between somewhere.
I also want to remove the break if possible.

Great idea! In my mind, there are two ways of continuously asking the user to play until they enter something that will let you know they want to stop like 'q', 'quit', or 'exit'. First you could nest all of your current code a while loop (indent and write 'while(): before the code), or turn your current code into a function, and call it over and over again until the user enters the exit command
Ex:
lets say i can print hello world like this
# your game here
but now I want to keep printing it until the user enters 'quit'
user_input = '.' # this char does not matter as long as it's not 'quit'
while user_input != 'quit': # check if 'user_input' is not 'quit'
# your game here
user_input = input('Press any key to continue (and enter) or write "quit" to exit: ') # prompt user to enter any key, or write quit

Put all of that code in a game() function.
Underneath, write
while True:
game()
play=int(input('Play again? 1=Yes 0=No : '))
if play == 1:
pass
else:
break
print("Bye!")

I think this should do it, just a basic while loop
playAgain = 'y'
while playAgain == 'y':
print ("Welcome to the Number Guessing Game in Python!")
# Initialize the number to be guessed
number_to_guess = 7
# Initialize the number of tries the player has made
count_number_of_tries = 1
# Obtain their initial guess
guess = int (input ("Please guess a number between 1 and 10: "))
while number_to_guess != guess:
print ("Sorry wrong number!")
# Check to see they have not exceeded the maximum number of attempts if so break out of loop
if count_number_of_tries == 3:
print("You've guessed more than three times, you're pretty bad")
elif guess < number_to_guess:
print ("Your guess was lower than the number.")
else:
print ("Your guess was higher than the number.")
# Obtain their next guess and increment number of attempts
guess = int(input ("Please guess again: "))
count_number_of_tries += 1
# Check to see if they did guess the correct number
if number_to_guess == guess:
print ("Well done you won!")
print ("You took " + str(count_number_of_tries) + " attempts to complete the game.")
else:
print ("Sorry, you lose")
print ("The number you needed to guess was " + str(number_to_guess) + "." )
print ("Game Over.")
playAgain = (input ("Type y to play again, otherwise press enter: "))
print("Goodbye gamer")

You can add a while loop to the outermost layer that randomly generates the value of number_to_guess on each startup. And ask if you want to continue at the end of each session.
import random
print("Welcome to the Number Guessing Game in Python!")
number_range = [1, 10]
inp_msg = "Please guess a number between {} and {}: ".format(*number_range)
while True:
# Initialize the number to be guessed
number_to_guess = random.randint(*number_range)
# Initialize the number of tries the player has made
count_number_of_tries = 1
# Obtain their initial guess
guess = int(input(inp_msg))
while number_to_guess != guess:
print("Sorry wrong number!")
# Check to see they have not exceeded the maximum number of attempts if so break out of loop
if count_number_of_tries == 3:
break
elif guess < number_to_guess:
print("Your guess was lower than the number.")
else:
print("Your guess was higher than the number.")
# Obtain their next guess and increment number of attempts
guess = int(input("Please guess again: "))
count_number_of_tries += 1
# Check to see if they did guess the correct number
if number_to_guess == guess:
print("Well done you won!")
print("You took" + str(count_number_of_tries) + "attempts to complete the game.")
else:
print("Sorry, you lose")
print("The number you needed to guess was " + str(number_to_guess) + ".")
if input("Do you want another round? (y/n)").lower() != "y":
break
print("Game Over.")

Related

Implementing "Guess the number" game

This is my first post in StackOverFlow and I'm sure that I can find for 100% percent an answer for it, but I'd really like to start my adventure with programming and know that this community might help me with it.
My questions are:
I wrote that first piece of code but I'd like to add here a function where the user writes the guess number bigger than the first one.
I am troubled with adding the additional function if for this situation - I do understand that it wouldn't suppose to be if, but elif.
Is anyone has any idea how to suppose to look-alike??
import random
top_range = input("Write a number bigger then 0: ")
if top_range.isdigit() or top_range[0] == "-":
top_range = int(top_range)
if top_range <= 0:
print('Write a number bigger then 0')
quit()
else:
print('Write a number bot a word')
quit()
random_number = random.randint(0, top_range)
guesses = 0
while True:
guesses += 1
user_guess = input("Guess the number : ")
if user_guess.isdigit():
user_guess = int(user_guess)
else:
print('Write another number.')
continue
if user_guess == random_number:
print('You did it!')
break
else:
if user_guess < random_number:
print('The number is bigger then that')
else:
print('The number is smaller than that')
print('You did it in', guesses, "guesses!")
Add a first if, then use elif for the other choices. I've also simplify a bit the first if
while True:
guesses += 1
user_guess = input("Guess the number : ")
if not user_guess.isdigit():
print('Write another number.')
continue
user_guess = int(user_guess)
if user_guess > top_range:
print("That is higher than top range, try again")
elif user_guess == random_number:
print('You did it!')
break
elif user_guess < random_number:
print('The number is bigger then that, try again')
else:
print('The number is smaller than that, try again')

Why does my Python user input code not consider the input correct

I am new to coding and want to train and do my own thing with user inputs. The User Input code does not work. It is a number guessing game. When I guess the right number, it says "Incorrect".
import random
while True:
intro = input("Hello! Want to play a game?(Y or N)")
if intro.lower() == "y" or intro.lower() == "yes":
time.sleep(0.1)
print("Let's play a number-guessing game!")
max_num_in = input("Pick a big number")
max_num = int(max_num_in)
time.sleep(0.1)
min_num_in = input("Now pick a smaller number")
min_num = int(min_num_in)
rndm_num = int(random.randrange(min_num,max_num,1))
print(rndm_num)
rndm_in = input("Guess a number between the maximum and minumum numbers!")
if rndm_num == rndm_in:
print("Whoo hoo! You did it! You guessed the number! The number was" + str(rndm_num))
elif rndm_in != rndm_num:
print("Whoops, wrong number. Please try again.(Trials left = 2)")
rndm_in1 = input("Guess again!")
if rndm_in1 == rndm_num:
print("Whoo hoo! You did it! You guessed the number! The number was" + str(rndm_num))
elif rndm_in1 != rndm_num:
print("You didn't get it right. Please try again (Trials left = 1)")
rndm_in2 = input("Guess again!")
if rndm_in2 == rndm_num:
print("Whoo Hoo! You finally did it! The number was" + str(rndm_num))
elif rndm_in2 != rndm_num:
print("Incorrect. The number was " + str(rndm_num))
elif intro.lower() == "n" or intro.lower() == "no":
print("Alright. Bye")
Your inputs are strings convert them to int by using int() function
"5"!=5
This one looks suspicious:
if rndm_num == rndm_in:
It looks like you getting a str as rndm_in but your rndm_num is an int.
Try:
if rndm_num == int(rndm_in):

Guess the number program in Python - after typing how many times I want to play, game is not working

I am working on Guess the number program in Python. I had to make some enhancements to it and add:
User has a default limit of 15 guesses (when enter key is hit)
Ask for a limit to the number of guests - this part doesn't work in my code.
import random
def main():
print('\n'*40)
print('Welcome to the Guess number game!')
print('\n'*1)
player_name = input("What is your name? ") print('\n'*1)
try_again = 'y'
number_of_guesses = 0
error = 0
guess_limit = 15
while ((try_again == 'y') or (try_again == 'Y')):
try:
limit = input('You have 15 default guesses to start. Do you like to have different number of guesses? ')
if limit.upper() == 'Y':
limit = input('How many times would you like to play? ') # after I input number of guesses I cannot proceed to the actual game
else:
number = random.randint(1, 100)
while (guess_limit != 0):
guess = int(input("Enter an integer from 1 to 100: "))
if (guess < 1) or (guess > 100):
print("ERROR! Integer must be in the range 1-100! ")
else:
if guess < number:
print ("Guess is low!")
elif guess > number:
print ("Guess is high!")
else:
print('\n'*1)
print ("YOU WIN! You made " + str(number_of_guesses) + " guesses.")
break
number_of_guesses += 1
guess_limit -= 1
print(guess_limit, 'guesses left')
print()
else:
#if guess_limit == 0:
print ("YOU LOSE! You made " + str(number_of_guesses) + " guesses.")
except ValueError:
print('ERROR: Non-numeric data. Please enter valid number!')
print('\n'*1)
try_again = input("Play again? Enter 'Y' or 'y' for yes: ")
print('\n'*1)
main()
OUTPUT: Welcome to the Guess number game!
What is your name? d
You have 15 default guesses to start.
Do you like to have different number of guesses? y
How many times would you like to play? 3 # after this I have
Play again? Enter 'Y' or 'y' for yes: # this result
How can I change that code?
you have to use
guess_limit = input("How many times would you like to play? ")
and then you have to check if it is blank or not by simple if conditions
if guess_limit == "":
guess_limit = 15
Below is the full code with well commented.
# import only system from os
from os import system
import random
def main():
# For clearing the screen
system('cls')
# For adding blank line
blank_line = '\n'*1
print('Welcome to the Guess number game!')
print(blank_line)
player_name = input("What is your name? ")
print(blank_line)
# to start the loop initially try_again = 'y'
try_again = 'y'
# Count number of guesses by player
number_of_guesses = 0
while (try_again.lower() == 'y'):
# Get number of times player want to guess
guess_limit = input("How many times would you like to play? ")
# If player enter nothing and hit enter
# then default value of guess_limit is 15
if guess_limit == "":
guess_limit = 15
# Convert the guess_limit to int data type
guess_limit = int(guess_limit)
# If user inputted number then go inside this try block
# else go inside except block
try:
# Generate random number in betwee 1-99 to be guess by the player
number = random.randint(1, 99)
# Loop untill there is no guesses left
while (guess_limit != 0):
# Player guess
guess = int(input("Enter an integer from 1 to 99: "))
# Check for valid number i.e number should be betwee 1 - 99
while ((guess < 1) or (guess > 99)):
guess = int(
input("ERROR! Please enter an integer in the range from 1 to 99: "))
# Check for High and low guess
if guess < number:
print("Guess is low")
elif guess > number:
print("Guess is high")
# If it is neither high nor low
else:
print(blank_line)
print("YOU WIN! You made " +
str(number_of_guesses) + " guesses.")
# To get out of the loop
break
# decrement the guess_limit by 1 on every iteration
guess_limit -= 1
print(guess_limit, 'guesses left')
# Increment number of guesses by the player
number_of_guesses += 1
print()
# If guess_limit is equal to 0, it means player have not guessed the number
# And player lose
if guess_limit == 0:
print("YOU LOSE! You made " +
str(number_of_guesses) + " guesses.")
except ValueError:
print('ERROR: Non-numeric data. Please enter valid number!')
print(blank_line)
# Ask again to play again
# If player enter anything other than 'Y' or 'y' then exit the game
try_again = input("Play again? Enter 'Y' or 'y' for yes: ")
print(blank_line)
main()

Asking the user if they want to play again [duplicate]

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

How can i create a game that alternated between players?

I am looking to make a guess my number game that alternates between the user guessing and the Al but I'm not sure how to do it. I already have a guess my number game code but I don't know what to add to make it change from user to computer.
#Guess my number
import random
print ("Welcome to the guess my number game")
print ("***********************************")
print ("I will choose a random number between 1-100")
print ("and you must guess what it is.")
print ()
number = random.randint(1,100)
guesses = 0
guess = 0
while guess != number:
guess = int(input("Take a guess: "))
guesses=guesses+1
if guess > number:
print("Lower...")
continue
elif guess < number:
print ("Higher...")
else:
print ("Well done you have guessed my number and it took you", guesses,"guesses!")
input ("\n\nPress enter to exit.")
guesses = [[],[]]
for player in itertools.cycle([0,1]):
if player == 0:
guess = int(input("Take a guess: "))
else:
guess = computer_guess()
guesses[player].append(guess)
if guess == number:
break
if guess > number:
print("Lower...")
continue
elif guess < number:
print ("Higher...")
print "Player %d wins"%player
print "It Took %d guesses"%len(guesses[player])
maybe what you are looking for

Categories