You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

密码生成器代码优化求助:仅输出3个完整密码而非生成过程

Fixing Password Generator to Output Full Passwords Only

Hey there! I see the issue with your password generator right away — you're printing the password while it's being built (inside the inner loop that adds each character), which is why you get that step-by-step output. Let's tweak the code to only show the final, complete passwords once they're fully generated.

Here's the revised code with all fixes applied:

import random  # Don't forget this! It's required for random.choice()

def Generate():
    chars = "abcdefghijklmnopqrstuvwxyz0123456780ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
    length_input = input("Password length? ")
    
    try:
        length = int(length_input)
        if 8 <= length <= 24:  # Enforce your stated 8-24 character range
            print("Generating...")
            for _ in range(3):
                password = ""  # Start with empty string, not a space
                for _ in range(length):
                    password += random.choice(chars)
                print(password)  # Print ONLY after the full password is built
        else:
            print("The password can only be between 8-24 characters long")
    except ValueError:
        print("Please enter a valid number for password length")

Generate()

Key changes made:

  • Added import random: Your original code was missing this, which would cause a runtime error when trying to use random.choice().
  • Moved print(password) outside the inner loop: Now it only runs once per password, after all characters are added.
  • Fixed initial password value: Changed from " " to "" so your passwords don't start with an unwanted space.
  • Improved length validation: Added a check for the lower bound (8 characters) to match your error message, and cleaned up the typo (characterss → characters).
  • Added try/except block: Handles cases where the user enters non-numeric input, preventing a crash.

Example output:

Password length?14
Generating...
CDbFAiKkAa9mr7
Ysyjj28Chqk(kE
%C8(w7MjPOzxxQ

内容的提问来源于stack exchange,提问作者Ace Lawson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:17:45