Hi everybody I hope everybody is having a great day! I have been coding in python for about 6 months now and I have been working on this "guess my number code" and basically the computer choses a random number between 1-100 and then the user tries to guess it. I get a problem with my variable guessesTaken saying that is not defined but I clearly defined up on line 5.
Here is the code:
import random
def Loop():
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 100)
print('Hi, ' + myName + ', I am thinking of a number between 1 and 100.')
mod = number % 2
if mod > 0:
print("The number I am thinking of is odd.")
else:
print("The number I am thinking of is even.")
while guessesTaken < 10:
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
print('Good job, ' + myName + '! You guessed my number in ' + str(guessesTaken) + ' guesses!')
guessesTaken = 10
if guess != number:
print('Nope. The number I was thinking of was ' + str(number))
playagain = input('Would you like to play again')
if playagain == "yes":
Loop()
if playagain == "no":
print ( 'Goodbye :)')
Loop()
I get the error "Traceback (most recent call last):
File "python", line 20, in
NameError: name 'guessesTaken' is not defined"
I have been trying to debug this for 1-2 weeks now and have still not found what is wrong with the code. Please don't directly tell me what the problem is please just give my some hints or clues
Sincerely yours Hardit a 6 month python programmer
The problem is with scoping and (partially) initialization. I suggest you look up how these things work, they are core concepts in programming.
The variable guessesTaken will be created "inside" the function loop, and will be available ONLY inside that function.
Once the function returns, the scope changes and your variable is no longer in the scope (it cannot be "seen").
A quick fix is adding guessesTaken = 0 in the same scope you want to use it. In this case, the scope is the whole file. Add the line guessesTaken = 0 after your imports and you're done.
Note: Python is not strongly typed, you can have whatever = 0 and then assign to whatever an Object of any type. In other languages, you have to assign to variables consistently with their types.
This error is there because in your code you initialize guessesTaken in the function Loop. However, you do not call the function so guessesTaken was not created yet. To make this work you have to call loop before the while loop. Or initialize guessesTaken outside the function.
Related
Just starting out here and was hoping someone could help me with an issue I'm having. Haven't been able to find any clear answers online, likely because this is such an early level exercise.
Basically I want to have the program print a different response after the first incorrect answer. For example... the first prompt is "Take a guess!" but after that I would like it to say... "Take another guess!"
Could anyone shed some light on this for me? Thanks in advance.
# Number guessing game.
import random
from time import sleep
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20. You have five chances to guess correctly.')
sleep(1)
# Ask the player to guess six times.
for guessesTaken in range(1, 6):
print('Take a guess!')
if guessesTaken > 1:
print('Take another guess!')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break #this is the correct guess!
if guess == secretNumber:
print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber) + '.')
Instead of using print to show the prompt, add it to the input function call. Within that you can use a ternary-style expression. Here's an example:
import random
NGUESSES = 6
RANGE = 1, 20
computer = random.randint(*RANGE)
for guess in range(NGUESSES):
if (user := int(input('Take a guess: ' if guess == 0 else 'Try again: '))) == computer:
print(f'Good job! You guessed correctly in {guess+1} guesses')
break
print('Too low' if user < computer else 'Too high')
else:
print(f'Nope. The number I was thinking of was {computer}')
I just started learning programming with the book: Invent your own computer games with Python.
Here is the code that I am going to refer to. (Python 3.4)
# This is a guess the number game.
import random
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1,20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
for guessesTaken in range(6):
print('Take a guess.')
guess = input()
guess = int(guess)
if guess < number-1:
print('Your guess is too low.')
if guess > number+1:
print('Your guess is too high.')
if guess == number + 1:
print('Close bruh!')
if guess == number - 1:
print('Almost!')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken + 1)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number + '.')
The book created a variable guessesTaken = 0. But if you run the program it doesn't matter what value you assign to guessesTaken at the beginning. It is as if Python forgets about it when the execution reaches the for statement. I can just as well omit the guessesTaken variable.
If it is true that Python forgets about the assignment statement for the variable, guessesTaken, then Python must use the guessesTaken variable next to the for statement to store the amount of loops that have been completed so that you can print it out for the user.
But the program prints the amount of guessesTaken + 1, so it means that Python counts the first loop as 0.
If all this is true, is it then always so that the variable next to a for statement is going to be the place where Python stores the amount of loops taken ? (as an integer)
Sorry, I started to sound like a Boolean data type :-)
You are correct, the original assignment of guessTaken is over written by guessTaken the for loop definition.
The variable in the for loop (in your case guessTaken) takes the values of the elements in the iterator itis looping over (in your case range(6))
In your case, range(6) returns the iterator [0,1,2,3,4,5] so guessTaken is 0, then 1, then 2 and so on up to 5.
I'm trying to make a number guessing game where when you guess the number right, it tells you how many guesses it took.
I've tried several loops but can't figure out how to get my "guesses" to increase.
import random
rand_num = random.randrange(1,201)
def guess_game():
guess = int(input("Please enter your guess: "))
guesses = 1
if guess == rand_num:
print("Hit!\nIt took you " + str(guesses) + " guesses!")
elif guess < rand_num:
print("Your guess is too low.")
guesses = guesses + 1
guess_game()
else:
print("Your guess is too high")
guesses = guesses + 1
guess_game()
guess_game()
For example, desired output should be something like this:
"Hit! It took you 5 guesses"
But it only says 1 guesses no matter how many tries it took.
Your code doesn't work because you keep calling guess_game() after every guess, effectively starting a new game after every guess.
When the user finally guesses correctly, it's always after 1 guess in that new game and then all games end at once, but never does the code reach the line where it prints the number after more than one guess in any of those games.
There's many different ways to fix this, but the main issue here is that (like many new programmers) you didn't realise calling a function doesn't just get the program to jump to your new code, it creates an entirely new space for the program to work in (each call to the function gets its own 'scope') and returns from that once the function is done, with the previous scope unchanged in most cases.
Every time you call guess_game(), you are essentially resetting the game.
Instead, you want to enclose your game in a while loop which it only exits when the game is over. I have written a working version for you here:
import random
rand_num = random.randrange(1,201)
def guess_game():
guesses = 1
while(True):
guess = int(input("Please enter your guess: "))
if guess == rand_num:
print("Hit!\nIt took you " + str(guesses) + " guesses!")
return 0
elif guess < rand_num:
print("Your guess is too low.")
guesses = guesses + 1
else:
print("Your guess is too high")
guesses = guesses + 1
guess_game()
Your Code is not working well because you have initialize guesses=1 in function when you call the function in itself (Recursion) the value of variable guesses is reset.
import random
rand_num = random.randrange(1,201)
guesses=0 #initialize it outside function
def guess_game():
guess = int(input("Please enter your guess: "))
global guesses
guesses+=1
if guess == rand_num:
print("Hit!\nIt took you " + str(guesses) + " guesses!")
elif guess < rand_num:
print("Your guess is too low.")
guess_game()
else:
print("Your guess is too high")
guess_game()
guess_game()
I have a simple exercise using PyCharm community editor, and I get a warning:
This inspection warns about local variables referenced before
assignment.
But there is no local variable here, and also it works well on Windows PowerShell. What's wrong with it?
# This is a guess the number game.
import random
secret_number = random.randint(1, 21)
print("I am thinking of a number between 1 and 20. You have three chances.")
# Ask the player to guess 3 times.
for guesses_taken in range(1, 4):
guess = int(input('Take a guess.\n'))
if guess > secret_number:
print('Your guess is too high.')
elif guess < secret_number:
print('Your guess is to low.')
elif guess == secret_number:
if guesses_taken == 1:
print('Oh my god. You just guessed only one time.')
else:
print("You are right. I'm thinking of %s, and you guessed my
number in %s guesses." % (secret_number, guesses_taken))
else:
break
if guess != secret_number: --> # Name 'guess' can be not defined.
print('Nope. The number I was thinking of was ' + str(secret_number) + '.')
Similarly, the revised version here still has the same problem.
# This is a guess the number game.
import random
secret_number = random.randint(1, 21)
print("I am thinking of a number between 1 and 20. You have three chances.")
# Ask the player to guess 3 times.
for guesses_taken in range(1, 4):
guess = int(input('Take a guess.\n'))
if guess > secret_number:
print('Your guess is too high.')
elif guess < secret_number:
print('Your guess is to low.')
else:
break
if guess == secret_number: --> # Name 'guess' can be not defined
if guesses_taken == 1: --> # Name 'guesses_taken' can be not defined
print('Oh my god. You just guessed only one time.')
else:
print("You are right. I'm thinking of %s, and you guessed my number in %s guesses." % (
secret_number, guesses_taken))
else:
print('Nope. The number I was thinking of was ' + str(secret_number) + '.')
You get warnings: they don't mean that your code won't work as expected, but they mean to tell you that things could go wrong under certain circomstances.
I don't use PyCharm, but the reasons I see for these warnings are:
guess gets assigned inside your for loop. So, in case the loop doesn't execute at least once, guess would never be assigned.
guesses_taken will first be assigned the first value of the range, then the second... But if the range were to be empty, it would also never get assigned.
See, for example:
for loop_index in range(1, -1): # empty!
my_value_assigned_in_loop = 1
print(loop_index)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-31-39f9878362fc> in <module>()
2 my_value_assigned_in_loop = 1
3
----> 4 print(loop_index)
NameError: name 'loop_index' is not defined
import random
def guess_number():
numb = random.randrange (10) +1
guessestaken = 0
guess = input("whats your number")
while (guess != numb):
if (guess > numb):
print "too low"
elif(guess < numb):
print "too high"
else:
input("whats your next numb")
tries += 1
I am making a number guessing game with range 1 to 10 and I need help on getting the loop to stop. when I guess the number it keeps going
Here's a working example of what you're trying to do:
import random
guessesTaken = 0
number = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
while guessesTaken < 6:
print('Take a guess.\n')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
You never reassign guess within the loop, so the truth value of guess != numb never changes. Put guess = before the input() call within the loop, or restructure it to a while True: ... break layout. Also, you only give the user another chance to guess the number if they get it exactly correct. Read through your code slowly and try to follow along with what the interpreter is doing.