繁体   English   中英

如何将所有变量转换为float

[英]How to cast all variables given as float

我试图将用户提供的所有变量转换为浮点数,但我当前的代码不能正常工作,我不知道为什么。

s = input('Displacement')
u = input('Initial Velocity')
v = input('Final Velocity')
a = input('Acceleration')
t = input('Time')
m = input('Mass')
theta = input('Angle made with the horizontal')

for i in (s, u, v, a, t, m, theta):
    if i != '':
        i = float(i)

例如,当我运行它并尝试对其中一个变量进行计算时

print (s**2)

我收到错误消息:

TypeError:**或pow()的不支持的操作数类型:'str'和'int'

如果它有一个值,我将如何遍历每个变量并将其转换为浮点数?

你可以定义一个新函数,让我们称之为: float_input()

def float_input(text: str) -> float:
    """Makes sure that that user input is of type float"""
    while True:
        try:
            num = float(input(text))
        except ValueError:
            print("You must enter a float.")
        else:
            return num

s = float_input('Displacement')
#...

print(s*2)

但是你甚至可以这样做(将数据存储在字典中)。 试试吧!!

def float_input(text: str) -> float:
    """Makes sure that that user input is of type float"""
    while True:
        try:
            num = float(input(text))
        except ValueError:
            print("You must enter a float.")
        else:
            return num

items = [
    'Displacement',
    'Initial Velocity',
    'Final Velocity',
    'Acceleration',
    'Time',
    'Mass',
    'Angle made with the horizontal'
]

# Single line option:
#d = {item: int_input('{}: '.format(item)) for item in items}

# Multi-line option
d = {}
for item in items:
    v = float_input('{}: '.format(item))
    d[item] = v

# Print the stored-data    
print(d)

然后访问这样的值,例如:

d.get('Displacement') 

如上所述,您应该在数据输入点转换为float 这可能是最干净,最有效的方法。

另一种解决方案是将变量存储在字典中,然后使用字典理解转换为float 这具有将特定任务的变量保持链接的设计优势。

以下示例说明了使用字典的两种方法。 这些方法都不适用于验证。 您应该使用try / except ValueError来确保输入在输入点有效。

input_dict = {'s': 'Displacement', 'u': 'Initial Velocity', 'v': 'Final Velocity',
              'a': 'Acceleration', 't': 'Time', 'm': 'Mass',
              'theta': 'Angle made with the horizontal'}

var_dict = {}

# direct conversion to float
for k, v in input_dict.items():
    var_dict[k] = float(input(v))

# conversion to float in a separate step
for k, v in input_dict.items():
    var_dict[k] = input(v)

# dictionary comprehension to apply float conversion
var_dict = {k: float(v) if v != '' else v for k, v in var_dict.items()}
i = float(i)

不会将s转换为float(s) i只是一个临时变量,每次迭代都会发生变化。 您需要在变量上明确转换类型,例如:

s = float(input('Displacement'))

循环不是必需的。

您当然可以使用以下命令:

s = input('Displacement')
u = input('Initial Velocity')
v = input('Final Velocity')
a = input('Acceleration')
t = input('Time')
m = input('Mass')
theta = input('Angle made with the horizontal')

variables = [s, u, v, a, t, m, theta]

for num, i in enumerate(variables):
     if i != '':
        variables[num] = float(i)

s, u, v, a, t, m, theta = variables

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM