python - 如果有这么多的可能性,如何使用 elif 或 if 条件?
问题描述
我知道有比这更聪明和简短的答案,但它并没有打印我给出的条件。您对此有解决方案吗?以及如何在循环中使用 if 语句?
import random
game = input("Do you want to play the game? yes/no")
for x in range(1):
pc_input = random.randint(1,3)
rock = 1
paper = 2
scissors = 3
if game == "yes":
usr_input = input("Rock , paper , scissors ")
if pc_input == 1 and usr_input == 1:
print("Tied game...")
if pc_input == 1 and usr_input == 2:
print("You won")
if pc_input == 1 and usr_input == 3:
print("You lost")
if pc_input == 2 and usr_input == 1:
print("You lost")
if pc_input == 2 and usr_input == 2:
print("Tied game...")
if pc_input == 2 and usr_input == 3:
print("You won")
if pc_input == 3 and usr_input == 1:
print("You won")
if pc_input == 3 and usr_input == 2:
print("You lost")
if pc_input == 3 and usr_input == 3:
print("Tied game...")
解决方案
只有三种不同的行为,所以试着写一个if/elif
只有三个分支的链。您可以简化逻辑以在相同条件下检查更多选项:
diff = (pc_input - usr_input) % 3
if diff == 0:
print("Tied game...")
elif diff == 1:
print("You lost")
elif diff == 2:
print("You won")
diff
是模 3 的两个数字之间的差,即如果您将 1、2、3 视为一个循环(如石头、纸、剪刀),那么模 3 的差告诉您pc_input
在循环中“领先”多远,与usr_input
. 领先 2 与落后 1 是一样的。
推荐阅读
- android - Reack Native 版本 .apk 在更高版本的 android 设备中崩溃,地理定位权限被拒绝错误
- python - (美汤) 获取按钮标签内的数据
- visual-studio - 如何使用 Visual Studio 2017 构建 Gtk#/Mono 应用程序
- linux - 在汇编中附加两个字符串
- typescript - 使用函数接口来确保参数但推断更具体的返回类型
- java - Spring Testing Mock MVC 不应用自定义 RequestMappingHandlerMapping
- python - Spyder在执行python代码后挂起
- python - 从python中的嵌套json数组中提取数据
- javascript - 在数组中切片节点
- reactjs - 您可以在条件内使用 useState 中的“setter”吗?