简单python函数整数错误?

2024-04-23 11:46:02 发布

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

为什么这个函数会给出错误消息“youneedtotyapinteger”,即使我输入了and integer?你知道吗

def readValue():
    while True:
        pressure = input('Type pressure: ')
        if pressure == int(pressure):
            return pressure
        else:
            print('You need to type an integer.')

Tags: and函数true消息inputifdeftype
3条回答

我想这是python3。在这种情况下,input()返回一个字符串。你知道吗

字符串3不等于int("3")的结果,因此测试失败。你知道吗

此行将字符串输入分配给pressure

pressure = input('Type pressure: ')

然后将字符串与转换后的intpressure进行比较

if pressure == int(pressure):

它们永远不会相等。你知道吗

如果您尝试执行一些简单的输入验证,那么可以使用try/except并检查异常ValueError,这表示转换为int失败。你知道吗

pressure = input('Type pressure: ')

该行对于以下任务无效, 根据我的说法,你想完成的任务可以做如下

def readValue():
    while True:
        pressure = input('Type pressure: ')
        try:
            pressure = int(pressure)
            return pressure
        except:
            print('You need to type an integer.')
            return 0
print readValue()

试试看,它会成功的!你知道吗

try/except可用于此类型的任务。。。。。 try将压力转换为整数值,如果发生任何错误,则将转到except part。:)

相关问题 更多 >