如何在make_user_choice函数的while循环中正确返回user_input变量?
问题:剪刀石头布游戏中
make_user_choice函数的循环返回问题 我尝试在make_user_choice函数的while循环中返回user_input变量,但不清楚正确的实现方式,当前代码运行出现异常。
原代码
import random """Supports a round of rock, paper, scissors between a user and a computer.""" user_input = input("Choose one: rock, paper, scissors? ") def make_user_choice(): """Returns the user's choice of rock, paper, or scissors if it is correct.""" while user_input != "rock" or user_input != "paper" or user_input != "scissors": print("that is not a valid imput. please try again") break return user_input return user_input def make_computer_choice(): """Returns the computer's random choice of rock, paper, or scissors.""" choice = random.randint(1,3) if choice == 1: return "rock" elif choice == 2: return "paper" if choice == 3: return "scissors" def wins_matchup(choice, opponent_choice): """Returns True if the first player's choice wins over their opponent. Choices can be rock, paper, or scissors. Assumes the choices are different. """ return choice == "rock" def format_score(user_score, computer_score): """Returns a formatted version of the players's current scores.""" return ">> Score: " + str(user_score) + "-" + str(computer_score)
运行输出
Choose one: rock, paper, scissors? rtgyhuji that is not a valid imput. please try again rtgyhuji (you) vs. rock Computer wins! >> Score: 0-1 that is not a valid imput. please try again rtgyhuji (you) vs. paper Computer wins! >> Score: 0-2
问题分析与修正
核心错误点:
- 全局变量误用:
user_input定义在函数外,属于全局变量,一旦输入错误值,函数内不会重新获取新输入,导致错误值一直被重复使用。 - 循环条件逻辑错误:
while user_input != "rock" or user_input != "paper" or user_input != "scissors"用了or,任何值都不可能同时等于三个选项,导致循环条件永远为真,失去校验意义。应该换成and,表示输入不是三个选项中的任意一个时才循环。 - break语句无效:break直接跳出循环,导致无法重新获取输入,循环校验的作用完全失效。
- return语句位置错误:break后的return永远不会被执行,正确逻辑应该是在循环内反复获取输入,直到输入有效后再返回。
修正后的make_user_choice函数
def make_user_choice(): """Returns the user's choice of rock, paper, or scissors if it is correct.""" while True: user_input = input("Choose one: rock, paper, scissors? ") if user_input in ["rock", "paper", "scissors"]: return user_input print("that is not a valid input. please try again")
同时需要删除全局的user_input = input(...)语句,因为输入逻辑已经整合到函数内部。
其他可优化点:
wins_matchup函数逻辑不完整,当前仅判断了choice == "rock",补充完整胜负规则:def wins_matchup(choice, opponent_choice): """Returns True if the first player's choice wins over their opponent. Choices can be rock, paper, or scissors. Assumes the choices are different. """ winning_pairs = { "rock": "scissors", "paper": "rock", "scissors": "paper" } return winning_pairs[choice] == opponent_choicemake_computer_choice可以简化为直接从列表随机选择:def make_computer_choice(): """Returns the computer's random choice of rock, paper, or scissors.""" return random.choice(["rock", "paper", "scissors"])
内容的提问来源于stack exchange,提问作者nathan
相关产品推荐
相关产品推荐

