我在学习python,正在创建一个石头布剪刀游戏。你知道吗
我被困在一个地方。你知道吗
我现在有4个变量(尽管我想把它降到2)
他们分别在字典中查找关键字和值。你知道吗
choice = {1:'rock', 2:'paper', 3:'scissors'}
我遇到的问题是使用变量从字典中获取密钥。你知道吗
这是给我带来麻烦的代码片段
print('--- 1 = Rock 2 = Paper 3 = Scissors --- ')
pKey = input() # this is sets the key to the dictionary called choice
while turn == 1: # this is the loop to make sure the player makes a valid choice
if pKey == 1 or 2 or 3:
pChoice = choice.values(pKey) # this calls the value from choice dict and pKey variable
break
else:
print('Please only user the numbers 1, 2 or 3 to choose')
comKey = random.randint(1, 3) # this sets the computer choices
comChoice = choice.values(comKey)
特别是麻烦的部分是
pChoice = choice.values(pKey)
以及
comChoice = choice.values(comKey)
我尝试了我所知道的一切,从使用括号,尝试不同的方法,使用不同的格式。你知道吗
我很想学这个!谢谢!你知道吗
听起来你只是想查字典
dict.values
用于创建包含字典所有值的列表(实际上是一个dict_values
对象)。它不用作查找。你知道吗就您的代码结构而言,它可能需要一些工作。石头/布/剪刀的选择对于一个
Enum
来说是完美的,但这可能是你现在有点无法理解的。让我们试着作为顶级模块常量。你知道吗将它们作为常量进行寻址可以确保它们在代码中的任何地方都是相同的,否则会出现非常明显的NameError(而不是因为执行了
if comChoice == "scisors"
而导致if分支未执行)枚举的最小示例如下所示:
您可以通过使用更详细的枚举定义来扩展这一点,并教每个Choice实例如何计算赢家:
不幸的是,没有什么好的方法可以在这方面失去抽象性(抽象出“纸”到选择.纸张每次调用它)因为你不知道当
Choices.rock
被实例化时Choices["paper"]
是什么。你知道吗你不知道如何从dict中提取元素,你的代码应该是这样的:
对我来说很好。你知道吗
相关问题 更多 >
编程相关推荐