[英]Python while loop not breaking
我是一名新程序员,我正在尝试制作一个基本的密码生成器。 但是我一直遇到这个问题,我的while循环永不中断。
l1 = 'q w e r t y u i o p a s d f g h j k l z x c v b n m 1 2 3 4 5 6 7 8 9 0'
l2 = l1.split()
def genpass(n):
x = 0 if x == 0:
password = ''
if n < 100:
while n > x:
password = password + random.choice(l2)
x + 1
print(password)
else:
print 'Sorry, too long'
有人可以告诉我我错了吗? 谢谢。
您永远不会在这里更改n
或x
:
while n > x:
password = password + random.choice(l2)
x + 1
因此,如果条件最初为True
,它将始终保持True
并无限循环。 需要做x = x + 1
顺便说一句,这是Pylint会为您捕获的确切错误。
请考虑以下几点:
1)状况明显
x = 0
if x == 0:
password = ''
您定义x = 0,然后检查x是否等于0。它始终为True。 因此,您可以通过以下方式更改它:
x = 0
password = ''
2)虽然循环永远不会结束
在您之前:
while n > x:
[some code]
x + 1 # here was your mistake
考虑以下两种将1
加到变量x
:
x = x + 1
要么
x += 1
两者都是同一回事。
进一步的启示: https : //docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements
import random
l1 = 'q w e r t y u i o p a s d f g h j k l z x c v b n m 1 2 3 4 5 6 7 8 9 0'
l2 = l1.split()
def genpass(n):
password = ''
x = 0
if n < 100:
while n > x:
password = password + random.choice(l2)
x = x + 1
print(password)
else:
print 'Sorry, too long'
genpass(10)
能帮上忙吗? :p
import random
l1 = 'q w e r t y u i o p a s d f g h j k l z x c v b n m 1 2 3 4 5 6 7 8 9 0'
l2 = list(l1.split())
def genpass(n):
x = 0
password=[]
if n < 100:
while n > x:
password.append(random.choice(l2))
x+=1
return ''.join(password)
else:
return('Sorry, too long')
#example with 14 char
print(genpass(14))
您在代码中犯了很多错误。 什么是x + 1? 这将是x = x + 1。 请先了解基础知识。 为什么在分配x = 0之后立即检查x == 0? 您不认为如果永远是肯定的吗? 您的代码为纯格式。 希望这行得通。
import random
l1 = 'q w e r t y u i o p a s d f g h j k l z x c v b n m 1 2 3 4 5 6 7 8 9 0'
l2 = l1.split()
def genpass(n):
x = 0
password = ''
if n < 100:
while n > x:
password = password + random.choice(l2)
x=x + 1
print(password)
else:
print ('Sorry, too long')
print("Enter how long you want your password to be")
genpass(int(input()))
您可以尝试一下,我已经进行了一些升级以生成更复杂的密码。
import random
lower = 'q w e r t y u i o p a s d f g h j k l z x c v b n m'
nums = '1 2 3 4 5 6 7 8 9 0'.split()
upper = lower.upper().split()
spcl = '; ! # @ & $ '.split()
all = lower.split() + nums + upper + spcl
def genpass(n):
x = 0
if x == 0:
password = ''
if n < 100:
while n > x:
password = password + random.choice(all)
x=x + 1
print(password)
else:
print('Sorry, too long')
# generates a sample password
genpass(10)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.