This question already has answers here:
Why does code like `str = str(...)` cause a TypeError, but only the second time?
(20 answers)
Closed 2 years ago.
I am trying to learn Python. I am currently writing my first program and following Automate the Boring Stuff. I have run into an error that I cannot understand. I am running python 3.9.1. The lines in question run perfectly fine on their own, but give me the following error:
line 11, in <module>
print ('Pick a number.')
TypeError: 'str' object is not callable
Here is the total code:
import random
print ('Hello! What is your name?')
name = input()
print = ('Hi, ' + name + '. I am thinking of a number between -99 and 99.')
secretNumber = random.randint(-99,99)
for guessesTaken in range(1,7):
print ('Pick a number.')
guess = int(input())
if guess < secretNumber:
print ('Your guess is too low. Guess again.')
elif guess > secretNumber:
print('Your guess is too high. Guess again.')
else:
break # This means the guess was correct
if guess == secretNumber:
print ('Good job, ' + name + '. You guessed the value in ' + str(guessesTaken) + ' guesses.')
else:
print ('You did not guess the number. The correct number was ' + str(secretNumber) + '.')
The problem is in the line 6 actually, where you try to assign an value to the print:
print = ('Hi, ' + name + '. I am thinking of a number between -99 and 99.')
You should delete that = and the code will work :)
import random
print('Hello! What is your name?')
name = input()
print('Hi, ' + name + '. I am thinking of a number between -99 and 99.')
secretNumber = random.randint(-99,99)
for guessesTaken in range(1,7):
print ('Pick a number.')
guess = int(input())
if guess < secretNumber:
print ('Your guess is too low. Guess again.')
elif guess > secretNumber:
print('Your guess is too high. Guess again.')
else:
break # This means the guess was correct
if guess == secretNumber:
print ('Good job, ' + name + '. You guessed the value in ' + str(guessesTaken) + ' guesses.')
else:
print ('You did not guess the number. The correct number was ' + str(secretNumber) + '.')
Because of your line
print = ('Hi, ' + name + '. I am thinking of a number between -99 and 99.')
where your redefined the built-in function print to be a string.
Remove = from that command:
print('Hi, ' + name + '. I am thinking of a number between -99 and 99.')
Related
Hey so i have started with python recently and im facing a syntax error when im trying to activate this code with python 3.1
This code is from the Automate the Boring Stuff and it's exactly the same as the author used and mine is facing an Error, any idea ?
btw the Error is with the elif condition
import random
print('Hello. What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 to 20 ')
secretNumber = random.randint(1, 20)
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
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses')
else:
print(' Nope, that number i was thinking of was ' + str(secretNumber))
code with identation fixed which ran on my machine
import random
print('Hello. What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 to 20 ')
secretNumber = random.randint(1, 20)
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
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses')
else:
print(' Nope, that number i was thinking of was ' + str(secretNumber))
Here is the correct indentation:
import random
print('Hello. What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 to 20 ')
secretNumber = random.randint(1, 20)
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
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses')
else:
print(' Nope, that number i was thinking of was ' + str(secretNumber))
Indentation is a very important concept of Python!
You have indentation errors on your code, elif and else should be indented at the same level of if. Same for the second 'else'.
import random
print('Hello. What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 to 20 ')
secretNumber = random.randint(1, 20)
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
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses')
else:
print(' Nope, that number i was thinking of was ' + str(secretNumber))
I think you are looking for this. Note the indentation of the if/else statements.
import random
print('Hello. What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 to 20 ')
secretNumber = random.randint(1, 20)
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
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken)
+' guesses')
else:
print(' Nope, that number i was thinking of was ' + str(secretNumber))
Disclaimer:
I'm a bit of a newb myself so there could be better answers out there.
Python is all about indentation. The indentations of the if/elif/else should be all on the same level. See below:
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break
I'm going through the Automate the Boring Stuff with Python videos on youtube. I finished the one about random number guessing game and am now adding some stuff to it to make it more complete.
I added some code that makes it so that if you don't enter an integer (which creates a ValueError) the program tells you that you didn't enter an integer. However, the point of the game is that you only get 6 guesses, but when the error comes up it, it resets the number of guesses.
How can I make it so that the error doesn't reset the number of cases?
Here's the code:
# This is a guess the number game.
import random
print ('Hello, what is your name?')
name = input ()
name = name.strip()
print ('Well, ' + name + ' I am thinking of a number between 1 and 20.')
secretNumber = random.randint (1, 20)
print ('DEBUG: Secret number is ' + str(secretNumber))
while True:
try:
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 for the correct guess
if (guess == secretNumber and guessesTaken == 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guess.')
break
elif (guess == secretNumber and guessesTaken > 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
break
else:
print ('Nope. The number I was thinkig of was ' + str(secretNumber))
break
except ValueError:
print ('You did not enter a number.') # This condition is for if a non-integer is entered.
I feel like I've tried every combination of where I can but the try and for loop, but can't seem to figure it out.
The outer while loop seems unnecessary because it allows you to try even after 6 attempts.
Therefore the break in the last three conditions will also be deleted.
You should put the try into the for loop so that if an exception is raised, the program will continue to count the number of attempts.
I would do something like:
# This is a guess the number game.
import random
print('Hello, what is your name?')
name = input()
name = name.strip()
print('Well, ' + name + ' I am thinking of a number between 1 and 20.')
secretNumber = random.randint(1, 20)
print('DEBUG: Secret number is ' + str(secretNumber))
for guessesTaken in range(1, 7):
try:
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 for the correct guess
except ValueError:
print('You did not enter a number.') # This condition is for if a non-integer is entered.
if (guess == secretNumber and guessesTaken == 1):
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guess.')
elif (guess == secretNumber and guessesTaken > 1):
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
else:
print('Nope. The number I was thinkig of was ' + str(secretNumber))
The except block also should be moved, to be related to the try block, under the block of the loop because we don't want to stop the for loop as I mentioned before.
This is a guess the number game.
import random
print ('Hello, what is your name?')
name = input ()
guess = 0
name = name.strip()
print ('Well, ' + name + ' I am thinking of a number between 1 and 20.')
secretNumber = random.randint (1, 20)
print ('DEBUG: Secret number is ' + str(secretNumber))
while True:
for guessesTaken in range (1, 7):
try:
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 for the correct guess
except ValueError:
print ('You did not enter a number.') # This condition is for if a non-integer is entered.
if (guess == secretNumber and guessesTaken == 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guess.')
break
elif (guess == secretNumber and guessesTaken > 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
break
else:
print ('Nope. The number I was thinkig of was ' + str(secretNumber))
break
Basically I'm trying to make a guessing game. There are 3 questions and you have 3 guesses for every question. The problem is I'm bad at coding, this is only my first time.
print("Guessing Game")
player_name = input("Hi! What's your name? ")
number_of_guesses1 = 0
number_of_guesses2 = 0
number_of_guesses3 = 0
guess1 = input("What is the most popular car company in America? ")
while number_of_guesses1 < 3:
number_of_guesses1 += 1
if guess1 == ("Ford"):
break
if guess1 == ("Ford"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
guess2 = input("Try again:")
if guess2 == ("Ford"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
guess3 = input("Try again:")
if guess3 == ("Ford"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
print('You did not guess the answer, The answer was Ford')
guess1b = input("What color do you get when you mix red and brown?")
while number_of_guesses2 < 3:
number_of_guesses2 += 1
if guess1 == ("Maroon"):
break
if guess1b == ("Maroon"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
guess2b = input("Try again:")
if guess2b == ("Maroon"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
guess3b = input("Try again:")
if guess3b == ("Maroon"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
print('You did not guess the answer, The answer was Maroon')
This code kind of works, but only if you get the answer wrong 2 times in a row for every question lol. I also haven't thought of a way to implement a score keeper yet (at the end I want it to say how many points you got out of 3.) The code also is obviously not done. Basically, my questions are: How come when I get the answer wrong once and then get it right on the second try it says that it took 3 tries? And if you get the answer right on the first or second try how can I make it so it ignores the remaining tries you have left? This is the error code for example if I get it right on the second try:
Traceback (most recent call last):
File "main.py", line 20, in <module>
if guess3 == ("Ford"):
NameError: name 'guess3' is not defined
By utilizing the data structures within Python and a couple of functions, you can simplify your code considerably as shown below:
from collections import namedtuple
# Create a tuyple containing the Question, number of allowed tries and the answer
Question = namedtuple("Question", ["quest", 'maxTries', 'ans'])
def askQuestion(quest: str, mxTry: int, ans: str) -> int:
""" Ask the question, process answer, keep track of tries, return score"""
score = mxTry
while score > 0:
resp = input(quest)
if resp.lower() == ans:
print('Yes, you got it')
break
else:
score -= 1
print(f'Sorry {resp} is incorrect, try again')
if score == 0:
print("Too Bad, you didn't get the correct answer.")
print(f"The correct answer is {ans}")
return score
def playGame():
# Create a list of questions defiend using the Question structure defined above
question_list =[Question('What is the most popular car company in America? ' , 3, 'ford'),
Question("What color do you get when you mix red and brown?", 3, 'maroon')]
plyr_score = 0
for q in question_list:
plyr_score += askQuestion(q.quest, q.maxTries, q.ans)
print(f'Your final score is {plyr_score}')
The above approach allows you to extend the question repertoire as well as provide a different number of max tries by question.
simply execute playGame() to run the game
Don't use a different variable to keep track of each guess, instead just use one variable, and continually update it using input(). Then you can check it over and over again, without writing a whole mess of if-else statements. For keeping track of the number correct, you can use a variable, and increment it every time a correct answer is entered.
print("Guessing Game")
player_name = input("Hi! What's your name? ")
score = 0
answer1 = "Ford"
answer2 = "Maroon"
guess = input("What is the most popular car company in America? ")
number_of_guesses = 1
while guess != answer1 and number_of_guesses < 3:
guess = input("Try again: ")
number_of_guesses += 1
if guess == answer1:
print('You guessed the answer in ' + str(number_of_guesses) + ' tries!')
score += 1
else:
print('You did not guess the answer, The answer was Ford')
guess = input("What color do you get when you mix red and brown? ")
number_of_guesses = 1
while guess != answer2 and number_of_guesses < 3:
guess = input("Try again: ")
number_of_guesses += 1
if guess == answer2:
print('You guessed the answer in ' + str(number_of_guesses) + ' tries!')
score += 1
else:
print('You did not guess the answer, The answer was Maroon')
print('You got ' + str(score) + ' out of 2 questions.')
Trying my first Python game with Python 3.6. Have tried several IDEs including Geany, and Wing Personal.
The error is:
Traceback (most recent call last):
File "game1.py", line 7, in
myName = input()
File "", line 1, in
#This is a guess the numbers 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.")
while guessesTaken < 6:
print("Take a guess.")
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print("Your guess is too low.")
if guess > number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print("Good job, " + myName + "! You guesses my number in " + guessesTaken + " guesses!")
if guess != number:
number = str(number)
print("Nope. The number I was thinking of was " + number)
This code has multiple indentation errors. Indentation generally means four spaces or one tab character. So, the code inside each if-else condition should be indented by one level.
Also, in one of the conditions:
if guess > number:
break
What do you expect that to do? Break is used to stop the loops. I guess you want to exit the program for this particular case. For that you can use return 0 or sys.exit().
Here is the code, properly indented:
#This is a guess the numbers game.
import random
import sys
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.")
while guessesTaken < 6:
print("Take a guess.")
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print("Your guess is too low.")
if guess > number:
sys.exit()
if guess == number:
guessesTaken = str(guessesTaken)
print("Good job, " + myName + "! You guesses my number in " + guessesTaken + " guesses!")
if guess != number:
number = str(number)
print("Nope. The number I was thinking of was " + number)
Why doesn't Python like the commented print line when it is uncommented and the other line is not there?
# This is a guess the number game
import random
guessesTaken = 0
myName = input('Hi there! What is your name?')
number = random.randint(1, 20)
print('Well ' + myName + ' I am thinking of a number between 1 and 20')
while guessesTaken < 6:
guess = int(input('Try and guess what it is!')) # There are 4 spaces in front of print.
# guess = int(input ())
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low') # There are 8 spaces in front of print.
if guess > number:
print('Your guess is too high')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
# print('Good Job, ' + myName + '! You guessed my number ' + number + ' in ' + guessesTaken + ' guesses!')
print('Good Job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('I am sorry. The number I was thinking of was ' + number + ' Thanks for playing, though.')
input('\n\nPress Enter to exit')
Because number is an integer. Turn it into a string too:
print('Good Job, ' + myName + '! You guessed my number ' + str(number) + ' in ' + guessesTaken + ' guesses!')
However, it'd be much better to use str.format() string formatting:
print('Good Job, {0}! You guessed my number {1} in {2} guesses!'.format(
myName, number, guessesTaken))
String formatting converts inputs for you; see the Format String Syntax documentation for more details on what formatting options you have.
number is an integer. You can't add integers and strings, as the error message you received almost certainly told you.
Convert it to a string using str(number).
The problem is that number is an integer. As the error message you received stated, you can't add integers and strings together.
You can convert it into a string using str(number) like I have done below.
This is what it should be:
print('Good Job, ' + myName + '! You guessed my number ' + str(number) + ' in ' + guessesTaken + ' guesses!')