Python新手求助:TypeError: can only concatenate tuple (not "str") to tuple错误
Hey there! Let's break down what's going wrong with your code and fix it step by step.
问题分析
Your error TypeError: can only concatenate tuple (not "str") to tuple comes from two key mistakes in your code:
Mistake 1: Using a comma instead of a decimal point
In your lineweight_kg = int(weight)* 0,453592, the comma,creates a tuple ((int(weight)*0, 453592)) instead of the decimal number0.453592you intended. That's whyweight_kgends up being a tuple, not a numeric value.Mistake 2: Trying to concatenate a numeric type with a string
Even if you fixed the decimal point issue, you can't directly use+to add a number (int/float) and a string in Python. You need to convert the number to a string first, or use a string formatting method.
修正后的代码
Here are a few working versions of your code, starting with the simplest fix:
1. Basic fix with string conversion
weight = input('How much do you weigh in pounds? ') weight_kg = int(weight) * 0.453592 # Replace comma with decimal point print(str(weight_kg) + ' is your weight in kilogrammes') # Convert number to string before concatenation
2. Better approach: Use f-strings (Python 3.6+)
F-strings are cleaner and handle type conversion automatically:
weight = input('How much do you weigh in pounds? ') weight_kg = int(weight) * 0.453592 print(f"{weight_kg} is your weight in kilogrammes")
3. Bonus: Handle decimal inputs and format output
If users might enter a decimal weight (like 150.5), use float() instead of int(), and you can even format the output to show fewer decimal places:
weight = input('How much do you weigh in pounds? ') weight_kg = float(weight) * 0.453592 print(f"{weight_kg:.2f} is your weight in kilogrammes") # Shows only 2 decimal places
内容的提问来源于stack exchange,提问作者someone

