Python Syntax error while making a little game - python

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

Related

There is a game to find a random number base on condition?

I would like to generate a random number (1,100), however, the random number is bigger than the user idea changes the range of random EX: computer random =36 but users answer is 87 so tell the computer my answer is bigger than your guess, the computer change its range (36,100) and vice versa.
this program runs just one time and doesn't repeat asking for select more randomly.
Thank you so much
from random import randint
a = int(1)
b = int(100)`enter code here`
guess = randint(a,b)
print(guess)
answer = input ("your idea:")
while answer != "done":
if answer == "big":
a = int(guess)
guess = randint(a,100)
print(guess)
if answer == "small":
b = int(guess)
guess = randint(1, b)
print(guess)
else:
answer == "done"
print("your guess number ", guess, "is right")
break
else:
answer == "done"
print("your guess number ", guess, "is right")
break
The break is indented outside the else. So it'll break regardless of the value of the answer. Just indent the break inside the else and it'll be fine

Why am I get a syntax error here when I am equating a variable containing an integer and a variable containing a numerical input from the user?

I am just learning the basics of Python and created a number guessing game. I want the user to be able to guess the number as many times as possible until they guess correctly. I did this through a while loop but the code, "else guess == a:" near the end is giving me a syntax error. I am confused because the while loop ensures that the input guess is an integer by the if statement,
if guess.isdigit():
guess = int(guess)
Please help
import random
a = random.randint(1,10)
print("this is a number guessing game")
question_one = input("Would you like to play? Yes or No?:")
if question_one == "Yes":
print("Let's go!")
else:
print("That sucks!")
exit()
guess = None
while guess != a:
guess = (input("Alright, guess a number from 1-10"))
if guess.isdigit():
guess = int(guess)
if guess > a:
guess = int(input("Guess lower!"))
elif guess < a:
guess = int(input("Guess higher!"))
else guess == a:
print("you got it!")
else doesn't let you define a condition. else will execute if all other conditionals return false. You should change that last else to elif. Or you can simply leave out the conditional guess == a all together. If it is not greater than or less than, the only other thing it can be is equal to.
If you have the last else, the code inside the else will be executed if any other condition goes false. So I think if you change the last else with an elif we work properly.
An else statement contains the block of code that executes if the conditional expression in all your if or elif statements is false. Hence in your case you're supposed to use the elif statement instead of else. See the following:
elif guess == a:
print("you got it!")

Python Random Guessing Game

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")

Is it possible to change a variable’s value while it is in the `while` loop?

I was trying to write code to solve a question:
Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. Keep track of how many guesses the user has taken, and when the game ends, print this out.
The code that I wrote was:
import sys
import random
x=random.randint(1,9)
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
for i in range (10):
z=input()
if int(z)<x:
print('Too low. Please try again.')
elif int(z)>x:
print('Too high. Please try again.')
elif int(z)==x:
print('You guessed it right!')
if i==0:
print('It took you a single turn! Nice')
else:
print('it took you ' + str(i+1)+' turns.')
print('Do you want to play again? Yes or No?')
j=input()
if j.lower()=='yes':
print('Okay, Please enter a number between 1 and 9 including the extremes.')
pass
else:
sys.exit()
Here’s what it looks like when run:
Hello there! Please enter a number between 1 and 9 including the extremes.
4
Too high. Please try again.
3
Too high. Please try again.
2
You guessed it right!
it took you 3 turns.
Do you want to play again? Yes or No?
yes
Okay, Please enter a number between 1 and 9 including the extremes.
6
Too high. Please try again.
4
Too high. Please try again.
2
You guessed it right!
it took you 6 turns.
Do you want to play again? Yes or No?
See, the code gives perfect results when the for loop is first executed. It gives weird results when we try to run this “game” for the second time by saying yes when it asks us the question: Do you want to play again? Yes or No?.
Is it possible to put i=0 when python reaches the 4th last line and the for loop starts again from i=0 so that I do not get weird results?
Or is there some other easier method remove this bug?
You can use while loop for the task. And you should add exception handling method for getting an input.
import random
cond = True
while cond:
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
x=random.randint(1,9)
for i in range (10):
z=int(input())
if int(z)<x:
print('Too low. Please try again.')
elif int(z)>x:
print('Too high. Please try again.')
elif int(z)==x:
print('You guessed it right!')
import sys
if i==0:
print('It took you a single turn! Nice')
else:
print('it took you ' + str(i+1)+' turns.')
print('Do you want to play again? Yes or No?')
j=input()
if j.lower()=='yes':
break
else:
cond = False
sys.exit()
First of all, you pick the random number only once, so it's always going to be the same.
Secondly, your game should be in while loop instead of for loop (if you want to allow player to restart after they guessed).
turns = 0
while True:
secret_number = random.randint(1,9)
print('Please enter a number between 1 and 9 including the extremes.')
guess = input()
turns += 1
if int(guess) < secret_number:
print("Too low")
elif int(guess) > secret_number:
print("Too high")
else:
print("You guessed in {} turn(s)".format(turns))
You continue the loop, and assign turns = 0 if user wants to keep playing, or you break if he doesn't.
All imports should go at the top of the file. Then, put a while loop so the player can restart after every game; this way, the variable x is also reset after every game. Also, the first print should be put outside the while and for loop, so it's printed only one time (the last if will print a new prompt at the beginning of a new game).
Your code at this point should look like this:
import random
import sys
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
while True:
x=random.randint(1,9)
for i in range (10):
z=input()
if int(z)<x:
print('Too low. Please try again.')
elif int(z)>x:
print('Too high. Please try again.')
elif int(z)==x:
print('You guessed it right!')
if i==0:
print('It took you a single turn! Nice')
else:
print('it took you ' + str(i+1)+' turns.')
print('Do you want to play again? Yes or No?')
j=input()
if j.lower()=='yes':
print('Okay, Please enter a number between 1 and 9 including the extremes.')
else:
sys.exit()
I'd write it like this, probably.
from itertools import count
from random import randint
def run_game():
random_value = randint(1, 9)
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
for i in count():
guess_string = input()
try:
guess = int(guess_string)
except ValueError:
print("Invalid value given for guess: {}".format(guess_string))
if guess < random_value:
print("Too low! Please try again.")
elif guess > random_value:
print("Too high! Please try again.")
else:
print('You guessed it right!')
if not i:
print('It took you a single turn! Nice')
else:
print('it took you {} turns.'.format(i + 1))
print('Do you want to play again? Yes or No?')
response_string = input()
return response_string.lower() == 'yes'
if __name__ == "__main__":
while run_game():
pass
But, for simplicity in understanding:
from itertools import count
from random import randint
if __name__ == "__main__":
playing = True
while playing:
random_value = randint(1, 9)
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
for i in count():
guess_string = input()
try:
guess = int(guess_string)
except ValueError:
print("Invalid value given for guess: {}".format(guess_string))
if guess < random_value:
print("Too low! Please try again.")
elif guess > random_value:
print("Too high! Please try again.")
else:
print('You guessed it right!')
if not i:
print('It took you a single turn! Nice')
else:
print('it took you {} turns.'.format(i + 1))
print('Do you want to play again? Yes or No?')
response_string = input()
if response_string.lower() != 'yes':
playing = False
break
The whole of your code is embedded within the for loop and the counter is never reset. If you want to reset i within the for loop, you have to define it outside the for loop so that it has a global scope.

How Do I Make This Python Guessing Game Start Again?

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

Categories