首页 > 解决方案 > 为什么我的 while 循环中的条件在 python 中不起作用?

问题描述

我试图创建一个程序,您可以在其中与计算机玩石头剪刀布。我设法在基本水平上做到了,但我想升级游戏,以便您可以跟踪用户和计算机在用户决定的总游戏中赢得了多少。

我使用了一个while循环,只要玩的总游戏数(不包括平局)不超过用户一开始决定的“最佳”游戏,它就会执行并继续游戏。但它不起作用。例如,如果我决定用电脑玩 3 场比赛中最好的比赛,并且我赢了 3 次,它仍然会要求我输入石头或剪刀。

import random

# keep track of who wins throughout the game
user_wins = 0
computer_wins = 0

# list of possible inputs to play the game
options = ["r", "p", "s"]

#user chooses how many games to play on aggregate
best_of = int(input('Best out of: '))

print(best_of)

# define a function that takes in two players as arguments
# and returns True if player wins based on the standard rules
# of rock paper scissors
def is_winner(player, opponent):
    if (player == 'r' and opponent == 's') or \
    (player == 'p' and opponent == 'r') or \
    (player == 's' and opponent == 'p'):
        return True
    
# game continues while the number of games(not inclunding ties) 
# does not exceed best_of
while (user_wins + computer_wins) <= best_of:
    user_input = input("""
    What do you play?
    'r' for rock,
    'p' for paper,
    's' for scissors
    Press 'q' to quit: """).lower()
    
    # loop breaks if user enters 'q'
    if user_input == "q":
        break
    
    # if user_input is not 'r', 'p', or 's', then has to try again
    if user_input not in options:
        continue
    
    #computer selects 'r', 'p' or 's' randomly
    computer_pick = random.choice(options)

    #print each players input
    print("You picked: ", user_input)
    print("Computer picked: ", computer_pick)

    # if inputs are the same then, game is tie and goes through loop again
    if user_input == computer_pick:
        print('It\'s a tie!')
        continue

    # if the player is winner, print a win message and add 1 to the user_wins variable
    elif is_winner(user_input, computer_pick):
        print('You won!')
        user_wins += 1

    # by default, if player doesnt win AND not a tie, the computer wins
    # so prints 'you lost' and add 1 to computer_wins
    else:
        print("You lost!")
        computer_wins += 1

#print final score once game is finshed
print("You won ", user_wins, " times.")
print("The computer won ", computer_wins, " times.")
print("Goodbye!") 

标签: pythonwhile-loopuser-defined-functions

解决方案


欢迎来到 StackOverflow!该错误处于while循环状态

你的条件是: while (user_wins + computer_wins) <= best_of:

当正确的是 while user_wins + computer_wins < best_of:

  1. 我删除了无用的括号(在此处检查运算符优先级)
  2. 条件是while user_wins + computer_wins < best_of。当您运行while循环时,它会检查条件然后运行代码。因此,在您的情况下,它应该中断 if user_wins + computer_wins == best_of。正因为如此,你应该使用<而不是<=

最后,我用PEP8重新格式化了你的代码。您可以在此处在线执行相同的操作。


推荐阅读