I want to add some code to the end of this guessing game which will ask the user if they want to play again. If they say yes, the program will, I suppose, just run again from the beginning. I've tried multiple ideas, but none have worked. The closest was another if loop at the end. Thank you! x
print("Welcome to this guessing game!")
import random
x = random.randrange(50)
guess = int(input("I've picked an integer between 1 to 99. Guess what it is: "))
while x != "guess":
print
if guess < x:
print("Your guess is too low!")
guess = int(input("Guess again:"))
elif guess > x:
print("Your guess is too high!")
guess = int(input("Guess again:"))
else:
print ("You guessed the right number!")
Something like:
while True:
your code
if input("Continue? Y/N: ").lower() not in {"y", "yes"}:
break
At the end of every play, this gets input from the user, converts it to lower case, and sees if it's "y" or "yes". If it's not, the game breaks out of the loop, i.e. quits. Otherwise it keeps looping.
You could wrap your game in a function. And then on user say "yes", you invoke the function. And at the end of you game, reask the samequestion.
This is what function is made for.
Pseudo code:
function askUser(){
'Do you want to play'=>yes: launchGame, no:print("ok bye bye")
}
function myGame(){
//your game
askUser()
}
for example
import random
something="yes"
while(something == "yes"):
#your code...
#....
#from your code
else:
print ("You guessed the right number!")
something=input("Do you want to play again? (yes/no)")#input return str? I use raw_input all the time in p2.7
and this:
while x != "guess":
why to guess use " "?
x = random.randrange(50) so x never being a string "guess" its like while True: or while 1:
print("Welcome to this guessing game!")
import random
x = random.randrange(50)
guess = int(input("I've picked an integer between 1 to 99. Guess what it is: "))
while True:
if guess < x:
print("Your guess is too low!")
guess = int(input("Guess again:"))
elif guess > x:
print("Your guess is too high!")
guess = int(input("Guess again:"))
else:
print ("You guessed the right number!")
break
You are learning about the basics of python too little advice to read more books
x is the type of int and guess you use "" included "guess" he is not a variable name and become a string
Related
I need help changing the range and showing the user what the range is so they know if they are closer or not. I have given the description I have been given. On what I need to do . I have given the code that I have come up wit so far. Let me know if you need anything else from me.
Step 6 – Guiding the user with the range of values to select between
Add functionality so that when displaying the guess prompt it will display the current range
to guess between based on the user’s guesses accounting for values that are too high and too
low. It will start out by stating What is your guess between 1 and 100, inclusive?, but as
the user guesses the range will become smaller and smaller based on the value being higher
or lower than what the user guessed, e.g., What is your guess between 15 and 32,
inclusive? The example output below should help clarify.
EXAMPLE
----------------
What is your guess between 1 and 44 inclusive? 2
Your guess was too low. Guess again.
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
play()
#Part 1
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.")
print("\n")
def play():
''' Plays a guessing game'''
number = int(random.randrange(1,10))
guess = int(input("What is your guess between 1 and 10 inclusive ?: "))
number_of_guess = 0
while guess != number :
(number)
#Quit
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
#Guessing
if guess < number:
if guess < number:
guess = int(input("Your guess was too low. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
if guess > number:
if guess > number:
guess = int(input("Your guess was too high. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
#Winner
if guess == number :
number_of_guess += 1
print("Congratulations you won in " + str(number_of_guess) + " tries!")
again()
def again():
''' Prompts users if they want to go again'''
redo = input("Do you want to play again (Y or N)?: ")
if redo.upper() == "Y":
print("OK. Let’s play again.")
play()
elif redo.upper() == "N":
print("OK. Have a good day.")
sys.exit(0)
else:
print("I’m sorry, I do not understand that answer.")
again()
main()
What you'll need is a place to hold the user's lowest and highest guess. Then you'd use those for the range checks, instead of the hardcoded 1 and 11. With each guess, if it's a valid one, you then would compare it to the lowest and highest values, and if it's lower than the lowest then it sets the lowest value to the guess, and if it's higher than the highest it'll set the highest value to the guess. Lastly you'll need to update the input() string to display the lowest and highest guesses instead of a hardcoded '1' and '10'.
You need to simplify a lot your code. Like there is about 6 different places where you ask a new value, there sould be only one, also don't call method recursivly (call again() in again()) and such call between again>play>again.
Use an outer while loop to run games, and inside it an inner while loop for the game, and most important keep track of lower_bound and upper_bound
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
redo = "Y"
while redo.upper() == "Y":
print("Let’s play")
play()
redo = input("Do you want to play again (Y or N)?: ")
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.\n")
def play():
lower_bound, upper_bound = 0, 100
number = int(random.randrange(lower_bound, upper_bound))
print(number)
guess = -1
number_of_guess = 0
while guess != number:
guess = int(input(f"What is your guess between {lower_bound} and {upper_bound - 1} inclusive ?: "))
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
elif guess not in list(range(lower_bound, upper_bound)):
print("You're outside the range")
continue
number_of_guess += 1
if guess < number:
print("Your guess was too low")
lower_bound = guess
elif guess > number:
print("Your guess was too high")
upper_bound = guess
print("Congratulations you won in", number_of_guess, "tries!")
Implement the GuessNumber game. In this game, the computer
- Think of a random number in the range 0-50. (Hint: use the random module.)
- Repeatedly prompt the user to guess the mystery number.
- If the guess is correct, congratulate the user for winning. If the guess is incorrect, let the user know if the guess is too high or too low.
- After 5 incorrect guesses, tell the user the right answer.
The following is an example of correct input and output.
I’m thinking of a number in the range 0-50. You have five tries to
guess it.
Guess 1? 32
32 is too high
Guess 2? 18
18 is too low
Guess 3? 24
You are right! I was thinking of 24!
This is what I got so far:
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
while guessed == False:
userInput = int(input("Guess 1?"))
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + randomNumber + "!")
elif userInput>randomNumber:
print(randomNumber + "is too high.")
elif userInput < randomNumber:
print(randomNumber + "is too low.")
elif userInput > 5:
print("Your guess is incorrect. The right answer is" + randomNumber)
print("End of program")
I've been getting a syntax error and I don't know how to make the guess increase by one when the user inputs the wrong answer like, Guess 1?, Guess 2?, Guess 3?, Guess 4?, Guess 5?, etc...
Since you know how many times you're going through the loop, and want to count them, use a for loop to control that part.
for guess_num in range(1, 6):
userInput = int(input(f"Guess {guess_num} ? "))
if userInput == randomNumber:
# insert "winner" logic here
break
# insert "still didn't guess it" logic here
Do you see how that works?
You forgot to indent the code that belongs in your while loop. Also, you want to keep track of how many times you guessed, with a variable or a loop as suggested. Also, when giving a hint you probably want to print the number guessed by the player, not the actual one. E.g.,
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
count = 0
while guessed is False and count < 5:
userInput = int(input("Guess 1?"))
count += 1
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + randomNumber + "!")
elif userInput > randomNumber:
print(str(userInput) + " is too high.")
elif userInput < randomNumber:
print(str(userInput) + " is too low.")
if count == 5:
print("Your guess is incorrect. The right answer is" + str(randomNumber))
print("End of program")
You are facing the syntax error because you are attempting to add an integer to a string. This is not possible. To do what you want you need to convert randomNumber in each print statement.
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
while guessed == False:
userInput = int(input("Guess 1?"))
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + str(randomNumber) + "!")
elif userInput>randomNumber:
print(str(randomNumber) + "is too high.")
elif userInput < randomNumber:
print(str(randomNumber) + "is too low.")
elif userInput > 5:
print("Your guess is incorrect. The right answer is" + randomNumber)
print("End of program")
import random
arr=[]
for i in range(50):
arr.append(i)
answer=random.choice(arr)
for trial in range(5):
guess=int(input("Please enter your guess number between 0-50. You have 5
trials to guess the number."))
if answer is guess:
print("Congratulations....You have guessed right number")
break
elif guess < answer-5:
print("You guessed too low....Try again")
elif guess > answer+5:
print("You guessed too high..Try again")
else:
print("Incorrect guess...Try again please")
print("the answer was: "+str(answer))
Just a three things to add:
The "abstract syntax tree" has a method called literal_eval that is going to do a better job of parsing numbers than int will. It's the safer way to evaluate code than using eval too. Just adopt that method, it's pythonic.
I'm liberally using format strings here, and you may choose to use them. They're fairly new to python; the reason to use them is that python strings are immutable, so doing the "This " + str(some_number) + " way" is not pythonic... I believe that it creates 4 strings in memory, but I'm not 100% on this. At least look into str.format().
The last extra treat in this is conditional assignment. The result = "low" if userInput < randomNumber else "high" line assigns "low" of the condition is met and "high" otherwise. This is only here to show off the power of the format string, but also to help contain conditional branch complexity (win and loss paths are now obvious). Probably not a concern for where you are now. But, another arrow for your quiver.
import random
from ast import literal_eval
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
win = False
for guess_count in range(1,6):
userInput = literal_eval(input(f"Guess {guess_count}: "))
if userInput == randomNumber:
print(f"You are right! I was thinking of {randomNumber}!")
win = True
break
else:
result = "low" if userInput < randomNumber else "high"
print(f"{userInput} is too {result}")
if win:
print ("YOU WIN!")
else:
print("Better luck next time")
print("End of program")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
import random
computer=random.randint(1, 100)
guess=int(input("guess the number"))
if guess > 100:
print("your guess is too high")
elif guess < 1:
print("your guess is too low")
elif guess==computer:
print("well done!")
else:
print("you\'re wrong, guess again")
This is my current code. it's game where the computer randomly chooses a number and the player has to guess it. i have tried but i don't know how to ask the player if they want to play again and if they say yes how to restart it.
Wrap the game code to function and use while True to call it again and again
import random
def play():
computer=random.randint(1, 100)
guess=int(input("guess the number"))
if guess > 100:
print("your guess is too high")
elif guess < 1:
print("your guess is too low")
elif guess==computer:
print("well done!")
else:
print("you\'re wrong, guess again")
while True:
answer = input("do you want to play?")
if answer == 'yes':
play()
elif answer == 'no':
break
else:
print("dont understand")
Put all the if-else statements within one big while loop that keeps looping until the user guesses the number correctly. Then, after each losing outcome, give the user another chance to guess the number so that the loop has a chance to reevaluate the guess with the next iteration. In my modification below I decided to leave the last if-else statement outside of the loop because when the user guesses correctly, the code will break out of the loop to check if the guess is correct. Of course in this scenario it has to be correct so the user is told that he or she is right and the program terminates.
import random
computer=random.randint(1, 100)
guess=int(input("guess the number\n"))
while(guess != computer):
if guess > 100:
print("your guess is too high\n")
guess=int(input("guess the number again\n"))
elif guess < 1:
print("your guess is too low\n")
guess=int(input("guess the number again\n"))
if guess==computer:
print("well done!\n")
Just an overview of how you can do it.
initialize a variable play_again = "yes"
Place a while check on play_again:
while play_again == "yes":
Enclose all if statements and guess input in the while loop
Read the user input in a variable within but at the end of the loop:
play_again = raw_input("\n\nWant to play again?: ")
You can use a while loop for multiple iterations
import random
computer=random.randint(1, 100)
guess=int(input("guess the number"))
play_again = 'y'
while play_again == 'y':
if guess > 100:
print("your guess is too high")
elif guess < 1:
print("your guess is too low")
elif guess==computer:
print("well done!")
else:
print("you\'re wrong, guess again")
play_again = input("Want to play again(y/n): ")
You should put your code in while loop. Then after game ask user if they want to continue with input() function. If they say 'no' you can break the loop or set argument of while to False.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
import random
print("Hey there, player! Welcome to Emily's number-guessing game! ")
name=input("What's your name, player? ")
random_integer=random.randint(1,25)
tries=0
tries_remaining=10
while tries < 10:
guess = input("Try to guess what random integer I'm thinking of, {}! ".format(name))
tries += 1
tries_remaining -= 1
# The next two small blocks of code are the problem.
try:
guess_num = int(guess)
except:
print("That's not a whole number! ")
tries-=1
tries_remaining+=1
if not guess_num > 0 or not guess_num < 26:
print("Sorry, try again! That is not an integer between 1 and 25! ")
break
elif guess_num == random_integer:
print("Nice job, you guessed the right number in {} tries! ".format(tries))
break
elif guess_num < random_integer:
if tries_remaining > 0:
print("Sorry, try again! The integer you chose is a litte too low! You have {} tries remaining. ".format(int(tries_remaining)))
continue
else:
print("Sorry, but the integer I was thinking of was {}! ".format(random_integer))
print("Oh no, looks like you've run out of tries! ")
elif guess_num > random_integer:
if tries_remaining > 0:
print("Sorry, try again! The integer you chose is a little too high. You have {} tries remaining. ".format(int(tries_remaining)))
continue
else:
print("Sorry, but the integer I was thinking of was {}! ".format(random_integer))
print("Oh no, looks like you've run out of tries! ")
I'll try to explain this as well as I can... I'm trying to make the problem area allow input for guesses again after the user inputs anything other than an integer between 1 and 25, but I can't figure out how to. And how can I make it so that the user can choose to restart the program after they've won or loss?
Edit: Please not that I have no else statements in the problems, as there is no opposite output.
Use a function.Put everything in a function and call the function again if the user wants to try again!
This will restart the complete process again!This could also be done if the user wants to restart.
Calling the method again is a good plan.Enclose the complete thing in a method/function.
This will solve the wrong interval
if not guess_num > 0 or not guess_num < 26:
print("Sorry, try again! That is not an integer between 1 and 25! ")
continue
For the rest, you can do something like this
create a method and stick in your game data
def game():
...
return True if the user wants to play again (you have to ask him)
return False otherwise
play = True
while play:
play = game()
New to Python and trying to figure out what went wrong here. Making a simple game in which I have to guess the number that was randomly generated by the computer. Thanks for your help.
Here's what I have:
guessed == random.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
entered = 0
while entered != guessed
entered = raw_input("Enter your suggestion:")
entered = int(guessed_number)
if entered > guessed
print('Try less')
else
print('Try more')
print('You win!')
You're missing colons at the end of your conditionals and loops, aka while entered != guessed:. Add them to the end of the if and else lines as well. Also you are using the comparison (==) operator when assigning guessed instead of the assignment operator (=).
Also you will notice it prints "Try more" even when they guess the correct number, and then it will print "You win!". I'll leave this as an exercise to the new developer to fix.
entered = int(guessed_number)
makes no sense because you don't have a guessed_number variable. I think you meant to do
entered = int(raw_input("Enter your suggestion:")
Also, you're missing colons after your block starts at while, if, and else.
Welcome to Python 3.x! Here's the fixed code for you.
#Import Random
import random as r
#Create a random Number!
guessed = r.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
#Initiate variable --entered--
entered = 0
while (entered != guessed):
entered = int(input("Enter your suggestion:"))
#Fixed your if/else tree with correct indents and an elif.
if (entered > guessed):
print('Try less')
elif (entered <guessed):
print('Try more')
else:
print('You win!')
To add to the list:
guessed == random.randint(1,100)
should be
guessed = random.randint(1,100)
I'm sure you'd rather assign to guessed than compare it random.randint(1,100) and then throw the result of that comparison away.
entered = int(guessed_number)
It doesn't make any sense. There is no variable for 'guessed_number'.
I have edited your code to make it work:
import random
guessed = r.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
entered = 0
while (entered != guessed):
entered = int(input("Enter your suggestion:"))
if (entered > guessed):
print('Try less')
elif (entered <guessed):
print('Try more')
else:
print('You win!')
Hope that helps!
~Edward