【问题标题】:While Loop isnt breaking虽然循环没有破坏
【发布时间】:2021-10-02 12:58:55
【问题描述】:

当我运行程序时,即使 game rounds 等于 rounds 尝试了不同的方法,但仍然存在问题或只是我看不到的东西,它也会一遍又一遍地循环

代码如下:


print('Rock Paper Scissors!\n"r" for rock, "p" for paper, "s" for scissors\n')
rounds = int(input('How many rounds?: '))
game_round = 0
game = game_round != rounds
while game:
    user = input('\nRock, Paper, Scissors?: ').lower()
    computer = random.choice(['r', 'p', 's'])
    print(f'Computer: {computer}\n')
    player = user
    opponent = computer
    user_win = 0

    # r > s, s > p, p > r
    # if player wins:
    player_win = (player == 'r' and opponent == 's') or (player == 's' and opponent == 'p') or (player == 'p' and opponent == 'r')
    # if computer wins:
    computer_w = (opponent == 'r' and player == 's') or (opponent == 's' and player == 'p') or (opponent == 'p' and player == 'r')

    if user == computer and game:
        game_round = game_round + 1
        print('Tie!')

    if player_win and game:
        user_win = user_win + 1
        game_round = game_round + 1
        print('You win!')

    if computer_w and game:
        game_round = game_round + 1
        print('You loose!')

    if game is False:
        print(f'Score {user_win}/{rounds}')```

【问题讨论】:

  • 你在哪里将false 分配给game
  • game 变量没有意义,只需将while循环设置为条件while game_round != round

标签: python loops while-loop


【解决方案1】:

正如 Sayse 在评论中所说,您可以这样做:

user_win = 0 # <- put user_win outside the loop so you can access it outside the loop.

while game_round != round:
   # other code

print(f"Score {user_win}/{rounds}")

【讨论】:

    猜你喜欢
    • 2021-12-14
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2020-08-05
    • 2015-05-08
    • 1970-01-01
    相关资源
    最近更新 更多