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

函数外调用变量时出现重复定义及重复输入问题求助

问题分析

原代码存在两个核心问题:

  1. 输入时机错误:不管用户选择是否自定义名字,都会提前执行输入语句,导致非预期的交互流程(比如选n时仍被要求输入名字)
  2. 逻辑冗余:函数仅做值的返回,未封装核心的输入判断逻辑,虽然不会重复触发输入,但交互逻辑不符合需求
修正方案

简化版(无函数封装)

直接将输入逻辑嵌入判断分支,仅在用户选择自定义时触发输入:

import random

# 用户名处理逻辑
rando_username = ['Yoda', 'Han', 'Luke', 'General Kenobi', 'Mace Windu', 'Padme', 'Anakin', 'Jar Jar Binks']
user_name_choice = input('Would you like to choose your own name for the duel? y/n: ')
if user_name_choice.lower() == 'y':
    username = input('What shall we call you? ')
else:
    username = random.choice(rando_username)

# 对手名处理逻辑
rando_opponent = ['Darth Vader', 'Darth Sidious', 'Darth Maul', 'Kylo Ren', 'Jabba the Hutt', 'Moff Gideon', 'Jango Fett', 'General Grievous']
opponent_name_choice = input(f'Hello there, {username}! Would you like to name your enemy? y/n: ')
if opponent_name_choice.lower() == 'y':
    opponent_name = input('What shall we call your enemy? ')
else:
    opponent_name = random.choice(rando_opponent)

# 输出最终结果
print(f'Excellent choice {username}, your opponent is {opponent_name}!')

函数封装版(适合复用逻辑)

将名字生成逻辑封装成函数,便于后续复用:

import random

def get_username():
    rando_username = ['Yoda', 'Han', 'Luke', 'General Kenobi', 'Mace Windu', 'Padme', 'Anakin', 'Jar Jar Binks']
    user_choice = input('Would you like to choose your own name for the duel? y/n: ')
    return input('What shall we call you? ') if user_choice.lower() == 'y' else random.choice(rando_username)

def get_opponent_name(username):
    rando_opponent = ['Darth Vader', 'Darth Sidious', 'Darth Maul', 'Kylo Ren', 'Jabba the Hutt', 'Moff Gideon', 'Jango Fett', 'General Grievous']
    opponent_choice = input(f'Hello there, {username}! Would you like to name your enemy? y/n: ')
    return input('What shall we call your enemy? ') if opponent_choice.lower() == 'y' else random.choice(rando_opponent)

# 调用函数获取名字
username = get_username()
opponent_name = get_opponent_name(username)

# 输出结果
print(f'Excellent choice {username}, your opponent is {opponent_name}!')

关键改动说明

  • 精准触发输入:仅当用户输入y(兼容大写Y)时,才弹出自定义名字的输入框,避免不必要的交互
  • 增强鲁棒性:用.lower()统一输入格式,支持用户输入大小写混合的y/n
  • 简化逻辑:移除冗余的全局变量和无意义的函数封装,让代码更直观

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:52:43