[英]Having trouble with a simple while loop
I've been trying to create a simple program in python in which the user is asked for their postcode until it contains both letters and numbers.我一直在尝试在 python 中创建一个简单的程序,在该程序中,用户被要求输入他们的邮政编码,直到它同时包含字母和数字。 This is the code I have so far:这是我到目前为止的代码:
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
When I run the program it doesn't ask me for my postcode even when it is wrong.当我运行程序时,即使它是错误的,它也不会询问我的邮政编码。 How can I fix this?我怎样才能解决这个问题?
You have to call the methods!你必须调用方法!
if i.isalpha(): # note the ()
# ...
if i.isdigit():
# ...
i.isalpha
is just the method
object (which is always truthy). i.isalpha
只是method
对象(始终为真)。 Only calling it will produce the real bool
you are looking for.只有调用它才会产生您正在寻找的真正bool
。
You could actually make this more concise, all the while not manually calling the methods and not having to maintain/reset all those variables:您实际上可以使这更简洁,同时无需手动调用方法,也不必维护/重置所有这些变量:
while True:
postcode = input("what is your postcode? ")
if any(map(str.isalpha, postcode)) and any(map(str.isdigit, postcode)):
break
Took me a while to see all the problems.我花了一段时间才看到所有的问题。
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")
You don't reset the values of num
and letter
each time.您不会每次都重置num
和letter
的值。
In your original you are changing a string you are iterating over.在您的原始文件中,您正在更改正在迭代的字符串。
And as someone else pointed out, you need to call functions with ()
.正如其他人指出的那样,您需要使用()
调用函数。
A good attempt though.一个很好的尝试。 There are many ways this could be done.有很多方法可以做到这一点。 Mine is just one "fix".我的只是一个“修复”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.