我猜我需要使用一段时间循环,但是我无法弄清楚在哪里放置它,以便re-asks用户错误。 non-valid答案。

import random
import string
    def random_pass(length):
    spec_char = input("Would you like special characters in your password? ")
    if spec_char == "yes":
        characters =  string.ascii_letters + string.digits + string.punctuation
        password = ''.join(random.choice(characters) for i in range(length))
        print("Your password is: ", password)
    elif spec_char == "no":
        characters = ''.join(random.choice(string.ascii_letters) for i in range(length))
        print("Your password is: ", characters)
    else:
        print("Please only type Yes or No")
char_length = int(input("How many characters would you like your password to be? "))
random_pass(char_length)
分析解答

刚修改了您的代码

import random
import string
def random_pass(length):
    while True:
      spec_char = input("Would you like special characters in your password? ")
      if spec_char == "Yes":
          characters =  string.ascii_letters + string.digits + string.punctuation
          password = ''.join(random.choice(characters) for i in range(length))
          print("Your password is: ", password)
          return
      elif spec_char == "No":
          characters = ''.join(random.choice(string.ascii_letters) for i in range(length))
          print("Your password is: ", characters)
          return
      else:
          print("Please only type Yes or No")
char_length = int(input("How many characters would you like your password to be? "))
random_pass(char_length)