Python字符串变量打印方法及代码执行报错修正咨询
Hey there! Let's break down your two Python questions clearly and practically:
1. How to print a string variable in Python
There are several straightforward, common ways to do this, depending on your use case:
- Directly print the variable: Just pass the variable name to the
print()function—it's the simplest approach.greeting = "Hello, Python world!" print(greeting) - Concatenate with other text: Combine the variable with fixed strings using the
+operator (just make sure all parts are string type!).username = "Mia" print("Welcome back, " + username + "!") - Use f-strings (Python 3.6+): This is the most readable and recommended method for modern Python. Wrap variables in
{}inside a string prefixed withf.hobby = "painting" print(f"Your favorite hobby is {hobby}.") - Use the
str.format()method: A reliable option if you need compatibility with older Python versions.pet = "dog" print("I have a {} as a pet.".format(pet))
2. Fixing the non-executable Python code
First, let's spot the core issue in your original code:
name = input("What is your name: ") age = int(input("How old are you: ")) year = str((2014 - age)+100) print(name + " will be 100 years old in the year " + year)
All your statements are squeezed into a single line without separators—Python can't tell where one command ends and the next begins. Here's the basic fixed version that will run smoothly:
name = input("What is your name: ") age = int(input("How old are you: ")) year = str((2014 - age) + 100) print(name + " will be 100 years old in the year " + year)
Bonus: A more robust & accurate version
The fixed code works, but we can polish it to be more practical:
- Replace the hardcoded
2014with the current year so calculations stay accurate as time passes. - Add error handling to avoid crashes if the user enters a non-integer for age.
- Use f-strings to make the output cleaner and easier to edit.
import datetime name = input("What is your name: ") try: age = int(input("How old are you: ")) current_year = datetime.datetime.now().year year = current_year + 100 - age print(f"{name} will be 100 years old in the year {year}") except ValueError: print("Oops! Please enter a valid whole number for your age.")
Key fixes explained:
- Split each statement onto its own line (Python uses line breaks as natural statement separators).
- Added the
datetimemodule to fetch the current year dynamically instead of relying on a fixed number. - Wrapped the age input in a
try-exceptblock to handle invalid inputs gracefully, so the program doesn't crash unexpectedly. - Swapped clunky string concatenation for an f-string to make the code more readable and maintainable.
内容的提问来源于stack exchange,提问作者Tanmay Anand
相关产品推荐
相关产品推荐

