以下是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
答案 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
的用户输入(可能是no
或answer
},Python检查("y", "yes", "Y", "Yes", "Of course")
中是否显示此变量。
这是一个小小的语法糖。
你也可以这样做:
for x in ("y", "yes", "Y", "Yes", "Of course"):
if answer == x:
return answer
docs中有关python操作数的更多信息(例如is
,is not
和not in
)。
答案 3 :(得分:0)
answer in ("y", "yes", "Y", "Yes", "Of course")
等于True
个元素中的任何一个,则 answer
评估为("y", "yes", "Y", "Yes", "Of course")
。