再次播放代码问题

时间:2014-05-05 15:13:04

标签: python python-2.7

我遇到代码问题,让某人“再次玩”"。这是代码:

playing = True
while playing:
    game()
    play_again = raw_input("Would you like to play again? Y|N").lower
    if (play_again == "n"):
        playing = False

然而,在我输入" n"或者" N",无论如何,游戏再次播放。任何想法?

2 个答案:

答案 0 :(得分:3)

您存储了str.lower方法,而不是结果。将()添加到实际调用该方法:

raw_input("Would you like to play again? Y|N").lower()

Python方法就像其他所有对象一样,你可以像存储字符串那样存储它们:

>>> 'NO'.lower
<built-in method lower of str object at 0x1058d8c88>
>>> 'NO'.lower()
'no'

不使用标志变量,而是使用break退出循环,而True使循环无止境:

while True:
    game()
    play_again = raw_input("Would you like to play again? Y|N").lower
    if play_again == "n":
        break

此处break关键字将在此处 结束循环,而无需先循环回顶部并测试变量。

答案 1 :(得分:1)

    play_again = raw_input("Would you like to play again? Y|N ").strip().lower()