Simple Guess My Number Game in Python - invalid syntax - python

I try to make a simple guessing game with the "Python programming for absolute beginner" book. Game should generate random number from 0 to 10, then take player's guesses and print "Too high!", if the guessed number is too high, or "Too low!" if the number is too low. After each guess, game adds 1 to the number of guesses. It ends, when the player's guess is correct and displays number of guesses taken.
My code is exactly the same, as code in the book, but when I run it in IDLE, I get "invalid syntax" error on "tries += 1" line. When I delete this line, the error happens on the next line etc. When I run it from file, it just opens and closes immediately. I use Python 3.4.1.
import random
number = random.randint(0,10)
player_guess = int(input("What's your guess?"))
tries = 1
while player_guess != number:
if player_guess > number:
print("Too high!")
else:
print("Too low!")
player_guess = int(input("What's your guess?")
tries += 1
print("Congrats!")
print(tries)
input("\n\nPress any key...")

You're missing a closing parentheses ) on the above line to complete the int conversion.

Related

Where should I put an if function for my Guessing game?

Right now, I am working on Chapter 3 of the book Python for the absolute beginner.
One of the challenges at the end of chapter 3 is to "Modify the Guess My Number game so that the player has a limited number of guesses" and that if the player fails to get the correct amount of guesses, a message should be displayed.
The code looks like this:
# Guess My Number
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money
import random
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")
# set the initial values
the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1
# guessing loop
while guess != the_number:
if guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
input("\n\nPress the enter key to exit.")
From what I can see so far, I need to add a variable that counts how many lives a player has, which is set to an amount at the beginning, like 10 and an if command should be used to make sure that, when the player uses all their lives, the message is displayed.
However, I am unsure where to place the if command in the existing code.
Well, If I were you I would make a game loop instead of the guessing loop. And then I would just break the game loop when I reach the guessing limit. However if you wanna keep your code you can use this.
while guess != the_number:
if tries == 3: # Replace 3 with the limit you'd like to use
print("You lost :(")
exit()
else:
if guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
Also in your case don't use break, it will still cause to print in the end the winning msg
(the spacing might be a little bit off so u may need to fix it)
After you say tries+=1, put an if statement. Your code should look like this:
if tries>3:
print("Game Over")
break()
import random
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")
# set the initial values
the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1
while tries < 8:
if guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
break
elif guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
if tries == 8:
print("You failed to guess my number")
input("\n\nPress the enter key to exit.")
You can also do it this way

Beginner 'Guess my number' program. while loop not breaking when correct number guessed or when out of guesses

So I'm learning python and I'm trying to code a simple guess my number game where you only have 5 guesses or the game ends. Im really having trouble with the while loop not recognising that the number has been guessed or the guess limit has been reached. Is there a better way of formatting my functions also. Thanks for any and all help, first time using this site.
# Guess my number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money
import random
GUESS_LIMIT = 5
# functions
def display_instruct():
"""Display game instructions."""
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.")
print("\nHARDCORE mode - You have 5 tries to guess the number!\n")
def ask_number(question, low, high, step = 1):
"""Ask for a number within a range."""
response = None
while response not in range(low, high, step):
response = int(input(question))
return response
def guessing_loop():
the_number = random.randint(1, 100)
guess = ask_number("\nTake a guess:", 1, 100)
tries = 1
while guess != the_number or tries != GUESS_LIMIT:
if guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = ask_number("Take a guess:", 1, 100)
tries += 1
if tries == GUESS_LIMIT:
print("\nOh no! You have run out of tries!")
print("Better luck next time!")
else:
print("\nYou guessed it! The number was", the_number)
print("And it only took you", tries, "tries!")
def main():
display_instruct()
guessing_loop()
# start the program
main()
input("\n\nPress the enter key to exit")
Your while condition will be true as long as you haven't hit the guess limit.
while guess != the_number or tries != GUESS_LIMIT:
You should join those conditions with and, not or. The way you have it now, the entire condition will be true because tries != GUESS_LIMIT is true, even if guess != the_number is false.
Or you can break your cycle explicitly with break statement. But previous answer is more correct in a sense you should really understand conditions you're setting for the loop.

Python returning untrue values?

I'm a newbie to Python, and I was working on a number guessing game in Python. However, when I set up the parameters:
import random
numberchosen = random.randint(0,100)
numberchosenstr = str(numberchosen)
print ("Let's play a number game")
numberguessed = input("Guess a number ")
print ("You guessed " + numberguessed)
if numberguessed > '100':
print ("You guessed too high, choose a number below 100")
if numberguessed < '0':
print ("You guessed too low, choose a number above 0")
if numberguessed != numberchosen:
print ("wrong")
But, when I run the module, and choose the number 5 for instance, or any number that is within the correct range yet not the correct number, it always returns
Let's play a number game
Guess a number 5
You guessed 5
You guessed too high, choose a number below 100
wrong
So, my question is, why does Python return the >100 error, and what are some ways to fix it?
You're comparing strings, which is done lexicographically (i.e. alphabetically, one character at a time). But even if one were an int, strings are always greater than numbers. You need to take the quotes off your comparison number, and call int() on your input, like so:
numberguessed = int(input("Guess a number ")) # convert to int
print ("You guessed {}".format(numberguessed)) # changed this too, since it would error
if numberguessed > 100: # removed quotes
print ("You guessed too high, choose a number below 100")
if numberguessed < 0: # removed quotes
print ("You guessed too low, choose a number above 0")

Modfying current code

My next task is modifying current code. In a previous exercise, I've written a basic application that covers a numbers guessing game. The code is as follows: -
# Guess My Number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money
import random
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")
# set the initial values
the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1
# guessing loop
while guess != the_number:
if guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
input("\n\nPress the enter key to exit.")
My task is to modify this so that there is a limited number of goes before a failure message is given to the user. Thus far, the chapter has covered "if, elif, else, for, loops, avoiding infinte loops." As such, I'd like to limit my response to these concepts only. For loops are covered next chapter.
What have I tried?
So far, I've tried amending the block in another while loop using 5 goes and the tries variable but it doesn't seem to work.
# guessing loop
while tries < 6:
guess = int(input("Take a guess: "))
if guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")
elif guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
break
tries += 1
input("You didn't do it in time!")
input("\n\nPress the enter key to exit.")
Any pointers or highlighting what I've missed would be appreciated plus any explanation as to what I'd missed. Teaching myself to think programatically is aslo proving tricky.
What doesn't work
When I run it, the loop conditions't don't appear to work. My idle feedback is as follows.
This means my question can be summarised as
Where is my looping logic broken?
>>> ================================ RESTART ================================
>>>
Welcome to 'Guess My Number'!
I'm thinking of a number between 1 and 100.
Try to guess it in as few attempts as possible.
Take a guess: 2
Take a guess: 5
Higher...
You didn't do it in time!
Press the enter key to exit.
The problem is that your break statement is not indented to be included in your elif:
elif guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
break
Thus, the loop always stops after the first iteration. Indent the break to be included within the elif and it should work.
The break is not in the conditional.
Add a tab before it.

How do i make my program move on to the next elif in python

import random
print"hello what is your name?"
name = raw_input()
print"hello", name
print"wanna play a game? y, n"
choice = raw_input()
if choice =='y':
print'good lets start a number guessing game'
elif choice =='n':
print'maybe next time'
exit()
random.randint(1,10)
number = random.randint(1,10)
print'pick a number between 1-10'
numberofguesses = 0
guess = input()
while numberofguesses < 10:
if guess < number:
print"too low"
elif guess > number:
print"too high"
elif guess == number:
print'your correct the number is', number
break
if guess == number:
print'CONGRATS YOU WIN THE GAME'
when i enter my guess into the program it only gives me one output for example
i enter 8
programs output is "too high"
but when i guess again the output is blank, how do i fix this?
hello what is your name?
ed
hello ed
wanna play a game? y, n
y
good lets start a number guessing game
pick a number between 1-10
2
too low
>>> 5
5
>>> 3
3
>>> 2
2
>>>
I think this is what you want:
numberofguesses = 0
while numberofguesses < 10:
guess = input() #int(raw_input("Pick a number between 1 and 10: ")) would be much better here.
numberofguesses+=1
if guess < number:
print "too low"
elif guess > number:
print "too high"
elif guess == number:
print 'your correct the number is', number
break
With your version of the code, you guess once. If you're wrong, your program tries the same guess over and over again forever (assuming your break was actually supposed to be indented in the elif). You might be typing new guesses into the terminal, but your program never sees them. If the break was actually in the correct place in your code, then you guess once and whether write or wrong it exits the loop right away.
your break is outside of your ifstatement
It will execute while loop one time and break no matter what

Categories