Python密码生成器开发问询:12-30位含大小写字母与数字
Fixing Your Python Password Generator
Hey there! Let's get your password generator working exactly as you need it—producing 12-30 character passwords with uppercase, lowercase letters, and numbers. First, let's spot the issues in your current code:
- You wrapped
string.ascii_lettersandstring.digitsin quotes, turning them into plain text strings instead of accessing the actual character sets from thestringmodule. - Your loop only pulls characters from the (broken)
lettersvariable, so you'd never get numbers in the final password. - The manual loop approach works, but we can make it cleaner and more reliable.
Here's a revised, robust version of your generator that meets all your requirements:
import random import string def generate_password(): # Split out character sets for clarity (and to ensure we cover all required types) uppercase = string.ascii_uppercase lowercase = string.ascii_lowercase numbers = string.digits # Start by adding at least one of each required character type—no more all-letter or all-number passwords! password_parts = [ random.choice(uppercase), random.choice(lowercase), random.choice(numbers) ] # Calculate remaining length (total 12-30, minus the 3 we already added) remaining_length = random.randint(9, 27) # Combine all valid characters for the rest of the password all_valid_chars = uppercase + lowercase + numbers # Add random characters to reach the desired total length password_parts += [random.choice(all_valid_chars) for _ in range(remaining_length)] # Shuffle the parts to avoid predictable patterns (like always starting with uppercase) random.shuffle(password_parts) # Join everything into a single password string return ''.join(password_parts) # Test it out! print(generate_password())
Key improvements explained:
- Guaranteed character diversity: By starting with one uppercase, one lowercase, and one number, we ensure the password always meets your combination requirement—no more random misses.
- Cleaner random selection: Using list comprehensions instead of a manual
forloop makes the code shorter and easier to read. - Better randomness: Shuffling the final character list prevents any predictable order (like the mandatory characters always being first).
- Correct module usage: We properly access
stringmodule attributes without quotes, so we're using the actual sets of letters and numbers.
If you wanted to tweak it further (like adding symbols later), you could just add string.punctuation to the all_valid_chars set and adjust the mandatory characters accordingly!
内容的提问来源于stack exchange,提问作者UltraHacker
相关产品推荐
相关产品推荐

