python 中 type() 转换的问题 3

Question with type() conversion in python 3

name = input("what is your name : ")
age = int(input("what is your age : "))
age_after_100_years = 2021 + (100-age)
print(name + " your age after 100 years is " + age_after_100_years)

in the above code on line 2, ive converted the string to int and then used it in "age_after_100_years" variables, but it gives me an error

Output:
what is your name : p
what is your age : 25
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-565602469d9c> in <module>
  2 age = int(input("what is your age : "))
  3 age_after_100_years = 2021 + (100-age)
----> 4 print(name + " your age after 100 years is " + age_after_100_years)

TypeError: can only concatenate str (not "int") to str

但是当我在第 3 行使用 str() 时,即

name = input("What is your name? : ")
age = int(input("What is your age? : "))
age_after_100_years = str((2022-age)+100)
print(name+" you will be 100 years old by the year "+age_after_100_years)

Output:
What is your name? : pratik
What is your age? : 25
pratik you will be 100 years old by the year 2097

以上代码有效,

正如我想知道的,我已经将变量“age”中的字符串转换为 int(),那么为什么我必须将变量“age_after_100_years”转换为 str(),如果我“age”变量是 int(),“age_after_100_years”以 int() 输入开头,我将 int 与 int 输入连接起来?

变量“age_after_100_years”是整型,所以如果要使用“+”运算符将其连接到另一个字符串,则必须将其转换为字符串。

Python 中的 + 运算符对数值进行加法运算(例如,1 + 2 = 3),但它对字符串进行连接("1" + "2" = "12")。根据 Python 告诉您的内容,您正试图 + 一个字符串和一个数字,这是不允许的。相反,您需要在进行连接之前将数字转换为字符串值 (str(number_variable))。

或者,正如其他人指出的那样,使用 f 字符串,它允许您将数字(或任何其他支持 str() 的 types/objects)替换为字符串表达式(实际上,任何东西,但是,如果您在尚未为 str() 方法实现接口的 BinaryTree class 上调用 str(),则可能会得到诸如 "BinaryTree object at 0x0454354" 之类的文本。

看看你的例子,你可能想做:

name = input("What is your name? : ")
age = int(input("What is your age? : "))
age_after_100_years = str((2022-age)+100)

# passing multiple parameters to print()
print(name, " you will be 100 years old by the year ", age_after_100_years)

# using string concatenation
print(name + " you will be 100 years old by the year " + str(age_after_100_years))

# using f-strings
print(f"{name} you will be 100 years old by the year {age_after_100_years}")

# using %-formatting
print("%s you will be 100 years old by the year %s" % (name, age_after_100_years) )

# using string.format()
print("{} you will be 100 years old by the year {}".format(name, age_after_100_years) )

所有人都应该完成工作,但 f 弦更简洁、更短且更易于阅读:)

friend 你的代码 id 给出了一个错误,因为其中的 age 变量是 int 类型,而在下一行你将连接不允许的 int 所以我已经更正了你的代码并在更正后 这是代码

name = input("what is your name : ")
age = int(input("what is your age : "))
age_after_100_years = 2021 + (100-age)
print(name , " your age after 100 years is " , age_after_100_years)

之后的结果是

what is your name : p
what is your age: 12
p  your age after 100 years is  2109