Python第三个函数While循环故障:重复询问与匹配错误求助
修复Python战斗地点函数的两处问题
问题分析
你的代码中Where_do_u_want_to_fight函数存在两个核心问题:
- 重复询问地点:外层代码已执行地点输入并将参数传入函数,但函数内部又包含
input语句,导致运行时两次询问战斗地点。 - 判断条件错误:函数内的条件判断使用传入的参数
a而非循环内获取的place进行匹配,导致输入正确地点后仍触发错误提示。
修复后的完整代码
def who_do_you_want_to_be(x): print("you will be " + x) print("Great choice!") def who_do_you_want_to_face(a, x): print(a + " will face " + x + "\n") def Where_do_u_want_to_fight(): while True: place = input("\nchoose to fight in either (pokemon stadium, planet namek, or the leaf village): ").lower() if place == "pokemon stadium": print("Not today but maybe tomorrow") print("Well also give you pokemon stadium music too but im in a rush") break elif place == "planet namek": print("Not today but maybe tomorrow") print("Well also give you planet namek music too but im in a rush") break elif place == "the leaf village": print("Not today but maybe tomorrow") print("Well also give you the leaf village music too but im in a rush") break else: print("Spell it correctly!\n") # 主程序逻辑 character = input("write what pokemon you want to be (charzard, pikachu, or Gyarados) :").lower() who_do_you_want_to_be(character) choice = input("\nwrite what pokemon you want to face (charzard, pikachu, or Gyarados) :").lower() who_do_you_want_to_face(character, choice) # 直接调用地点选择函数,无需提前输入 Where_do_u_want_to_fight()
关键修改说明
- 消除重复输入:移除外层的
place输入语句,删除Where_do_u_want_to_fight函数的参数a,让函数内部独立处理地点输入和循环验证逻辑。 - 修正判断条件:将函数内的判断条件从
a == ...改为place == ...,确保判断的是用户当前输入的地点值,解决正确输入仍提示错误的问题。
内容的提问来源于stack exchange,提问作者omar
相关产品推荐
相关产品推荐

