运行我的程序时出现错误。我需要更改什么?

huangapple go评论92阅读模式
英文:

Getting error when I run my program. What do I need to change?

问题

          导入 randomstring

    字符串 = string.ascii_letters + string.digits +     string.punctuation


    def 生成随机密码():
        长度 = int(input("密码有多少个字符?"))
        密码数量 = int(input("您想要多少个密码?"))
        字符计数 = 字符串
        if 字符计数 > str(长度):
            print("太长了,请重试")
            return
        密码 = []
        for i in range(长度):
            密码.append(random.choice(字符串))
            if 字符计数 < str(长度):
                random.shuffle(字符串)
                    for i in range(长度 - 字符计数):
                    密码.append(random.choice(字符串))
            random.shuffle(密码)
            输出 = "".join(密码)
            print(输出)
            return(输出)

    结果 = 生成随机密码()

    with open("pwd.txt", "w+") as 文件:
        文件.write(结果)
英文:
      import random,  string

characters = string.ascii_letters + string.digits +     string.punctuation


def generate_random_password():
    length = int(input(&quot;How many characters in password? &quot;))
    number_of_passwords = int(input(&quot;How many passwords would you     like? &quot;))
    character_count = characters
    if character_count &gt; str(length):
        print(&quot;To long, try again&quot;)
        return
    password = []
    for i in range(length):
        password.append(random.choice(characters))
        if character_count &lt; str(length):
            random.shuffle(characters)
                for i in range(length - character_count):
                password.append(random.choice(characters))
        random.shuffle(password)
        output = &quot;&quot;.join(password)
        print(output)
        return(output)

results = generate_random_password()

with open(&quot;pwd.txt&quot;, &quot;w+&quot;) as file:
    file.write(results)

This the code for the generator and when I get to the end the result is the same:

    file.write(results)
TypeError: write() argument must be str, not None

I tried the str function and int function; I changed "w+" to "a". I thought using the str function would fix it, considering the argument must be str.

答案1

得分: 0

代码现在可以运行。我编辑了它,这样你就可以生成指定长度的密码了。现在轮到你完成代码,使其能够生成多个密码。

import random, string

characters = list(string.ascii_letters + string.digits + string.punctuation)

def generate_random_password():
    length = int(input("密码长度是多少个字符?\n"))
    number_of_passwords = int(input("你想要生成多少个密码?\n"))
    character_count = len(characters)
    
    if length > character_count:
        print("太长了,请重试")
        return -1

    password = []
    output = ""
    for i in range(number_of_passwords):
        output = "".join(random.sample(characters, length))
        password.append(output)
        print(output)
    return password

results = generate_random_password()

if results != -1:
    with open("pwd.txt", "w+") as file:
        for pwd in results:
            file.write(pwd + "\n")
英文:

Code is now runnable. I edited it so that you can now generate a password of a specific length. Now, it's up to you to complete the code so that it can generate more than 1 password.

import random, string

characters = list(string.ascii_letters + string.digits + string.punctuation)


def generate_random_password():
    length = int(input(&quot;How many characters in password?\n&quot;))
    number_of_passwords = int(input(&quot;How many passwords would you like?\n&quot;))
    character_count = len(characters)
    
    if length &gt; character_count:
        print(&quot;Too long, try again&quot;)
        return -1

    password = []
    output = &quot;&quot;
    for i in range(length):
        output += &quot;&quot;.join(random.sample(characters, length))
        password.append(output)
        print(output)
        return (output)


results = generate_random_password()

if results != -1:
    with open(&quot;pwd.txt&quot;, &quot;w+&quot;) as file:
        file.write(results)

答案2

得分: 0

在接受用户输入时,需要确保输入的数据类型是特定类型(在本例中是int),您应该始终进行验证。

函数应该按照它们的名称建议的方式执行——没有更多。

random 模块具有一个choices() 函数,非常适合您的需求。

from random import choices
from string import ascii_letters, digits, punctuation

CHARACTERS = ascii_letters + digits + punctuation

def generate_random_password(length):
    return ''.join(choices(CHARACTERS, k=length))

while True:
    try:
        if (length := int(input('密码有多少个字符? '))) > len(CHARACTERS):
            raise Exception(f'最大长度为{len(CHARACTERS)}')
        password = generate_random_password(length)
        with open('pwd.txt', 'w') as pwd:
            pwd.write(password)
        break
    except Exception as e:
        print(e)
英文:

When taking user input that needs to be of a certain type (in this case int) you should always validate it.

Functions should do what their name suggests - nothing more.

The random modules has a choices() function which is ideal for your needs.

from random import choices
from string import ascii_letters, digits, punctuation

CHARACTERS = ascii_letters + digits + punctuation

def generate_random_password(length):
    return &#39;&#39;.join(choices(CHARACTERS, k=length))

while True:
    try:
        if (length := int(input(&#39;How many characters in password? &#39;))) &gt; len(CHARACTERS):
            raise Exception(f&#39;Maximum length is {len(CHARACTERS)}&#39;)
        password = generate_random_password(length)
        with open(&#39;pwd.txt&#39;, &#39;w&#39;) as pwd:
            pwd.write(password)
        break
    except Exception as e:
        print(e)

huangapple
  • 本文由 发表于 2023年3月12日 16:36:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75711932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定