【发布时间】:2020-07-30 13:47:39
【问题描述】:
我正在尝试编写一个程序,该程序会询问用户他们的姓名和年龄,并返回他们到 100 岁的时间。我不断收到错误,我无法理解我做错了什么。
这是更基本的代码,我已对其进行了更改以尝试使其正常工作,因为使用{age}、{name} 等来打印我的 f 字符串时遇到了太多阻力。
import sys, math
# Inputs
name = str(input("What is your name: "))
age = str(input("How old are you: "))
# Calculations
diff = (100 - age)
year = str((2020 - age)+100)
# Output
print ("Hay " + name + " you are currently " + age + " years old, in " + diff + " years you will be 100, in the year " + year)
在我的程序的diff = (100 - age) 阶段,它返回以下内容:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~/Documents/Python/years until you are 100.py in
7 # Calculations
8
----> 9 diff = (100 - age)
10
11 year = str((2020 - age)+100)
TypeError: unsupported operand type(s) for -: 'int' and 'str'
我错过了什么?
【问题讨论】:
-
您可以对 int 执行算术运算。您不能对字符串执行算术运算。你的
age是一个字符串。 -
但年龄指的是我的用户输入,它是一个 int 否?哦,当我打字时,我已经意识到了一半,所有输入都是字符串,对吗?那么我怎样才能让'年龄'被计算为一个整数呢?我必须先将输入转换为 int 吗?
-
您确实检查了 Jonrsharpe 提供的链接?
-
不,但我现在也将阅读该内容。
-
我解决了,是我没有像他提到的那样将 srting 转换为 int 。我做了一个快速的 age = int(age) 并且它把它整理出来了:D 谢谢 Jonsharpe!
标签: python python-3.x f-string