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

如何基于用户输入次数执行代码生成指定数量随机密码

解决方案

核心问题修正与优化

你的代码主要问题在于用冗余的elif判断数量,且没有实现循环生成对应数量的密码。以下是针对性的改进方案,同时兼容Python3并增加输入合法性校验:

完整改进代码

import random

colours = ["red", "blue", "black", "yellow", "orange", "purple", "green", "white", "teal", "gold"]
adjectives = ["fat", "skinny", "long", "short", "hard", "soft", "huge", "small", "wide", "narrow"]
buildings = ["office", "hospital", "church", "apartment", "house", "garage", "shop", "station", "restaurant", "gym"]

print("Password Creator")

# 确保用户输入合法的数字(1-36之间)
while True:
    try:
        amount = int(input("How many passwords do you need?"))
        if 1 <= amount <= 36:
            break
        print("This exceeds the limit! Please enter a value between 1-36.")
    except ValueError:
        print("Please enter a valid number!")

# 合并单词列表,避免使用Python内置函数名`all`作为变量
all_words = colours + adjectives + buildings
password_word_count = 3

# 循环生成指定数量的密码
for _ in range(amount):
    selected = random.sample(all_words, password_word_count)
    password = "".join(selected)
    print(password)

可选优化:按类别组合密码

如果需要每个密码必须包含一个颜色+一个形容词+一个建筑(更贴合需求描述),可以把密码生成部分替换为:

# 每个密码从三类列表各取一个单词
for _ in range(amount):
    colour = random.choice(colours)
    adj = random.choice(adjectives)
    building = random.choice(buildings)
    password = "".join([colour, adj, building])
    print(password)

内容的提问来源于stack exchange,提问作者John Barrowseed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 10:15:13