python - 为什么我的 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!")
解决方案
欢迎来到 StackOverflow!该错误处于while
循环状态
你的条件是:
while (user_wins + computer_wins) <= best_of:
当正确的是
while user_wins + computer_wins < best_of:
- 我删除了无用的括号(在此处检查运算符优先级)
- 条件是
while user_wins + computer_wins < best_of
。当您运行while
循环时,它会检查条件然后运行代码。因此,在您的情况下,它应该中断 ifuser_wins + computer_wins == best_of
。正因为如此,你应该使用<
而不是<=
推荐阅读
- jquery - 如何通过 PDFMonkey 的 jQuery/Classic ASP 中的 webhook 启动/读取?
- reactjs - 单击 ReactJS 的图像时打开新选项卡
- php - 从 codeception 代码覆盖率报告中排除所有包含常用术语的目录
- python - 可以从 Python 中的 mdf 文件中提取信号的时间戳吗?
- c# - c# 向 SQL 存储过程发送地理参数
- hive - 当少数表没有主键时,sqoop import-all 具有并行性
- javascript - python设置变量等于null如果没有输入否则不是特定类型然后是字符串
- angular - 在 Angular 8 中更改另一个下拉列表时更新下拉列表值
- multithreading - 将数据传递给线程和脚本
- sql - 如何获取没有单个最大值行的行