【发布时间】:2016-01-25 20:06:14
【问题描述】:
我正在学习 python,正在创建一个石头剪刀布游戏。
我被困在一个部分。
我目前有 4 个变量(虽然我想把它减少到 2 个)
- pKey
- pChoice
- comKey
- comChoice
他们分别在字典中查找 Key 和 Value。
choice = {1:'rock', 2:'paper', 3:'scissors'}
我遇到的问题是使用变量从字典中获取键。
这是给我带来麻烦的代码 sn-p
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)
我已经尝试了我所知道的一切,包括使用括号、尝试不同的方法和使用不同的格式。
很想学这个!谢谢!
【问题讨论】:
-
小心
if pKey == 1 or 2 or 3。它没有做你认为的那样。 -
谢谢,我会不顾一切地说,如果 pKey == 1 或 pKey == 2 或 pKey == 3,我需要它:是在正确的轨道?
-
您可以使用
if pKey == 1 or pKey == 2 or pKey == 3,也可以使用if pKey in [1, 2, 3]。然而现在这永远不会是真的,因为pKey是"1"、"2"或"3"。
标签: python dictionary setvalue