guessesTaken variable and the for statement - python

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.

Related

How to make guessing the number game(high, low hints) with cheating allowed (Ulam's Game) in python?

I made a game of guessing the number where computer choose a secret number between 1 to 100 and i try to guess that number. On each guess, computer gives hint that whether it is lower or higher than his secret number by saying "too low" or "too high". But i want that sometimes computer will cheat ( for example in place of saying "too low" it will say "too high"). But whenever he tells a lie, in very next guess he must have to tell the truth. He must not to be allowed to lie in two consecutive guesses. Though he can lie alternatively. He may tell the truth without any limitation, consecutively and anytime. In below code, computer randomly say "too low" or "too high". By doing so he is sometimes lying consecutively more than once. Please fix the code so that it doesn't lie in two consecutive guesses.
import random
myName = input('What is your name?~ ')
print('Well, ' + myName + '! I am thinking of a number from 1 to 100')
number = random.randint(1, 100)
guessesTaken = 0
result = ['low', 'high']
while guessesTaken < 20:
guess = int(input(str(guessesTaken + 1) + '-Take a guess!~ '))
guessesTaken += 1
if guess < number:
print('Your guess is too ' + random.choice(result) + '!')
if guess > number:
print('Your guess is too ' + random.choice(result) + '!')
if guess == number:
break
if guess == number:
print('Good job, ' + myName + '! You guess my number in ' + str(guessesTaken) + ' guesses')
else:
print('Nope! The number I was thinking of was ' + str(number))
Here is how I solved the problem.
We define a variable can_lie. It tells if the computer is allowed to lie, it's True if the last thing he told was the truth.
Then if we are allowed to lie, and only one time over two, we lie.
After this we are not allowed to do it for the next turn, so can_lie become False.
Then we say the opposite of what we should have said, because we are lying.
If we are telling the truth, then can_lie become True, so we are allowed to tell whatever we want the next turn.
Then we tell what we are supposed to say.
import random
myName = input('What is your name?~ ')
print('Well, ' + myName + '! I am thinking of a number from 1 to 100')
number = random.randint(1, 100)
guessesTaken = 0
result = ['low', 'high']
can_lie = True
while guessesTaken < 20:
guess = int(input(str(guessesTaken + 1) + '-Take a guess!~ '))
guessesTaken += 1
if can_lie and random.choice((True, False)):
#Here we lie
can_lie = False
if guess > number:
print('Your guess is too low !')
if guess < number:
print('Your guess is too high !')
else:
can_lie = True
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 guess my number in ' + str(guessesTaken) + ' guesses')
else:
print('Nope! The number I was thinking of was ' + str(number))
This code lies randomly, but never twice in a row.
import random
myName = input('What is your name?~ ')
print('Well, ' + myName + '! I am thinking of a number from 1 to 100')
number = random.randint(1, 100)
guessesTaken = 0
result = ['low', 'high']
previous_prediction = True
while guessesTaken < 20:
guess = int(input(str(guessesTaken + 1) + '-Take a guess!~ '))
guessesTaken += 1
if guess == number:
break
if previous_prediction:
low_high = random.choice(result)
else: # Make random choice only if told truth in previous choice
low_high = 'low' if guess < number else 'high'
print('Your guess is too ' + low_high + '!')
#If there is a lie between actual result and told result, mark the prediction as False, such that next time, only truth is provided
if not (( (guess < number) and low_high=='low') or ( (guess > number) and low_high=='high')):
previous_prediction = False
else:
previous_prediction = True
if guess == number:
print('Good job, ' + myName + '! You guess my number in ' + str(guessesTaken) + ' guesses')
else:
print('Nope! The number I was thinking of was ' + str(number))
However, you should have tried a bit more to solve it.

Is there a way to change the output of the strings based on the conditions of the loop?

I hope I worded the question right. So I'm going through a Python textbook. (automate the boring stuff). In it, I am supposed to create a guess the number game in which the player has 6 chances to pick the correct number.
However, I would like to make a couple of changes that I'm struggling with.
I want the output to show the exact amount of chances left (6 chances, 5 chances, 4, chances ... 0). I think i may have solved this problem, but I believe you all may have a better way.
when the player is down to 1 chance, i would like the text to change from 'chances left' to 'chance left'.
# This is a guess the number game.
import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
# Ask the player to guess 6 times.
for guessTaken in range(7, 1, -1):
print('Take a guess. You only have ' + str(guessTaken - 1) + ' chances left... ')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low. ')
elif guess > secretNumber:
print('Your guess is too high. ')
else:
break # This condition is the correct guess
if guess == secretNumber:
print('Good job! you guessed my number i ' + str(guessTaken) + ' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))
Change your range to range(6, 0, -1) so you don't need to subtract 1 in the message.
Use an if statement.
for guessTaken in range(6, 0, -1):
suffix = "s" if guessTaken > 1 else ""
print('Take a guess. You only have ' + str(guessTaken) + ' chance' + suffix + ' left... ')
You're also printing the wrong number in the success message. guessTaken is the number of guesses they have left, not the number of guesses they used. You need to change that to 7 - guessTaken.
Now may be a good time to learn about functions, if you haven't already. A simple function to do this is this:
def chances_remaining_message(num_chances):
if num_chances == 1:
return 'Take a guess. You only have 1 chance left...'
else:
return 'Take a guess. You only have ' + str(num_chances) + ' chances left...'
Which you would then call here:
# Ask the player to guess 6 times.
for guessTaken in range(7, 1, -1):
print(chances_remaining_message(guessTaken - 1))
guess = int(input())

Question about Automate The Boring Stuff Chapter 3

I am on chapter three of Automate The Boring Stuff with Python. For exercise guessTheNumber.py I am unclear as to how "guessesTaken" was defined and how it is being incremented.
https://automatetheboringstuff.com/chapter3/
How is this program:
1. Defining the guessesTaken variable
2. increasing the value of guessesTaken for each guess
Thank you,
# This is a guess the number game.
import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
# Ask the player to guess 6 times.
for guessesTaken in range(1, 7):
print('Take a 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 condition 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))
It is used as a loop counter, it was defined in:
for guessesTaken in range(1, 7):
And is being incremented in every iteration of the for loop. So if the loop counter reaches 3, that means the loop ran (didn't break) three times, and so the user had to guess three times.

NameError: name 'guessesTaken' is not defined issue

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.

Number guessing game

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.

Categories

Resources