Break命令不停止循环

2024-07-04 05:38:53 发布

您现在位置:Python中文网/ 问答频道 /正文

Break命令不起作用,当我尝试运行它时,它会像无法编译一样被卡住,因为它卡在一个循环中

我的代码根本没有运行,我已经检查了我的代码,但它似乎不起作用。对我来说一切都很好

import random
# print("Winning Rules of the Rock paper scissor game as follows: \n"
#       + "Rock vs paper->paper wins \n"
#       + "Rock vs scissor->Rock wins \n"
#       + "paper vs scissor->scissor wins \n")
while True: 
 def main():
    print("Enter choice \n 1. Rock \n 2. paper \n 3. scissor \n")
    try : 
        choice_name = (input("User turn: "))
        if choice_name == 1:
            choice_name = 'Rock'
        if choice_name == 2:
            choice_name = 'paper'
        if choice_name == 3:
            choice_name = 'scissor'
        else: 
            choice_name = None
            input("Atleast Enter a Valid Number like BRUHHHHHHHHH: ")
    except ValueError: 
        print ("Try again")     
        main()
    print("user choice is: " + choice_name)
    print("\nNow its computer turn.......")

    Computer_Choice = random.randint(1, 3)

    while Computer_Choice == choice_name:
        Computer_Choice = random.randint(1, 3)

    if Computer_Choice == 1:
        Computer_Choice_name = 'Rock'
    elif Computer_Choice == 2:
        Computer_Choice_name = 'paper'
    else:
        Computer_Choice_name = 'scissor'

    print("Computer choice is: " + Computer_Choice_name)

    print(choice_name + " V/s " + Computer_Choice_name)

    if((choice_name == 1 and Computer_Choice == 2) or
       (choice_name == 2 and Computer_Choice == 1)):
        print("paper wins => ", end="")
        result = "paper"

    elif((choice_name == 1 and Computer_Choice == 3) or
         (choice_name == 3 and Computer_Choice == 1)):
        print("Rock wins =>", end="")
        result = "Rock"
    else:
        print("scissor wins =>", end="")
        result = "scissor"

    if result == choice_name:
        print("<== User wins ==>")
    else:
        print("<== Computer wins ==>")

    print("Do you want to play again? (Y/N)")
    ans = input()

    if ans == 'n' or ans == 'N': 
     break
print("\nThanks for playing")

1条回答
网友
1楼 · 发布于 2024-07-04 05:38:53

您正在while循环中定义一个函数。当前,循环的计算结果始终为False

你想要的是:

def main():
    while True:
        # ...

然后您需要实际调用main。在文件末尾:

if __name__ == '__main__':
    main()

相关问题 更多 >

    热门问题