簡體   English   中英

Python while循環不中斷

[英]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'

有人可以告訴我我錯了嗎? 謝謝。

您永遠不會在這里更改nx

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM