密码生成器代码优化求助:仅输出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 userandom.choice(). - Moved
print(password)outside the inner loop: Now it only runs once per password, after all characters are added. - Fixed initial
passwordvalue: 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/exceptblock: 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
相关产品推荐
相关产品推荐

