如何让用户输入一个小数或者整数?

2024-04-25 22:32:38 发布

您现在位置:Python中文网/ 问答频道 /正文

如何让用户输入他们想要的任何类型的号码?我试过的是:

a=0
def main():
    x = int(input("Input a number in Celsius to convert it to Fahrenheit"))
    f = (x*1.8)+(32)
    print(f, "degrees Fahrenheit")

a=a+1
while a > 0:
    main()

main()

Tags: to用户in类型numberconvertinputmain
2条回答

就用这个:

x = float(input('Input a number in celcius to convert it to fahrenheit'))

然后使用x执行所需的计算。

阅读pythonhere中的基本类型。

无论如何,你在问题中的缩进是完全错误的。你的代码甚至不应该运行。你运行main()的逻辑也是荒谬的。可能是这样的:

a=0

def main():
    x = float(input("Input a number in celcius to convert it to fahrenheit"))
    f = (x*1.8)+(32)
    print(f, "degrees fahrenheit")

while a < 10: # for taking 10 inputs and converting
    main()
    a += 1

根据你想要的type数字,你只需要试着抓住

更新 因为原始输入将数据存储为str,因为isinstance(x, str)将为您提供True

x = raw_input("Input a number in celcius to convert it to fahrenheit")

try:
    val = int(x) # you can also covert to float before doing your calculation
    #carry out your calculations
except ValueError:
    print("That's not an int!")

相关问题 更多 >