我该如何返回一个输入值?

编程语言 2026-07-09

我想在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 = input() 这一行放在 make_user_choice() 的内部。把它作为函数下的第一行代码,并且放在while user_input != "rock...." 的第一行之下。这样就会获取用户输入,然后继续执行while循环,直到检查出用户的输入是否有效。接着,在while循环中删除break关键字和return(user_input);你只需要在整个逻辑之外再放一个return,因为只有在用户输入有效时它才会执行。还有,你使用的 'or' 会在用户输入有效时也触发无效输入的处理,例如如果用户输入rock,虽然while user_input != rock已经成立,但另外两个条件还没成立,这时请改用 'and'。下面是我认为正确的代码应该像这样:

def make_user_choice():
    """Returns the user's choice of rock, paper, or scissors if it is correct."""
    user_input = input("Choose one: rock, paper, scissors?"
    while user_input != "rock" and user_input != "paper" and user_input != "scissors":
        print("that is not a valid input. please try again")
        user_input = input("Choose one: rock, paper, scissors?"
    return(user_input)

并且也删除你代码顶部的第一行user_input = input(""),更好的一点是你甚至可以直接把冗长的while条件替换掉,或者更好地在整段代码里都加上.lower() 以将输入全部转换为小写

while user_input not in ["rock", "paper", "scissors"]

备选方案

你可能应该在 make_user_choice() 函数内获取用户输入。

大致如下:

RPS = ["rock", "paper", "scissors"]
PROMPT = "Choose one: " + ", ".join(RPS) + ": "

def make_user_choice():
    while (user_input := input(PROMPT)) not in RPS:
        print("that is not a valid imput. please try again")
    return user_input

print(make_user_choice())

如果 RPS 是一个集合,那么性能会更好。然而,这并不能保证提示中显示选项的顺序。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章