I tried to use this code i found on the internet to test some stuff
my code:
print('what is your age')
myAge = input()
print('you will be ' + str(int(myAge) + 1 ) + 'in one year'
but did not work and said unexpected EOF in parsing
(i am new to this stuff and im just testing these stuff this out)
You need to close the last print bracket:
print('what is your age')
myAge = input()
print('you will be ' + str(int(myAge) + 1 ) + ' in one year')
Because of no ')' at the end of 3rd line it throws error
myAge = input('what is your age\n')
print('you will be ' + str(int(myAge) + 1) + ' in one year')
We can combine the first print line and input () as
myAge = input('what is your age\n')
use have missing )
use the format method , much readable not casting
print('what is your age')
myAge = int(input())
print('you will be {} in one year'.format(myAge+1))
Related
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.')
I'm tying to make it so when you enter a digit value in the while loop, the loop ends and so does the program. However when I type "break" I get an invalid syntax error:(. Sorry for the bad coding, this is my first time.
print('Hello, world!')
print('What is your name?')
myName = input()
print('It is nice to met you, '+ myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?')
myAge=input()
if myAge.isdigit():print('You will be ' + str(int(myAge) + 1) + ' in "one" year')
else: print('that is not a number. Lets try again, what is your age?')
C = 0
while (C<=3):
myAge2=input()
C+=1
if myAge2.isdigit():print('You will be ' + str(int(myAge2) + 1) + ' in "one" year')
break
else: print('Try again')
Indentation to apply the correct break
if myAge2.isdigit():
print('You will be ' + str(int(myAge2) + 1) + ' in "one" year')
break
else:
print('Try again')
I tried simplifying the code:
print('Hello, world!\nWhat is your name')
myName = input()
print('It is nice to met you, {}.\nThe length of your name is: {}'.format(myName, len(myName)))
print('What is your age?')
myAge=input()
if myAge.isdigit():
print('You will be ' + str(int(myAge) + 1) + ' in "one" year')
else:
print('that is not a number. Lets try again, what is your age?')
myAge2=input()
while myAge2.isdigit():
print('You will be ' + str(int(myAge2) + 1) + ' in "one" year')
break
else:
print('Try again')
Problem with the code indentation, otherwise everything is working perfectly.
print('Hello, world!')
print('What is your name?')
myName = input()
print('It is nice to met you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?')
myAge = input()
if myAge.isdigit():
print('You will be ' + str(int(myAge) + 1) + ' in "one" year')
else:
print('that is not a number. Lets try again, what is your age?')
C = 0
while (C <= 3):
myAge2 = input()
C += 1
if myAge2.isdigit():
print('You will be ' + str(int(myAge2) + 1) + ' in "one" year')
break
else:
print('Try again')
Output
To clarify, this is similar to another question but I feel the answer is easier to understand.
I am making a very simple program for saying what year you will turn "x" years old. (It's a practice from Practice Python... Starting to relearn Python after a while) I would like the program to ask the user what age they want to know, and it does so. This works fine, but I do not remember how to have it keep asking until they write "n" and otherwise keep asking. Any ideas?
Thanks for the help! Code Below:
I've tried using a Java-esque loop, but this isn't Java, and I don't know what I'm doing. Up to any ideas.
# Libraries
import time
# Initial Code
name = input("What's your name? ")
print("Thank you " + name + "!")
age = int(input("How old are you? "))
year = int(input("Now, just for clarification, what year is it? "))
new_age = input("Now enter what age you would like to know! ")
print("Thank you! Now, I'll tell you the year you will turn " +new_age+ "!")
time.sleep(3)
print("Great, that calculation will only take a second or so!")
time.sleep(1.5)
math_year = year - age
answer = int(math_year) + int(new_age)
print(name + ", you will turn " + str(new_age) + " years old in " + str(answer) +"!")
time.sleep(3)
# Loop Code
again = input("Would you like to know another age? Y/n ")
if again == 'Y':
new_age = input("Awesome! What age would you like to know? ")
print("Great, that calculation will only take a second or so!")
time.sleep(1.5)
math_year = year - age
answer = int(math_year) + int(new_age)
print(name + ", you will turn " + str(new_age) + " years old in " + str(answer) +"!")
All results work, it just can't loop after the second time.
You can use while instead of if. Whereas if executes its block of code once, while will execute it again and again until the condition becomes false.
# Loop Code
again = 'Y'
while again == 'Y':
new_age = input("Awesome! What age would you like to know? ")
print("Great, that calculation will only take a second or so!")
time.sleep(1.5)
math_year = year - age
answer = int(math_year) + int(new_age)
print(name + ", you will turn " + str(new_age) + " years old in " + str(answer) +"!")
again = input("Would you like to know another age? Y/n ")
As of python 3.8 (so, sometime after late October this year), you'll be able to use the assignment operator := to take care of those first two lines at once:
# Loop Code
while (again := 'Y'):
...
again = input("Would you like to know another age? Y/n ")
hello try something like
while True:
"""
your code
"""
answer = input("again"?)
if answer == 'Y':
continue
elif answer == 'N':
break
else:
# handle other input as you want to
pass
Need help with a project at school where i am getting an indentation error on the following lines of code:
#First question
while numberofquestions <10:
operations = ['x', '-', '+']
operation = random.choice(operations)
number1 = random.randrange(0,10)
number2 = random.randrange(0,10)
if operation == '+':
answer = number1 + number2
elif operation == '-':
answer = number1 - number2
elif operation == 'x':
answer = number1 * number2
while True:
try:
user_answer = input("What is " + str(number1) + " " + operation + " " + str(number2) + "?")
user_answer = float(user_answer)
except ValueError:
print("Sorry that was an incorrect input, please try again.")
else:
break
if user_answer == answer:
print("Well Done! You got it correct!")
score = score+1
else:
print("Sorry you got that wrong")
print ("***********-*-*-*-Your score so far is-*-*-*-*********** ")
print (score)
numberofquestions = numberofquestions+1
print ("Well done, you have completed your test! Your final score was...")
print (score)
The individual error itself is in the line:
while True:
try:
And the error I get is "unindent does not match any outer indentation level"
Here is a link containing my whole code incase it helps: http://paste.ubuntu.com/17167322/
These lines:
while True:
try:
user_answer = input("What is " + str(number1) + " " + operation + " " + str(number2) + "?")
user_answer = float(user_answer)
except ValueError:
print("Sorry that was an incorrect input, please try again.")
else:
break
Have wrong indentation.
The two user_answer lines have one extra indention, and the else block has no matching if or try/except block.
Always set editor to CONVERT TAB TO WHITESPACE.
Never ever save tab as indentation, most parser that deal with indentation don't know how to handle mix of tab and spaces. This is the most common problem for all new developer that deal with indentation syntax (python , yaml, etc)
I spot the issue ASAP by copy your code to Notepad++, turn on "show all character". From line 67 to 74, you use space as indentation, while the rest you are using TAB. Depends on editor, some call the function as "Replace Tab by space", "Save tab as space" ,"translate tabs to spaces"
while True:
try:
....
except ValueError:
print("Sorry that was an incorrect input, please try again.")
###### Here is indentation error culprit, mostly due to tab/space mix.
else:
break
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!')