我想在 1 上增加变量“age”,但它给我带来了这个错误
我尝试将
print(f"Happy birthday {namename} your age is turned from{age} to {age_second}")
更改为 print(f"Happy birthday {namename} your age is turned from{age} to {age} + 1")
或类似的东西。但它没有起作用。它遵循代码语法,介绍了我尝试的第二个变体。
namename = input("What is your name")
print(f"Hello {namename}")
age = input("How old are you?")
age_second = int({age} + 1)
print(f"Happy birthday {namename} your age is turned from{age} to {age_second}")
在 F 字符串 (
f"..."
) 之外,语法 {age}
还意味着其他含义:它创建一个包含一项的集合(即 age
的值)。
这就是您收到错误的原因:您正在尝试将 int (
1
) 添加到集合 ({age}
),这是 Python 不支持的操作。
相反,您想要获取输入的整数值,然后加一:
age = input("How old are you?")
age_second = int(age) + 1
你的问题是你如何计算
age_second
。
age = input("How old are you?")
print(type(age)) # <class 'str'>
print(type({age})) # <class 'set'>
age_second = int({age} + 1) # wrong; cannot add 'set' to 'int'
相反,你应该这样做:
namename = input("What is your name")
age = int(input("How old are you?")) # cast 'str' to 'int' here
print(f"Happy birthday {namename} your age is turned from {age} to {age + 1}")
因为 Python 编译器认为
age
是 set
类型,所以不能将 +
运算符与 int
类型一起使用。您可以通过将其更改为 int(age) + 1
来解决此问题。