if循环中的过程即使满足条件也不起作用

时间:2017-12-07 18:09:59

标签: python if-statement

我已经制作了这个代码来模拟一个石头剪刀游戏。我有一个主游戏的程序,当我自己运行它而没有if循环结束时,它的工作原理。但是,当我尝试验证用户条目是否为数字时,它不会打印正确的消息。这是完整的代码:

import random
def game(choice):
    number = random.randint(1,3)
    if choice == 1 and number == 2:
        print("You lose.")
    if choice == 1 and number ==3:
        print("You win.")
    if choice == 1 and number == 1:
        print("It is a draw")
    if choice == 2 and number == 3:
        print("You lose.")
    if choice == 2 and number ==1:
        print("You win.")
    if choice == 2 and number == 2:
        print("It is a draw")
    if choice == 3 and number == 1:
        print("You lose.")
    if choice == 3 and number ==2:
        print("You win.")
    if choice == 3 and number == 3:
        print("It is a draw")  
x = input("Choose 1 (rock), 2 (paper) or 3 (scissors).")
digit = x.isdigit()
if digit == True:
    game(x)

顺便说一句,没有错误信息,程序就行不通了!

1 个答案:

答案 0 :(得分:0)

首先,您的代码存在一些问题。如果您想忽略,请跳至错误处理以回答您的问题。你会在那里找到它。

命名变量

您的变量不会告诉读取您代码的人他们是什么。如果你向某人展示number这个词,他们就不会知道这是计算机在石头剪刀中选择的东西。与choice(选择谁?)相同,甚至更为x。那么为什么我们不能分别命名computer_choiceuser_choicechoice。我知道这些打字时间要长一些,但是为了更清晰一点,值得牺牲一些额外的击键。另请注意,我按照通常的Python标准使用了snake_case名称格式。

重复性/ game()

你的game函数可以做一些重做。您只需要一个通用的配方'输赢。在这种情况下,失败的时间是(感谢@Brett Beatty)if computer_choice == (user_choice + 1) % 3,绘图是computer_choice == user_choice,获胜是else。此外,当您的代码正在播放时,用户只知道他们是赢了还是输了,而不是计算机选择了什么,所以为了更加清晰,我添加了一个列表和另一个print()行。此功能对测试代码也很有用。此外,使用从零开始的变量值,例如computer_choiceuser_choice变量。将值转换为列表索引时,这非常有用。下面是我所编写的代码的修订版本,其中包含了上述所有要点(我还将其作为一个函数,如下所示 - 我认为它看起来更好):

import random


def game(user_choice):
    user_choice -= 1
    rps = ["Rock", "Paper", "Scissors"]
    computer_choice = random.randint(0, 2)
    print("You: {} Computer: {}".format(rps[user_choice], rps[computer_choice]))
    if user_choice == computer_choice:
        return 0
    elif computer_choice == (user_choice + 1) % 3:
        return -1
    else:
        return 1

错误处理

要确保用户输入整数,您必须在输入语句周围添加int()。但是,如果用户输入的值不是整数,那么单独返回ValueError,这是一个问题。但是,有一种方法可以使用try: except: else:块来解决此问题,如下所示。这是你需要决定值是否为整数,它还会打印正确的消息。我也认为这是你想要的if digit == True(仅供参考,如果你这样做,你只需要if digit)。

def main():
    while True:
        try:
            value = int(input("Choose 1 (rock), 2 (paper) or 3 (scissors):"))
        except ValueError: # If any part of the code in the try block raises a ValueError
            print("Not an integer")
        else:  # If error is not raised
            if not 1 <= value <= 3: # If value is not between 1 and 3
                print("Must be between 1 and 3")
            else:
                result = game(value) # sets result to return value from game()
                break
    if result == 1:
        print("You Win")
    elif result == -1:
        print("You Lose")
    else:
        print("It's a Draw")

最后,&#39; if loop&#39;?

让我说清楚。没有if loop这样的东西!如果某个条件为if,则True语句会运行代码 ** ONCE ** 。我想你想要的是一个while循环。只要某个条件为True,它就会运行代码 ** REPEATEDLY ** 。在下面的代码中,我创建了一个while True循环,每次用户输入"y"时都会运行代码,如果没有,则会在循环中运行break
另外,使用if __name__ == '__main__'。它存在于Python中,因此Python文件既可以作为可重用模块,也可以作为独立程序。如果你想看起来很聪明,它看起来也会更复杂。

if __name__ == '__main__':
    while True:
        main()
        if input("Again? Yes(y) No(Anything else): ").lower() != 'y':
            break

示例输出(忽略颜色):

Choose 1 (rock), 2 (paper) or 3 (scissors):1
You: Rock Computer: Scissors
You Win
Again? Yes(y) No(Anything else): y
Choose 1 (rock), 2 (paper) or 3 (scissors):3
You: Scissors Computer: Scissors
It's a Draw
Again? Yes(y) No(Anything else): y
Choose 1 (rock), 2 (paper) or 3 (scissors):2
You: Paper Computer: Paper
It's a Draw
Again? Yes(y) No(Anything else): n

Process finished with exit code 0

此外,对于OP,如果您还没有,我建议您下载Pycharm。它完全免费,使编码更容易。它也改善了演示。它了解了上面提到的一些事情,并保持您的代码符合PEP指南。

相关问题