无法接受用户输入并正确使用它
Unable to accept user-input and use it without errors
好的,我已经处理了几天,但我自己无法修复它。
Python 3 并处理下面的这段代码。我的问题是变量类型和用户输入。此代码是更大代码的一部分,我希望用户(主要是我)能够使用有意义的变量名称(“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
您收到此错误是因为 input()
总是 returns 一个字符串。
您不能向 int
s 或 float
s 添加任意字符串的原因是因为在大多数情况下它没有意义。
考虑 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 dict
。 dict
将键映射到某个值。
键可以是多种类型,但最重要的是,它们可以是 str,即 input()
returns 的类型。
在这种情况下,它可能是 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.')
好的,我已经处理了几天,但我自己无法修复它。
Python 3 并处理下面的这段代码。我的问题是变量类型和用户输入。此代码是更大代码的一部分,我希望用户(主要是我)能够使用有意义的变量名称(“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
您收到此错误是因为 input()
总是 returns 一个字符串。
您不能向 int
s 或 float
s 添加任意字符串的原因是因为在大多数情况下它没有意义。
考虑 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 dict
。 dict
将键映射到某个值。
键可以是多种类型,但最重要的是,它们可以是 str,即 input()
returns 的类型。
在这种情况下,它可能是 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.')