ตัวสร้างรหัสผ่านแรกใน Python

Sep 10 2020

นี่เป็นโครงการแรกของฉันที่ใช้ Python ฉันสร้างตัวสร้างรหัสผ่านอย่างง่ายที่ตรวจสอบอินพุตของผู้ใช้ ฉันจะปรับปรุงได้อย่างไร

import random
def password_generator():
    password = []
    letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
               "v", "w", "x", "y", "z"]
    password_length = 0
    password_numbers = []
    password_letters = []
    # Input the length of the password
    while True:
        password_length_input = input("Choose the length of your password with numbers between 6 and 15:\n")
        if not password_length_input.isnumeric():
            print(f"{password_length_input} is not a number, try again:")
            continue
        else:
            password_length = int(password_length_input)
            print(f"Password length: {password_length}")
        if 6 <= password_length <= 15:
            break
        else:
            print("The password must be between 6 and 15 characters, try again:")
            continue
    # Input the amount of numbers in password
    while True:
        password_numbers_input = \
            input(f"Choose the amount of numbers you want in your password, max {password_length}\n")
        if not password_numbers_input.isnumeric():
            print(f"{password_numbers_input} is not a number try again")
            continue
        elif int(password_numbers_input) > password_length:
            password_numbers = 0
            print(f"The value is too high, choose maximum {password_length} numbers")
            continue
        else:
            password_numbers = int(password_numbers_input)
            print(f"Password numbers: {password_numbers}")
            for number in range(0,password_numbers):
                password.append(random.randrange(0,9))
            break
    # Check for numbers and letters in password
    while True:
        if password_numbers == password_length:
            print(f"The password will be only {password_numbers} numbers, no letters.")
            break
        else:
            password_letters = password_length - password_numbers
            print(f"""Your password will be {password_length} characters with {password_numbers} numbers and {password_letters} letters.""")
            for letter in range(0,password_letters):
                password.append(random.choice(letters))
            break
    random.shuffle(password)
    password_string = ''.join([str(item) for item in password])
    print(f"Your password is:\n{password_string}")

password_generator()

ตัวอย่างการใช้งาน:

Choose the length of your password with numbers between 6 and 15:
Password length: 8
Choose the amount of numbers you want in your password, max 8
Password numbers: 2
Your password will be 8 characters with 2 numbers and 6 letters.
Your password is:
pzc11bmf

คำตอบ

9 benrg Sep 10 2020 at 22:06
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",`
           "v", "w", "x", "y", "z"]

วิธีการเขียนตัวอักษรนี้มีโอกาสเกิดข้อผิดพลาดได้ง่าย ฉันจะนำเข้าstringและใช้string.ascii_lowercaseแทนletters. หากคุณต้องการสร้างตัวอักษรของคุณเองไม่ว่าจะด้วยเหตุผลใดก็ตามฉันจะเขียน

letters = [chr(n) for n in range(ord('a'), ord('z') + 1)]

เนื่องจากไม่มีอันตรายจากการละเว้นหรือทำซ้ำจดหมาย


password_length = 0
password_numbers = []
password_letters = []

จะไม่ใช้ค่าเริ่มต้นเหล่านี้ ค่าเริ่มต้นสำหรับpassword_numbersและpassword_lettersไม่สมเหตุสมผลเนื่องจากตัวแปรเหล่านั้นมีตัวเลข ฉันจะลบทั้งสามบรรทัด


if not password_length_input.isnumeric():
    print(f"{password_length_input} is not a number, try again:")
    continue
else:
    password_length = int(password_length_input)
    print(f"Password length: {password_length}")

ฉันจะเขียนแทน

try:
    password_length = int(password_length_input)
except ValueError:
    print(f"{password_length_input} is not a number, try again:")
    continue
print(f"Password length: {password_length}")

while True:
    if password_numbers == password_length:
        ...
        break
    else:
        ...
        break

ไม่มีความรู้สึกที่จะมีการwhileวนซ้ำที่นี่เนื่องจากคุณมักจะแยกออกจากการทำซ้ำครั้งแรก


range(0,password_numbers)

range(password_numbers)คุณก็สามารถเขียน


password.append(random.randrange(0,9))

นี้จะผนวกหลักจาก 0 ถึง 8 รวมไม่เคย 9. random.randrange(10)ถ้าคุณต้องการหลักสิบสิ่งที่คุณควรจะเขียน random.choice(string.digits)หรือบางทีอาจจะดีกว่าการใช้งาน


password_string = ''.join([str(item) for item in password])

ถ้าคุณใช้string.digitsแล้วองค์ประกอบของทุกจะเป็นตัวอักษรเพื่อให้คุณสามารถลดความซับซ้อนนี้passwordpassword_string = ''.join(password)

6 Anonymous Sep 10 2020 at 20:31

วิธีที่ตรงไปตรงมามากขึ้นในการสร้างสตริงแบบสุ่ม:

import random
import string

    def get_random_string(length):
        letters = string.ascii_lowercase
        result_str = ''.join(random.choice(letters) for i in range(length))
        print("Random string of length", length, "is:", result_str)
    
    get_random_string(8)
    get_random_string(8)
    get_random_string(6)

ยืมมาจากที่นี่และมีตัวอย่างเพิ่มเติม

ตอนนี้หากคุณมีข้อกำหนดเฉพาะเช่นจำนวนตัวเลขขั้นต่ำคุณสามารถปรับแต่งสูตรหรือสร้างสองรายการและรวมเข้าด้วยกันในขณะที่สับค่า

มีตัวอย่างในลิงก์ที่ฉันยกมาด้านบน: "สร้างสตริงตัวเลขและตัวอักษรแบบสุ่มที่มีจำนวนตัวอักษรและตัวเลขคงที่" => การรวมความเข้าใจสองรายการ

วิธีที่คุณทำคือขั้นตอน แต่ไม่ใช่ Pythonic เป็นการคิดค้นล้อใหม่

อย่างน้อยที่สุดรายการอักขระที่อนุญาตของคุณควรมีลักษณะดังนี้:

letters = "abcdefghijklmnopqrstuvwxyz"

จากนั้นคุณเลือกตัวอักษรแบบสุ่มเช่นletters[3]จะส่งกลับ 'd' เนื่องจากรายการเป็นแบบ 0 และ Python ถือว่าสตริงเป็นลำดับของอักขระ การใช้การสุ่มอย่างที่คุณทำอยู่แล้วคุณสามารถเขียนโค้ดที่กระชับมากขึ้นได้

3 K.Oleksy Sep 10 2020 at 19:19

อันดับแรก

ฉันขอแนะนำให้สร้างวิธีการแยกกันสำหรับแต่ละวิธีในขณะที่ลูป

ประการที่สอง

ฉันคิดว่าการวนซ้ำ "ในขณะที่ True" ไม่ใช่แนวทางปฏิบัติที่ดี แทนที่จะเป็นเช่นนั้นให้ใช้เงื่อนไข

ประการที่สาม

ฉันขอแนะนำให้สร้างคลาส PasswordGenerator ซึ่งจะมีรหัสของคุณ จะช่วยให้คุณสามารถขยายโค้ดของคุณได้ในอนาคต

โครงสร้างพื้นฐานสำหรับโครงการของคุณ

 class PasswordGenerator():
     
    check_declared_password_length():
        ...
        
    check_amount_of_password_numbers():
        ...
    *
    *
    *

ในตอนท้ายอย่าลืมสร้างฟังก์ชันด้วยความรับผิดชอบเดียว หลังจากนั้นคุณสามารถเขียนการทดสอบหน่วยสำหรับแต่ละข้อได้และจะง่ายขึ้น