Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取用户输入,使用所述输入进行计算,并使用f字符串生成输出_Python_Python 3.x_F String - Fatal编程技术网

Python 获取用户输入,使用所述输入进行计算,并使用f字符串生成输出

Python 获取用户输入,使用所述输入进行计算,并使用f字符串生成输出,python,python-3.x,f-string,Python,Python 3.x,F String,我正在尝试编写一个程序,询问用户的姓名和年龄,并返回他们到100岁的时间。我不断地犯错误,我不明白我做错了什么 下面是我修改过的更基本的代码,我试图让它工作,因为让我的f字符串用{age},{name}等打印时遇到了太多阻力 import sys, math # Inputs name = str(input("What is your name: ")) age = str(input("How old are you: ")) # Calcul

我正在尝试编写一个程序,询问用户的姓名和年龄,并返回他们到100岁的时间。我不断地犯错误,我不明白我做错了什么

下面是我修改过的更基本的代码,我试图让它工作,因为让我的f字符串用
{age}
{name}
等打印时遇到了太多阻力

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'

我错过了什么?

对!我自己弄到的,以防其他人像我一样想知道

以下是正确的代码

import sys, math

# Inputs

name = str(input("What is your name: "))

age = str(input("How old are you: "))

# Conversions

age = int(age)

# Calculations

diff = (100 - age)

year = str((2020 - age)+100)

# Output


print (f"Hay {name} you are currently {age} years old, in {diff} years you will be 100, in the year {year}")
这个问题正如我和另一位非常友好的用户在关于这个问题的评论中所说的那样

我忘记了所有的输入都是字符串,所以当我使用我的(age)变量时,它不会做数学运算

在我计算之前,只需添加一个从str到int的转换,就可以解决所有问题:D:
age=int(age)

您可以对int执行算术运算。您不能对字符串执行算术运算。你的
age
是一个字符串。但是age指的是我用户的输入,它是一个int no?当我打字的时候,我已经意识到了一半,所有的输入都是一个字符串,对吗?那么,我怎样才能将“年龄”计算为整数呢?我必须先把输入转换成int吗?你检查过Jonrsharpe提供的链接吗?没有,但我现在也要读一下。我解决了这个问题,我没有像他提到的那样将srting转换成int。我做了一个快速的age=int(age),它很好地解决了这个问题:D谢谢你Jonsharpe!