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
Related
The objective is to create a simple program that generates a number between 1 and 100, it will then ask the user to guess this, if they guess outside of the number range it should tell them to guess again, if not it should tell them whether their guess was too high or too low, prompting them to guess again. Once they do guess the correct number it should tell them they've won and the number of tries it took for them to guess it correctly.
Here is what I have so far
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
return play_game
else:
print("Invalid number.")
return play_game()
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
play_game()
The issue I'm currently running into is when it checks to see if their guess was between 1-100 instead of moving on to weather or not their number was too how or to low, it stays and loops.
If anyone could help me with this issue and review the code in general I'd appreciate it.
I think the problem is with some indentation and some logical problems in the flow.
When you call play_game() from inside the game, it starts a completely different game
with different random_number.
A good code that satisfies your condition might look like the following
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
else:
print("Invalid number.")
play_game()
You could re-adjust your code:
1. if no. within range, run your high, low, match checks
2. break if guess matches the no
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 0
while True:
count += 1
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
break
else:
print("Invalid number, try again")
play_game()
The issue you are running into is because of incorrect indentation. The if-else statements that check whether the number is within the valid range are at the same indentation level as the while loop and thus are not executed within it. Simply indenting should fix the problem.
Furthermore, you have called play_game without parenthesis, making it incorrect syntax for a function call. However, rather than checking if the number is greater than 0 and lesser than 100, it would more optimal to check whether number is lesser than 0 or greater than 100, and if that is the case, print invalid number and call play_game().
It would look something like this:
while True:
if guess < 0 and guess > 100:
print ("Invalid number.")
return play_game()
The rest of your code looks good. I've also attached the link on the section of indentations of the Python documentation here.
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 need to keep track of the number of guesses a user inputs in a simple guessing game.
I have tried using attempts= 0 and then setting attempts to = attempts + 1. Even when I do this, the code will print "You have guessed in 1 attempts" even when the user has guessed in more attempts than one.
Code:
attempts = 0;
print("Hello, welcome to the game. You will be choosing a number
between 1 and 100. You can only guess up to 10 times.")
for tries in range(tries_allowed):
print("You only get 10 tries.")
break
while attempts < 10:
guess = int(input("Please guess a number"));
attempts_used= attempts + 1;
if guess > random_number:
print("Guess is too high, try a smaller number");
elif guess < random_number:
print("Guess is too low, try a higher number");
elif guess == random_number:
attempts_used=str(attempts_used)
print("Correct- you win in", attempts_used, "guesses");
exit();
else:
if tries_allowed == 10:
print("You failed to guess in time")
my_list= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list.append(attempts_used)
print(my_list)
You never update the attempts variable, you've created a new one called attempts_used, you don't need to do this.
Just use attempts everywhere you're using attempts_used
Note: Whilst you're at it you should get rid of what is known as a "magic number", or a hard coded limit in your while loop
while attempts < tries_allowed:
Cleaned up your code a bit, shows the += counting method working for your script.
As others have said, the original code is creating an entirely new variable attempts_used that is simply attempts + 1, and attempts remains 0.
It could also be attempts = attempts + 1, += means the same thing.
To make a int a str in python for printing purposes, it does not need to be stored to a separate variable, just call str() around it, unless you plan to use the string separately.
import random
random_number = random.randint(1,100)
attempts = 0
tries_allowed = 10
print("Hello, welcome to the game. You will be choosing a number between 1 and 100")
print("You only get " + str(tries_allowed) + " tries.")
my_list = []
while attempts < tries_allowed:
guess = int(input("Please guess a number: "))
if guess in my_list:
print("You have already guessed " + str(guess))
continue
attempts += 1
my_list.append(guess)
if guess > random_number:
print("Guess is too high, try a smaller number")
elif guess < random_number:
print("Guess is too low, try a higher number")
elif guess == random_number:
print("Correct- you win in", str(attempts), "guesses")
break
else:
if attempts == 10:
print("You failed to guess in time")
for item in my_list:
print(item)
Your "attemps" variable stays on 0, so attemps_used(attempts + 1) will always be 1. You have to merge both of the variables in only one in order to control it (attempts=attempts+1)
Code which also checks previous input and prints a message.
import random
# Hello World program in Python
attempts = 0
print("Hello, welcome to the game. You will be choosing a number between 1 and 100. You can only guess up to 10 times.")
random_number = random.randint(1, 101)
#print(random_number)
my_list= []
for tries in range(10):
print("You only get 10 tries.")
guess = int(input("Please guess a number: "))
if guess in my_list:
print("You already guessed this number!!")
my_list.append(guess)
attempts += 1
if guess > random_number:
print("Guess is too high, try a smaller number")
elif guess < random_number:
print("Guess is too low, try a higher number")
else:
print("Correct- you win in", tries + 1, "guesses")
attempts = -1
break
if attempts is 10 and attempts is not -1:
print("You failed to guess in time")
print("Attempts : ", my_list)
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.
This is my first time visiting using stackoverflow--I'm new to programming and am taking a beginner's course for Python. Excited to get started!
Our second assignment asks us to create the well-known Guess the Number Game. For those of you who already know this game, I would love some help on an extra piece that's been added to it: we must list off each guess with their respective order. A sample output should look like this:
I'm thinking of an integer, you have three guesses.
Guess 1: Please enter an integer between 1 and 10: 4
Your guess is too small.
Guess 2: Please enter an integer between 1 and 10: 8
Your guess is too big.
Guess 3: Please enter an integer between 1 and 10: 7
Too bad. The number is: 5
I've got the coding down to where I have Guess 1 and Guess 3 appear, but I cannot make Guess 2 appear. I've been reworking and replacing every "while", "if", "elif", and "else" command to fix this, but can't seem to come up with a solution! Here is my code so far:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
attempts = 0
from random import randint
number = randint(0,10)
guess = eval(input("Guess 1: Please enter an integer between 1 and 10: "))
while guess != number and attempts == 0:
if guess < number:
print("Your guess is too small.")
break
if guess > number:
print("Your guess is too big.")
break
elif guess == number:
print("You got it!")
attempts = attempts + 1
if number != guess and attempts == 1:
guess = eval(input("Guess 2: Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
elif guess > number:
print("Your guess is too big.")
while guess == number:
print("You got it!")
attempts = attempts + 1
elif number != guess and attempts == 2:
guess = eval(input("Guess 3: Please enter an integer between 1 and 10: "))
if guess < number:
print("Too bad. The number is: ", number)
elif guess > number:
print("Too bad. The number is: ", number)
while guess == number:
print("You got it!")
This code outputs Guess 1 and then quits. Can anyone help me figure out how to make Guess 2 and 3 appear?? All ideas are welcome--Thanks!
You can shorten you code quite a bit, just move the input in the loop and keep looping for either three attempts using range or the user guesses correctly:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
from random import randint
number = randint(0,10)
# loop three times to give at most three attempts
for attempt in range(3):
# cast to int, don't use eval
guess = int(input("Guess 1: Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
elif guess > number:
print("Your guess is too big.")
else: # not higher or lower so must be the number
print("You got it!")
break
It would be better to use a while with a try/except to verify the user inputs a number, looping until the user has used 3 attempts or guesses correctly:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
attempts = 0
from random import randint
number = randint(0,10)
while attempts < 3:
try:
guess =int(input("Guess 1: Please enter an integer between 1 and 10: "))
except ValueError:
print("That is not a number")
continue
if guess < number:
print("Your guess is too small.")
attempts += 1
elif guess > number:
print("Your guess is too big.")
attempts += 1
else: # if it is a number and not too high or low it must be correct
print("You got it!")
break # break the loop
You cannot just use an if/else if you actually want to give the user feedback on whether their guess was too low or too high.
Also as commented don't use eval. Some good reason why are outlined here
All your while guess!=number and attempts == loops are useless, because you're either breaking out of them or incrementing attempts so their condition evaluates to False after the first iteration.
Guess 2 is never reached because either number equals guess (so number != guess is False) or attempts is still zero.
Guess 3 is never reached for the same reason. However, if guess 2 would be reached, guess 3 would never be reached because you put elif in front.
Try to get rid of the code for guess 2 and guess 3. Write all the code for guess = eval(input()) and if guess < number: ... elif guess > number: ... once and put it inside a loop. Here's a bit of pseudocode to illustrate the idea:
while attempts < 3
ask for user input
if guess equals number
print "you win"
exit the loop
else
print "that's wrong"
I used the "concatenation" method along with some of your helpful response ideas and finally got my code to work!! Thank you all so, so much for the help!! Here is the correct code for this program:
def guess():
from random import randint
number = randint(0,10)
print("I'm thinking of an integer, you have three guesses.")
attempts = 0
while attempts < 2:
guess = eval(input("Guess " + str(attempts + 1) + ": Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
attempts += 1
elif guess > number:
print("Your guess is too big.")
attempts += 1
else:
print("You got it!")
break
else:
attempts == 3
guess = eval(input("Guess 3: Please enter an integer between 1 and 10: "))
if guess < number:
print("Too bad. The number is: ", number)
elif guess > number:
print("Too bad. The number is: ", number)
else:
print("You got it!")
And then ending it with a call to function ("guess()"). Hope this serves well for those who experience this problem in the future. Again, thank you guys!