gpt4 book ai didi

python - 如何将所有给定的变量转换为 float

转载 作者:行者123 更新时间:2023-11-30 22:13:25 25 4
gpt4 key购买 nike

我试图将用户提供的所有变量转换为 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)

我收到错误消息:

类型错误: ** 或 pow() 不支持的操作数类型:“str”和“int”

如何迭代每个变量并将其转换为 float (如果它有值)?

最佳答案

您可以定义一个新函数,我们称之为: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') 

关于python - 如何将所有给定的变量转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50784162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com