【问题标题】:Taking user input, calculations with said input and producing an output using f-strings [duplicate]接受用户输入,使用所述输入进行计算并使用 f-strings 产生输出
【发布时间】: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


【解决方案1】:

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

以下是正确的代码

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}")

这个问题在我的 cmets 中就我和另一个非常友善的用户之间的这个问题所述。

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

只需在我的计算之前添加从 str 到 int 的转换即可将其全部排序:D: age = int(age)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-18
    • 2016-03-17
    • 2011-01-09
    • 2021-07-19
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多