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

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_letters and string.digits in quotes, turning them into plain text strings instead of accessing the actual character sets from the string module.
  • Your loop only pulls characters from the (broken) letters variable, 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 for loop 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 string module 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:29:11