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
Related
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.")
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()
import random
print("Welcome to the game, Guess a Number! \n")
print("There will be 3 rounds to the game.")
print("During the first round, you will be asked to choose a number between 0-10.")
print("You will have 3 chances to guess the correct number. If you can't, the game will start over.")
print("Good Luck! \n")
def ReadyToPlay():
NumberGuesses = 0 #sets numerb of guesses
MaxGuesses = 3 #sets maximum times you can guess
number = random.randint(0,10)
print("Hi stranger, I am thinking of a number between 0 and 10.")
while NumberGuesses < MaxGuesses:
guess = int(input("Take a guess: ")) #prompt to take guess
NumberGuesses = NumberGuesses + 1 #keeps number count
if guess < number:
print("Sorry, your guess is to low.")
elif guess > number:
print("Sorry, your guess is to high.")
if guess == number: #stops current loop and continues the rest of my statment
break
if guess == number:
NumberGuesses = str(NumberGuesses)
print('\n')
print("Congrats Stranger! You have guessed the correct number.")
print("Moving on to round two. \n")
NumberGuesses = 0 #sets numerb of guesses
MaxGuesses = 3 #sets maximum times you can guess
number = random.randint(0,50)
print("Now, I am thinking of a number between 0 and 50.")
while NumberGuesses < MaxGuesses:
guess = int(input("Take a guess: ")) #prompt to take guess
NumberGuesses = NumberGuesses + 1 #keeps number count
if guess < number:
print("Sorry, your guess is to low.")
elif guess > number:
print("Sorry, your guess is to high.")
if guess == number:
break
if guess == number:
NumberGuesses = str(NumberGuesses)
print('\n')
print("You're on fire!")
print("Now you have arrived to the last round.")
print("You will have to choose 2 numbers, in order to complete the game. \n")
NumberGuesses = 0 #sets numerb of guesses
MaxGuesses = 6 #sets maximum times you can guess
number = random.randint(0,100)
print("The first number I am thinking of is between 0 and 100")
while NumberGuesses < MaxGuesses:
guess = int(input("Take a guess: "))
NumeberGuesses = NumberGuesses + 1
if guess < number:
print("Sorry, your guess is to low.")
elif guess > number:
print("Sorry, your guess is to high.")
if guess == number:
break
if guess == number:
print('\n')
print("Your guessA is correct.")
print("Now, guess the second number.")
NumberGuesses = 0 #sets numerb of guesses
MaxGuesses = 6 #sets maximum times you can guess
number = random.randint(0,100)
print("The second number I am thinking of is between 0 and 100")
while NumberGuesses < MaxGuesses:
guess = int(input("Take a guess: ")) #prompt to take guess
NumberGuesses = NumberGuesses + 1 #keeps number count
if guess < number:
print("Sorry, your guess is to low.")
elif guess > number:
print("Sorry, your guess is to high.")
if guess == number:
break
if guess == number:
print('\n')
print("Your guessB is also correct.")
print("Congratulations on finishing the game!!!")
if guess != number:
number = str(number)
print("\n")
print("The number I was thinking of was: " + number)
replay = input("Do you want to play again (y/n)?: ")
if replay == "y":
ReadyToPlay()
ReadyToPlay
i need help creating 3 levels, being able to replay the game from each level and keeping track of my wins and losses. i am a beginner so it needs to be very easy to code. So far I have created three parts to the game which all work. But when I need to reply, the game starts from the beginning and not from where u have reached up until
Use a container that will hold the state of the game; update the state during game play. Add a parameter to ReadyToPlay() that is optional. The parameter accepts a container that holds the current game state. If passed when the function is called, use it to start the game from there. Pass the state container for a replay.
You might want to consider having your function return the guess and current state then move the if guess != number: code outside of the function.
I have the following code for a random number guessing game:
import random
number = random.randint(1,100)
name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")
guess1 = input()
if guess1 == number:
print ("Good job, you got it!")
while guess1 != number:
if guess1 > number:
print ('your guess is too high')
if guess1 < number:
print ('your guess is too low')
which throws the error that > or < cannot be used between str and int.
What should I do so it doesn't trigger that error?
There are two errors in your code.
You need to convert the input for guess1 from a string (by default) to an integer before you can compare it to the number (an integer).
The while loop will never stop since you are not letting the user input another value.
Try this:
import random
number = random.randint(1,100)
name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")
guess1 = int(input()) # convert input from string to integer
while guess1 != number:
if guess1 > number:
print ('your guess is too high. Try again.')
elif guess1 < number:
print ('your guess is too low. Try again.')
guess1 = int(input()) # asks user to take another guess
print("Good job, you got it!")
You can make use of a while loop here - https://www.tutorialspoint.com/python/python_while_loop.htm
The logic should be:
answer_is_correct = False
while not answer_is_correct :
Keep receiving input until answer is correct
I hope this works for you:
import random
myname = input('Hello, what is your name?')
print('Well',myname,'am thinking of a number between 1 and 100')
number = random.randint(1,100)
guess = 0
while guess < 4:
guess_number = int(input('Enter a number:'))
guess += 1
if guess_number < number:
print('Your guess is to low')
if guess_number > number:
print('Your guess is to high')
if guess_number == number:
print('Your guess is correct the number is',number)
break
if guess == 4:
break
print('The number i was thinking of is',number)
from random import randint
print("you wanna guess a number between A to B and time of guess:")
A = int(input("A:"))
B = int(input("B:"))
time = int(input("time:"))
x = randint(1, 10)
print(x)
while time != 0:
num = int(input("Enter: "))
time -= 1
if num == x:
print("BLA BLA BLA")
break
print("NOPE !")
if time == 0:
print("game over")
break
Code in Python 3 for guessing game:
import random
def guessGame():
while True:
while True:
try:
low, high = map(int,input("Enter a lower number and a higher numer for your game.").split())
break
except ValueError:
print("Enter valid numbers please.")
if low > high:
print("The lower number can't be greater then the higher number.")
elif low+10 >= high:
print("At least lower number must be 10 less then the higher number")
else:
break
find_me = random.randint(low,high)
print("You have 6 chances to find the number...")
chances = 6
flag = 0
while chances:
chances-=1
guess = int(input("Enter your guess : "))
if guess<high and guess>low:
if guess < find_me:
print("The number you have entered a number less then the predicted number.",end="//")
print("{0} chances left.".format(chances))
elif guess > find_me:
print("The number you have entered a number greater then the predicted number.",end="//")
print("{0} chances left.".format(chances))
else:
print("Congrats!! you have succesfully guessed the right answer.")
return
else:
print("You must not input number out of range")
print("{0} chances left.".format(chances))
print("The predicted number was {0}".format(find_me))
You can conditions within the while loop to check if its right. It can be done the following way.
import random
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 100)
print('Well, ' + myName + ', I am thinking of a number between 1 and 100.')
inputNumber = int(raw_input('Enter the number')
while inputNumber != number:
print "Sorry wrong number , try again"
inputNumber = int(raw_input('Enter the number')
print "Congrats!"
from random import *
def play_game():
print("Let's play a number guessing game")
# Selecting a random number between 1 and 100
number = randint(1, 100)
choice = int(input("I am thinking of a number between 1 and 100. Could you guess what it is? "))
# Guide the user towards the right guess
# Loop will continue until user guesses the right number
while choice != number:
if choice < number:
choice = int(input("Too low. Can you try again? "))
elif choice > number:
choice = int(input("Too high. Can you try again? "))
continue_game = input("You guessed it right! Would you like to play it again? (Y/N) ")
# Restart the game if user wishes to play again
if continue_game == "Y":
print("--" * 42)
play_game()
else:
print("Thanks for playing :)")
exit(0)
play_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