我正在尝试制作一个非常基本的计算器来熟悉python的基础知识.部分代码涉及请求输入并将其设置为不同的变量,但作为输入输入的变量存储为字符串,即使它们作为数字输入:
def change_x_a():
velocity_i = input("Initial Velocity?")
velocity_f = input("Final Velocity?")
time = input("Time?")
float(velocity_i)
float(velocity_f)
float(time)
answer = (0.5*(velocity_i+velocity_f)*time)
print(answer)
Run Code Online (Sandbox Code Playgroud)
有没有解决这个问题?
float()不会修改您传递的变量.相反,它会转换您给出的值并返回一个float.
所以
float(velocity_i)
Run Code Online (Sandbox Code Playgroud)
本身什么都不做,在哪里
velocity_i = float(velocity_i)
Run Code Online (Sandbox Code Playgroud)
将给出你正在寻找的行为.
请记住,float()(和其他类型转换函数)如果你传递了他们不期望的东西,就会抛出异常.为了获得更好的用户体验,您应该处理这些异常1.通常,人们在循环中执行此操作:
while True:
try:
velocity_i = float(input("Initial Velocity?"))
break # Valid input - stop asking
except ValueError:
pass # Ignore the exception, and ask again
Run Code Online (Sandbox Code Playgroud)
我们可以将这种行为包装成一个很好的小函数,使其更易于重用:
def get_input(prompt, exptype):
while True:
try:
return exptype( input(prompt) )
except ValueError:
pass # Ignore the exception, and ask again
Run Code Online (Sandbox Code Playgroud)
并称之为:
val_f = get_input('Give me a floating-point value:', float)
val_i = get_input('Give me an integer value:', int)
Run Code Online (Sandbox Code Playgroud)
1 - 哇,我刚刚意识到,我事后已经独立编写了与Python链接完全相同的代码.
| 归档时间: |
|
| 查看次数: |
93 次 |
| 最近记录: |