在简单的while循环中遇到问题

2024-03-29 01:33:26 发布

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

我一直在尝试用python创建一个简单的程序,其中要求用户输入他们的邮政编码,直到它同时包含字母和数字。 这是我目前掌握的代码:

num = False
letter = False
while num == False and letter == False:
    postcode = input("what is your postcode? ")
    for i in postcode:
        if i.isalpha:
            letter = True
        if i.isdigit:
            num = True

当我运行程序时,它不会要求我提供我的邮政编码,即使它是错的。我怎样才能解决这个问题


Tags: and代码用户程序falsetrueinputif
2条回答

你必须调用这些方法

if i.isalpha():  # note the ()
    # ...
if i.isdigit():
    # ...

i.isalpha只是method对象(它总是真实的)。只调用它将产生您正在寻找的真正的bool

实际上,您可以使其更加简洁,同时不必手动调用方法,也不必维护/重置所有这些变量:

while True:
    postcode = input("what is your postcode? ")
    if any(map(str.isalpha, postcode)) and any(map(str.isdigit, postcode)):
        break

我花了一段时间才看到所有的问题

num = False
letter = False
while not(num and letter):
    num = False
    letter = False
    user_input = input("What is your postcode? ")
    x = user_input[0]
    y = user_input[1]
    print(x.isalpha())
    print(y.isdigit())
    if x.isalpha():
        letter = True
    if y.isdigit():
        num = True
    print(num, letter)
        
print("You are in")

您不会每次都重置numletter的值

在原始文本中,您正在更改迭代的字符串

正如其他人指出的,您需要使用()调用函数

不过这是一次很好的尝试。有很多方法可以做到这一点。我的只是一个“修复”

相关问题 更多 >