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

Python随机姓名选择器故障:为何始终选中最后输入的姓名?

Python随机姓名选择器问题排查与修复

问题根源

  1. 循环缩进错误:for循环后的输入语句未缩进,Python会触发语法错误,无法正确执行多次输入操作。
  2. 误清空用户输入列表:导入random后执行了list1 = [],直接清空用户刚输入的所有姓名,导致洗牌操作完全无效。
  3. 错误调用变量:输出时使用names变量,该变量仅保存最后一次输入的姓名,因此每次都会显示最后输入的名字。

修复后的完整代码

import random

print("Hooray you decided to use a random name picker!")
print("\n")
print("Below you will be prompted on how to enter your list of names.")
print("\n")
n = int(input("How many names would you like to enter on the list today? Please press enter after you type in your number: "))
list1 = []

for i in range(n):
    names = input("Please enter the name. Press enter when finished. ")
    list1.append(names)

print("\nHere are the names you entered into the list:", list1)

answer = input("\nAre you ready to pick a name? Press enter to continue.")
print("\n")

# 对用户输入的列表执行洗牌
random.shuffle(list1)
# 选取洗牌后的第一个元素作为结果
picked_name = list1[0]

print(f"The name picked: {picked_name}")
print("\n")
# 打印洗牌后的列表验证效果
print("洗牌后的完整列表:", list1)

简化方案说明

如果不需要保留洗牌后的列表,可直接用random.choice()随机选取姓名,省去洗牌步骤,代码更简洁:

# 替换原洗牌和选取代码
picked_name = random.choice(list1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 07:52:46