繁体   English   中英

如何使我的while循环检查这两种情况

[英]How to make my while loop check both conditions

对于我的程序,我要求用户提供邮政编码。 我试图让程序再次询问用户他们的邮政编码,如果他们输入的不仅是数字,而且是5个字符。 它的确不是5个字符,而是再次要求提供邮政编码,但不会再次询问用户是否输入了非数字的字符。 例如,如果您键入“ 8789”,则无法使用,但如果您键入“ 8jkf0”,则将使用。

我试过将我的或切换到和,但是仅此而已。 我想不出要尝试的其他方法。 我是python的新手。 我在学校使用它,有时在业余时间使用它。

zipcode = input("What is your ZIP code? ")
ziplen = len(zipcode)
while not (char.isnumber() for char in zipcode) or not ziplen == 5:
    zipcode = input("What is your ZIP code? ")
    ziplen = len(zipcode)

我希望该程序再次询问用户的邮政编码,如果他们输入的不仅仅是数字和正好5个字符,而是只检查它是否正好是5个字符。

isnumeric检查整个字符串,因此只是:

while not zipcode.isnumeric() or not len(zipcode) == 5:
    ...

您需要调用all()函数以返回测试zipcode所有字符的结果。 您的列表理解会产生一个生成器,这将永远是真实的。

正确的功能是isdigit ,而不是isnumber

while ziplen != 5 or not all(map(str.isdigit, zipcode)):

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM