【问题标题】:Unable to accept user-input and use it without errors无法接受用户输入并正确使用它
【发布时间】:2020-09-30 15:00:57
【问题描述】:

好的,我已经解决了几天,无法自己解决。

Python 3 并在下面处理这个 sn-p 代码。我的问题是变量类型和用户输入。这段代码是我希望用户(主要是我)能够使用有意义的变量名称(地球质量的“m_earth”和类似数量)作为“F1”计算的输入,以及其他我想使用的......如果......我可以先让这部分工作。

我尝试过使用“float”和“int”,但它确实会产生其他我无法修复的错误。

下面包含的代码是使用此代码时发生的情况。

任何人有一些建议...拜托?

谢谢

G = float(6.674E-11)

# All masses are in Kg
m_earth = 5.972E24
m_moon = 7.345E22

m1 = input('Enter the first mass  ')
print(m1, 'Kg')

m2 = input('Enter the second mass  ')
print(m2, 'Kg')

r = input('Enter the center-to-center distance from mass m1 to mass m2  ')

F1 = G * m1 * m2 / r ** 2
print('The gravitational force is  ', F1, "N")

Enter the first mass  m_earth
m_earth Kg
Enter the second mass  m_moon
m_moon Kg
Enter the center-to-center distance from mass m1 to mass m2  3E12
Traceback (most recent call last):
  File "C:/Users/xyz/PycharmProjects/My Python Programs/try it.py", line 15, in <module>
    F1 = G * m_earth * m_moon / r ** 2
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

进程以退出代码 1 结束

【问题讨论】:

  • 快速解决方法是在 F1 计算之前添加 m1 = eval(m1)m2=eval(m2) 行。只要您是唯一的用户并且您知道您已经定义了哪些变量,它就可以工作并且没问题
  • input() 返回一个字符串,您不能使用intfloat 进行乘法、加法等操作。
  • 谢谢....我按照下面的添加了--- r = input('输入质量m1到质量m2的中心距') m1 = eval(m1) m2 = eval(m2) F1 = G * m_earth * m_moon / r ** 2 --------- 我收到以下错误:“ F1 = G * m_earth * m_moon / r ** 2 TypeError: unsupported ** 或 pow() 的操作数类型:'str' 和 'int' "
  • stackoverflow.com/a/2376520/12479639 这是众多答案之一,可以让您了解如何解决它。
  • 顺便说一句,如果您希望其他人会使用您的程序,切勿在未经检查的用户输入上使用eval。这可能非常危险。

标签: python-3.x variables type-conversion user-input


【解决方案1】:

您收到此错误是因为input() 总是返回一个字符串。 不能向ints 或floats 添加任意字符串的原因是因为在大多数情况下它没有意义。

考虑3 + 'Hello'。 您希望结果是什么?

那么我们该如何处理呢?我们将其转换为 python 理解为允许对其执行算术函数的东西。在 python 中,这些类型是int(整数)和float 小数。为了争论,还有很多其他的,但你不需要它们作为你的例子。

由于我们不能保证用户输入了一个数字,我们需要某种类型的检查来确保他们输入了。

这就是我们可以使用try/except 块的地方。

G = float(6.674E-11)

# All masses are in Kg
m_earth = 5.972E24
m_moon = 7.345E22

m1 = input('Enter the first mass  ')
print(m1, 'Kg')

m2 = input('Enter the second mass  ')
print(m2, 'Kg')

r = input('Enter the center-to-center distance from mass m1 to mass m2  ')

# any Error that occurs in the try block
# will hand control to the except block
# if the type of Exception in except is 
# the type of error that occurred
try:
    # here we try to convert the variable m1 of type str
    # to a variable of type float
    # since float() "returns" a float and does not convert in place
    # we need to catch the output it gives into the same variable
    m1 = float(m1)
    m2 = float(m2)
    r = float(r)
    F1 = G * m1 * m2 / r ** 2
    print('The gravitational force is  ', F1, "N")
# any conversion error here will result in a ValueError
# We can catch that specific error and alert the user they 
# mis-entered some data
except ValueError as v:
    print('Some of your input is not valid.')

但您希望能够指定变量的名称。 为此,您可以使用 python dictdict 将键映射到某个值。 键可以是多种类型,但最重要的是,它们可以是 str,input() 返回的类型。 在这种情况下,它可能是m_earth

# we need sys to do an early exit in the program
# if the data entered is not a key in the dict
import sys

G = float(6.674E-11)

# All masses are in Kg
my_dict = {'m_earth': 5.972E24,
           'm_moon': 7.345E22}

m1 = input('Enter the first mass  ')
# this will raise a KeyError
# if the key is not in your dict
try:
    m1 = my_dict[m1]
except KeyError as k:
    sys.exit('That name is invalid.')
print(m1, 'Kg')

m2 = input('Enter the second mass  ')
try:
    m2 = my_dict[m2]
except KeyError as k:
    sys.exit('That name is invalid.')

r = input('Enter the center-to-center distance from mass m1 to mass m2  ')

try:
    r = float(r)
    F1 = G * m1 * m2 / r ** 2
    print('The gravitational force is  ', F1, "N")
except ValueError as v:
    print('Some of your input is not valid.')

【讨论】:

  • Axe319 ---- 嗯,这行得通,我感谢你所做的所有工作。我知道来自“输入”的字符串内容,以及我使用 int 和 float 围绕它的尝试不是要走的路,而且我还不够好,无法通过第 22 条规则(如我所见)。我不明白为什么您的代码有效,但我将不得不花时间处理它,并希望我可以将其调整到该项目的其余代码中,并了解它为什么有效以及为什么它解决了我遇到的这个问题。再次感谢(点赞)
  • @fiz 只是为了给你指明正确的方向,查看 python dicts 以​​及它们的功能。我相信那是你缺少的部分。
猜你喜欢
  • 1970-01-01
  • 2015-11-28
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 2015-04-13
  • 2011-01-09
相关资源
最近更新 更多