Simple Python Game while-loop syntax error - python

So - I'm new to Python and just messing around with some basic games to get my head around the language.. For whatever reason this little code returns "Invalid Syntax on Line 8" which is the "While guessedwrong == 1" line... Can anyone tell me why?
from random import randint
UserResponse = int(input("Guess what number between 1 and 100 I'm thinking
of!"))
RandomNumber = randint(1,100)
guessedwrong = 1
While guessedwrong == 1:
If UserResponse > RandomNumber:
print("Nope! Lower!")
UserResponse = int(input("Try again!"))
elif UserResponse < RandomNumber:
print("Njet! Higher!")
UserResponse = int(input("Try again!"))
else
print("Correct! You're awesome!")
GuessedWrong = 0

Python is case sensitive:
while guessedwrong == 1:
#^
if UserResponse > RandomNumber
#^
# Some other your code
else:
# ^^
print("Correct! You're awesome!")
guessedwrong = 0
# ^^^^^^

Full corrected code
from random import randint
UserResponse = int(input("Guess what number between 1 and 100 I'm thinking of!"))
RandomNumber = randint(1, 100)
guessedwrong = 1
while guessedwrong == 1:
if UserResponse > RandomNumber:
print("Nope! Lower!")
UserResponse = int(input("Try again!"))
elif UserResponse < RandomNumber:
print("Njet! Higher!")
UserResponse = int(input("Try again!"))
else:
print("Correct! You're awesome!")
guessedwrong = 0

Related

Why am I getting a syntax error for my code on the last elif statement; I want it to be on the same block as the first if statement

# import random
# random_number = random.randint(1,1000)
random_number = int(input("Enter a number from 1000"))
guess = 500
high_value = 1000
low_value = 0
guess_counter = 0
if random_number > 500:
for i in range(0,10):
if guess == random_number:
# print("You got it {}".format(guess))
# print(("you got it {}".format(random_number)))
print("The random number was {}".format(random_number))
break
if guess < random_number:
low_value = guess
guess = low_value + (high_value - low_value)//2
high_value = 2*(guess - low_value) + low_value
guess_counter += 1
print("Guess # {}, your guess was {}".format(guess_counter, guess))
else:
high_value = guess
guess = low_value + (high_value - low_value)//2
low_value = -2*guess + 2*low_value + high_value
guess_counter += 1
print("Guess # {}, your guess was {}".format(guess_counter, guess))
guess = 250
random_number = int(random_number)
elif random_number < 500:
print("hi")
Trying not to get a syntax error here. Why am I getting a syntax error for my code on the last elif statement; I want it to be on the same block as the first if statement.
Corrected it for you, the if and elif need to be indented the same:
import random
# random_number = random.randint(1,1000)
random_number = int(input("Enter a number from 1000"))
guess = 500
high_value = 1000
low_value = 0
guess_counter = 0
if random_number > 500:
for i in range(0,10):
if guess == random_number:
# print("You got it {}".format(guess))
# print(("you got it {}".format(random_number)))
print("The random number was {}".format(random_number))
break
if guess < random_number:
low_value = guess
guess = low_value + (high_value - low_value)//2
high_value = 2*(guess - low_value) + low_value
guess_counter += 1
print("Guess # {}, your guess was {}".format(guess_counter, guess))
else:
high_value = guess
guess = low_value + (high_value - low_value)//2
low_value = -2*guess + 2*low_value + high_value
guess_counter += 1
print("Guess # {}, your guess was {}".format(guess_counter, guess))
guess = 250
random_number = int(random_number)
elif random_number < 500:
print("hi")
because
guess = 250
random_number = int(random_number)
this lines is not continue if without indet so you can't use elif after
You are getting a syntax error because guess = 250 and random_number = int(random_number) needs to be indent. This said based of the assumption that you are trying to write a number guessing game there are also many logic errors in your code.

Counting Game Try/Except and calculating the users attempts

I am creating a python random counting game. I'm having some difficulties with certain parts. Can anyone here review my code? I'm having difficulty with trying to implement a try/except and a tries function that counts the user's attempts. I also have to verify that the number is a legitimate input and not a variable. So far I've gotten this far and its coming along good. I just need alittle help ironing out a few things. Thanks guys you rock.
Here is the code below:
import random
def main():
start_game()
play_again()
tries()
print("Welcome to the number guessing game")
print("I'm thinking of a number between 1 and 50")
def start_game():
secret_number = random.randint(1,50)
user_attempt_number = 1
user_guess = 0
while user_guess != secret_number and user_attempt_number < 5:
print("---Attempt", user_attempt_number)
user_input_text = input("Guess what number I am thinking of: ")
user_guess = int(user_input_text)
if user_guess > secret_number:
print("Too high")
elif user_guess < secret_number:
print("Too low")
else:
print("Right")
user_attempt_number += 1
if user_guess != secret_number:
print("You ran out of attempts. The correct number was"
+str(secret_number)+ ".")
def play_again():
while True:
play_again = input("Do you want to play again?")
if play_again == 'yes':
main()
if play_again =='no':
print("Thanks for playing")
break
def tries():
found= False
max_attempts=50
secret_number = random.randint(1, 50)
while tries <= max_attempts and not found:
user_input_text = start_game()
user_guess_count=+1
if user_input_text == secret_number:
print("It took you {} tries.".format(user_guess_count))
found = True
main()
Try this method:
def play_game():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
count = 1 #new line
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
count = count+

Variable issue with my python guessing game

I'm making a guessing game where you have the option of an easy medium and hard mode but when I adjusted my code so that the display changes from 100 to 1,000,000 I get an error saying:
File "C:/Users/Zach Hirschman/AppData/Local/Programs/Python/Python35-32/GuessGame.py", line 38, in main
if guess > randomNumber:
UnboundLocalError: local variable 'randomNumber' referenced before assignment
I can't seem to figure out how I can fix this, any help would be appreciated.
"""
Zach Hirschman
12/20/2017
GuessGame.py
This program asks the user to guess a number
"""
import random
def main():
difficulty = input("Enter a difficulty level: 'easy','medium', or 'hard'
: ")
print("At any time, type 'hint' to get a hint")
if difficulty == "easy":
randomNumber = random.randint(1,100)
elif difficulty == "medium":
randumNumber = random.randint(1,10000)
elif difficulty == "hard":
randomNumber = random.randint(1,1000000)
found = False
while not found:
if difficulty == "easy":
guess = int(input("Guess a number between 1 and 100"))
if guess > randomNumber:
print("Too high")
elif guess == randomNumber:
print("Thats correct!!")
found = True
else :
print("Too Low")
elif difficulty == "medium":
guess = int(input("Guess a number between 1 and 10000"))
if guess > randomNumber:
print("Too high")
elif guess == randomNumber:
print("Thats correct!!")
found = True
else :
print("Too Low")
elif difficulty == "hard":
guess = int(input("Guess a number between 1 and 1000000"))
if guess > randomNumber:
print("Too high")
elif guess == randomNumber:
print("Thats correct!!")
found = True
else :
print("Too Low")
x = input("would you like to play again? Type 'yes' or 'no': ")
if x == "yes":
main()
else:
print("See you later!")
main()
I think it was just a scoping issue. For randomNumber variable to be available in the while loop, the while loop has to be within the same function that the variable is declared in (eg. main()): then they have the same "scope".
Initialising randomNumber before the if statements is not needed and will make no difference. That is usually done before for or while loops (as you did with found = False). randomNumber was not being initialised because it depended on "difficulty", which was out of scope.
Note that after defining it, the function has to be called by main(). In your code main() wasn't running, only the ifs/while parts were as they were written outside the function.
import random
def main():
difficulty = input("Enter a difficulty level: 'easy','medium', or 'hard' : ")
print("At any time, type 'hint' to get a hint")
if difficulty == "easy":
randomNumber = random.randint(1,100)
elif difficulty == "medium":
randomNumber = random.randint(1,10000)
elif difficulty == "hard":
randomNumber = random.randint(1,1000000)
found = False
while not found:
if difficulty == "easy":
guess = int(input("Guess a number between 1 and 100"))
if guess > randomNumber:
print("Too high")
elif guess == randomNumber:
print("Thats correct!!")
found = True
else :
print("Too Low")
main()
The other options are:
moving everything out of the function, which will work fine by gets complicated for longer programs
adding a return value to main() and binding it to randomNumber. This would also require the same for the difficulty variable, so would be better to refactor into multiple smaller functions.
Finally, randomNumber had a typo - that didn't cause the problem though.
Another approach which simplifies a little your solution:
import random
difficulty_thresholds = {
"easy" : 100,
"medium" : 10000,
"hard" : 1000000
}
wants_to_continue = True
while wants_to_continue:
difficulty = input("Enter a difficulty level: 'easy','medium', or 'hard': ")
maximum_number = difficulty_thresholds.get(difficulty, 100)
randomNumber = random.randint(1, maximum_number)
found = False
while not found:
guess = int(input("Guess a number between 1 and {}: ".format(maximum_number)))
if guess > randomNumber:
print("Too high")
elif guess == randomNumber:
print("That's correct!!!")
found = True
else:
print("Too Low")
do_we_continue = input("Would you like to play again? Type 'yes' or 'no': ")
wants_to_continue = do_we_continue == "yes"
print("See you later!")

Infinite While Loop Help Needed

print("Hi. Welcome on Guess The Number!!")
from random import randint
randomnumber = randint(1,100)
print("Guess the number!!")
usernumber = int(input("Which number am I thinking about?"))
try = 0
while usernumber != randomnumber:
if usernumber < randomnumber:
print("Lower...")
print()
try += 1
usernumber = int(input("Which number am I thinking about"))
elif usernumber < randomnumber:
print("Higher")
print()
try += 1
usernumber = int(input("which numberam I thinking about?"))
print("Finally!!!")
if try <= 10:
print("Well done!!")
elif try > 10:
print("U lost")
print()
print("The End!")
This causes me an infinite loop when I put an input number that is higher than the random number.
How can I fix this?
In your code, both the if and the else only cater to usernumber < randomnumber. This is why you will end up with an infinite loop - because you haven't coded the if-else branch, that would handle such a case.

Guessing random number game python

My program is supposed to ask the user to guess a number between 0 and 100 however I can't seem to get the output right. At the moment if the the User number is greater than the random number, it prints out an infinite amount of "Your number is too high." Also if the first UserGuess is low, then all the following numbers will have the same prompt: ("Your number is too low") despite them being actually bigger than the random number. I have no idea what I am doing wrong. Any help would be greatly appreciated. Thank you!
from random import randint
def main():
guessesTaken = 0
randomNumber = randint(0,100)
#print(randomNumber)
giveUp = -1
UserGuess = int(input("Take a guess" + "(The random number is: " + str(randomNumber) + "): "))
while UserGuess != randomNumber:
guessesTaken += 1
if UserGuess < randomNumber:
UserGuess = int(input("Your guess is too high.Try again: "))
elif UserGuess > randomNumber:
UserGuess = int(input("Your guess is too high.Try again: "))
elif UserGuess == randomNumber or UserGuess == giveUp:
break
if UserGuess == randomNumber:
guessesTaken = str(guessesTaken)
print("Yes, that is right!")
print("It took you " + guessesTaken + " guesses")
if UserGuess == giveUp:
guessesTaken = str(guessesTaken)
randomNumber = str(randomNumber)
print("Better luck next time.")
print("You tried"+ guessesTaken + " guesses")
return
print (main())
if __name__ == "__main__":
main()
You need to get more user input once you're inside the loop. Consider
UserGuess = None
while UserGuess != randomNumber:
UserGuess = int(input("Take a guess" + "(The random number is: " + str(randomNumber) + "): "))
guessesTaken += 1
....
As it stands, you're taking only the first guess. Then you're repeatedly reevaluating it. Since there's no chance for the user to change their guess, it loops infinitely.
Also, you'll want to change up the order of your if/elifs.
As it stands, the structure is
if guess (is too low)
if the guess (is not too low), and (is too high)
if the guess (is not too low), and (is not too high), and (is correct) or (is 'give up')
A quick way to get it working would be
if UserGuess == randomNumber or UserGuess == giveUp:
...
elif UserGuess > randomNumber:
...
elif UserGuess < randomNumber:
....

Categories