Python虽然循环没有破坏

时间:2018-02-17 05:05:09

标签: python python-3.x python-2.7

我是一名新程序员,我正在尝试制作一个基本的密码生成器。但是我的问题在于我的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'

有人可以告诉我,我做错了吗?感谢。

6 个答案:

答案 0 :(得分:2)

您永远不会在此处更改nx

while n > x:
    password = password + random.choice(l2)
    x + 1

因此,如果条件最初为True,它将始终保持True并无限循环。需要x = x + 1

顺便说一下,这是Pylint会为您捕获的确切错误。

答案 1 :(得分:2)

请考虑以下事项:

1)明显的条件

    x = 0
    if x == 0:
        password = ''

定义x = 0,然后检查x是否等于0.它总是为True。 因此,你可以这样改变它:

    x = 0
    password = ''

2)while循环永远不会结束

之前:

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

答案 2 :(得分:1)

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)

答案 3 :(得分:1)

这有帮助吗? :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))

答案 4 :(得分:0)

您在代码中犯了很多错误。什么是x + 1?它将是x = x + 1。请先了解基础知识。在分配x = 0之后,为什么要检查x == 0?难道你不认为if总是肯定的吗?您的代码采用干净的格式。希望这有效。

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()))

答案 5 :(得分:0)

您可以试试这个,我已经升级了一点以生成更复杂的密码。

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)