Python3 - 字符串/整数错误

时间:2018-02-17 00:38:57

标签: python-3.x variables

我在底部包含了短代码,然后是错误响应。我试图通过获取输入变量(年龄)并向其添加值2来创建新变量(agep)以获得数值结果。为什么我会收到错误以及打印所需结果的正确方法是什么?

   print ("Welcome")
   myVar = "Hello"
   myName = input ("What is your name?") 
   print (myVar + " " + myName)
   age = input ("What is your age?")
   print ("You are " +age)
   agep = age + 2
   print ("You will be " + agep + " in 730 days")
  

错误:第8行,在       agep = age + 2 TypeError:必须是str,而不是int

2 个答案:

答案 0 :(得分:0)

您的age变量正在被读取为字符串。尝试明确地告诉Python在创建agep时将其读作int:

print ("Welcome")
myVar = "Hello"
myName = input ("What is your name?") 
print (myVar + " " + myName)
age = input ("What is your age?")
print ("You are " +age)
# Here, transform age to int so that you can add 2 (another int)
agep = int(age) + 2
# Here, turn it back into a string to be able to concatenate with other strings
print ("You will be " + str(agep) + " in 730 days")

以下是您可能想要查看的python数据类型的一些background reading

答案 1 :(得分:0)

因为Python没有对String和Integer值求和: 因此,如果要添加年龄,则必须将age变量设置为整数: 像这样:int(age)(用2添加age变量。)

最后,要进行打印,您必须再次将integer variable更改为string,如下所示:str(agep)

,您的代码为:

 print ("Welcome")
 myVar = "Hello"
 myName = input ("What is your name?") 
 print (myVar + " " + myName)
 age = input("What is your age?")
 print ("You are " +age)
 agep = int(age) + 2
 print ("You will be " + str(agep) + " in 730 days")