Python如何将此语句解释为True?

时间:2015-07-09 15:30:10

标签: python if-statement

以下是RockPaperScissors代码的一部分,我无法弄清楚Python如何解释

if answer in ("y", "yes", "Y", "Yes", "Of course"):
    return answer

因此返回为True。

以下代码的其他部分返回一个Integer

player = int(player)
if player in (1, 2, 3):
    return player

它是如何为一个零件返回True而在另一个零件中返回一个Integer,因为它是相同的结构?

基于以下代码:

def start():
    print "Let's play a game of Rock, Paper, Scissors"
    while game():
        pass
    scores()

def game():
    player = move()
    computer = random.randint(1, 3)
    result(player, computer)
    return play_again()

def move():
    while True:
        print
        player = raw_input("Rock = 1\nPaper = 2\nScissors = 3\nMake a move : ")
        try:
            player = int(player)
            if player in (1, 2, 3):
                return player
        except ValueError:
            print "Oops ! I didn't understand that, Please enter 1, 2 or 3."

def result(player, computer):
    print "1..."
    time.sleep(1)
    print "2..."
    time.sleep(1)
    print "3 !"
    time.sleep(0.5)
    print "Computer threw {0}!".format(names[computer])
    global player_score, computer_score
    if player == computer:
        print "Tie game"
    else:
        if rules[player] == computer:
            print "victory getting closer !"
            player_score += 1

def play_again():
    answer = raw_input("Would you like to play again ?")
    if answer in ("y", "yes", "Y", "Yes", "Of course"):
        return True
    else:
        print "ok that's enough for today !"

def scores():
    global player_score, computer_score
    print "HIGH SCORES"
    print "Player : " + player_score
    print "Computer :" + computer_score

4 个答案:

答案 0 :(得分:4)

如果answer("y", "yes", "Y", "Yes", "Of course")的元素,则评估为True

答案 1 :(得分:3)

您认为return answer会返回True。它没有。

它返回answer的值,它将是一个非空字符串,等于元组中的一个字符串。因此,如果您输入play_again(),函数'Y'将返回'Y',因为answer位于元组中。

if在列表中的值时,else:套件未执行,因此return分支会打印一条消息,函数结束时没有None语句。然后Python返回play_again()

所以("y", "yes", "Y", "Yes", "Of course")要么返回一个非空字符串,一个是元组None的成员,返回game()while返回该值不变,返回start()中的while game(): pass 循环:

while

返回值的None语句tests the truth value。非空字符串被认为是真的(因此循环继续),{{1}}被认为是假(循环结束)。

答案 2 :(得分:1)

根据分配给变量yes的用户输入(可能是noanswer},Python检查("y", "yes", "Y", "Yes", "Of course")中是否显示此变量。

这是一个小小的语法糖。

你也可以这样做:

for x in ("y", "yes", "Y", "Yes", "Of course"):
    if answer == x:
        return answer

docs中有关python操作数的更多信息(例如isis notnot in)。

答案 3 :(得分:0)

如果answer in ("y", "yes", "Y", "Yes", "Of course")等于True个元素中的任何一个,则

answer评估为("y", "yes", "Y", "Yes", "Of course")