[英]While Loop not working in Python
I am struggling on this while loop in python I am trying to make the program continue to repeat itself until it output an lower,upper and digit but it ends as I run the program 我在python中的while循环中苦苦挣扎,我试图使程序继续重复自身,直到它输出低位,高位和数字,但在我运行程序时结束
import random
num = 3
print(num)
message=""
for n in range(num):
while message =="":
newnum= random.randint(48,122)
if newnum > 47 and newnum < 58:
val=chr(newnum)
val = newnum
message +=chr(val)
elif newnum > 64 and newnum <91:
val=chr(newnum)
val = newnum
message +=chr(val)
elif newnum > 97 and newnum < 123:
val=chr(newnum)
val = newnum
message +=chr(val)
else:
newnum -= random.randint(7,10)
val=chr(newnum)
val = newnum
message +=chr(val)
if (any(x.isupper() for x in message) and any(x.islower() for x in message)and any(x.isdigit() for x in message)):
print(message)
else:
message =""
After the first iteration your message will be != of '', because you will set it to a chr(val). 第一次迭代后,您的消息将是“ =”(共''),因为您会将其设置为chr(val)。 Thus it will never re-enter in the while loop again and it will just finish the for loop. 因此它将永远不会再次进入while循环,而只会完成for循环。
I think your problem is in wrong indention. 我认为您的问题是缩进错误。 Try to use 尝试使用
for n in range(num):
while message =="":
newnum= random.randint(48,122)
if newnum > 47 and newnum < 58:
val=chr(newnum)
val = newnum
message +=chr(val)
elif newnum > 64 and newnum <91:
val=chr(newnum)
val = newnum
message +=chr(val)
elif newnum > 97 and newnum < 123:
val=chr(newnum)
val = newnum
message +=chr(val)
else:
newnum -= random.randint(7,10)
val=chr(newnum)
val = newnum
message +=chr(val)
if (any(x.isupper() for x in message) and any(x.islower() for x in message) and any(x.isdigit() for x in message)):
print(message)
else:
message =""
Your problem is mainly ident and the while condition, take a look at my code. 您的问题主要是ident和while条件,请看我的代码。
import random
num = 3
print(num)
message=""
end = False #set a valid condition to end the program
for n in range(num):
# while message =="":
while end == False:
newnum= random.randint(48,122)
if newnum > 47 and newnum < 58:
val=chr(newnum)
val = newnum
message +=chr(val)
elif newnum > 64 and newnum <91:
val=chr(newnum)
val = newnum
message +=chr(val)
elif newnum > 97 and newnum < 123:
val=chr(newnum)
val = newnum
message +=chr(val)
else:
newnum -= random.randint(7,10)
val=chr(newnum)
val = newnum
message +=chr(val)
if (any(x.isupper() for x in message)
and any(x.islower() for x in message)
and any(x.isdigit() for x in message)):
print(message)
end=True
# else:
# message =""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.