首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python while循环

Python while循环
EN

Stack Overflow用户
提问于 2012-12-28 06:46:00
回答 4查看 14.7K关注 0票数 8

我在python3中有这段代码,用于检查输入时的错误,但我需要确定输入是否为整数,如果不是,则打印错误消息。

有人能帮我找出while循环中的代码吗?谢谢

代码语言:javascript
复制
price = 110;

ttt = 1;

while price < 0 or price > 100:

    price = input('Please enter your marks for Maths:');
    ttt =ttt +1;
    if ttt >= 2:
        print( 'This is an invalid entry, Please enter a number between 0 and 100')
EN

回答 4

Stack Overflow用户

发布于 2012-12-28 06:51:26

使用int()函数将其转换为整数。这将在无法执行转换时引发ValueError:

代码语言:javascript
复制
try:
    price = int(price)
except ValueError as e:
    print 'invalid entry:', e
票数 9
EN

Stack Overflow用户

发布于 2012-12-28 07:22:25

您可能想要这样的代码,它既可以捕获价格是否为整数,也可以捕获价格是否在0到100之间,如果满足这些条件,则中断循环。

代码语言:javascript
复制
while True:
    price = raw_input('Please enter your marks for Maths:')
    try:
        price = int(price)
        if price < 0 or price > 100:
            raise ValueError
        break
    except ValueError:
        print "Please enter a whole number from 0 to 100"

print "The mark entered was", price

或者,由于您具有可管理的少量可能值,因此您还可以执行以下操作:

代码语言:javascript
复制
valid_marks = [str(n) for n in range(101)]
price = None
while price is None:
    price = raw_input('Please enter your marks for Maths:')
    if not price in valid_marks:
       price = None
       print "Please enter a whole number from 0 to 100"
票数 3
EN

Stack Overflow用户

发布于 2012-12-28 06:50:55

首先,使用raw_input而不是input

此外,将ttt检查放在输入之前,以便正确显示错误:

代码语言:javascript
复制
price = 110;
ttt = 1;
while price < 0 or price > 100:
    if ttt >= 2:
        print 'This is an invalid entry, Please enter a number between 0 and 100';
    price = raw_input('Please enter your marks for Maths:');
    ttt = ttt +1;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14062266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档