Python入门代码执行异常求助:按书籍编写的代码停在首个变量处
Hey there! Let's break down the issues in your code step by step—you're super close to getting it working right!
First, let's look at your original code for reference:
# This program says hello and asks for my name. print('Hello, world!') print('What is your name?') #ask for their name myName=input('Sebastian') print('It is good to meet you,'+myName) print('The length of your name is:') print(len(myName)) print('What is your age?') #ask for their age myAge=input(21) print('You will be'+str(int(myAGE)+1)+'in a year.')
Key Problems & Fixes:
input()requires string prompts:
Theinput()function only accepts a string as its prompt text. Your linemyAge=input(21)passes an integer (21), which will throw aTypeErrorimmediately—this is almost certainly why your code stops early. For the name input,input('Sebastian')works technically, but it shows "Sebastian" as the prompt instead of asking for the user's name. Useinput('Enter your name: ')for a clear prompt, or if you want a default name when the user hits enter, trymyName = input('What is your name? ') or 'Sebastian'.Python cares about variable case:
In the last line, you wrotemyAGEbut your variable is namedmyAge(lowercase 'a'). Python treats these as two different variables, so this will trigger aNameError. Stick to consistent casing!Missing spaces break readability:
Your final print statement will output something likeYou will be22in a year.because there are no spaces around the age number. Add spaces inside the string literals to fix this.Indentation note:
Python uses indentation to define code blocks (like loops or functions), but your code has no blocks that require indentation—so all lines should stay left-aligned. If you tried indenting lines that don't belong to a block, that's why you got an indentation error.
Corrected Code:
# This program says hello and asks for my name. print('Hello, world!') print('What is your name?') # Ask for their name # Optional: Use a clear prompt + set default if user enters nothing myName = input('Enter your name: ') or 'Sebastian' print('It is good to meet you, ' + myName) print('The length of your name is:') print(len(myName)) print('What is your age?') # Ask for their age # Fix: Pass string prompt, then convert input to integer myAge = int(input('Enter your age: ')) # Fix variable case + add spaces for clean output print('You will be ' + str(myAge + 1) + ' in a year.')
A quick extra tip: For cleaner code, use f-strings (Python 3.6+) instead of string concatenation. For example:
print(f'It is good to meet you, {myName}') print(f'You will be {myAge + 1} in a year.')
That should resolve all your issues—give it a try!
内容的提问来源于stack exchange,提问作者bigbass001

