Python 为什么我的代码处理不正确?它总是返回错误的行?
如果计算机随机选取某个字母,它应该返回某一行,但它只选择一个实例反复重复,即使满足打印另一个句子的条件Python 为什么我的代码处理不正确?它总是返回错误的行?,python,random,Python,Random,如果计算机随机选取某个字母,它应该返回某一行,但它只选择一个实例反复重复,即使满足打印另一个句子的条件 import random Player_Score = 0 Computer_Score = 0 while Player_Score < 5 or Computer_Score < 5: Player_object = input("Would you like to choose R, P, or S?") Computer_object = str(rand
import random
Player_Score = 0
Computer_Score = 0
while Player_Score < 5 or Computer_Score < 5:
Player_object = input("Would you like to choose R, P, or S?")
Computer_object = str(random.sample(set(["R", "P", "S"]), 1))
if Player_object == "R" or Player_object == "r":
if str(Computer_object) == "R":
print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have tied with the Computer and neither of you have scored a point.")
elif str(Computer_object) == "P":
Computer_Score = Computer_Score + 1
print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ". You have been beaten by the Computer and it has scored a point.")
else:
Player_Score = Player_Score + 1
print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have beaten the Computer scored a point.")
str(random.sample(set([“R”、“p”、“S]”),1))
返回“['S']”而不是'S'
,因此您的代码总是进入else条件
相反,请尝试使用random.sample(“RPS”,1)[0]
,它将返回列表的第一个(也是唯一一个)元素,或者使用random.choice('RPS')str(random.sample(set([“R”,“p”,“S”),1))
返回“['S']”而不是'S'
,因此您的代码总是进入else条件
相反,请尝试使用random.sample(“RPS”,1)[0]
,它将返回列表的第一个(也是唯一的)元素,或者使用random.choice('RPS')random。sample
返回一个列表,因此str(计算机对象)
将永远不会等于“R”
,“p”
,等等。。试着打印random.sample(set([“R”,“P”,“S”),1)
看看我的意思,然后使用random.sample(set([“R”,“P”,“S”),1)[0]
并注意差异。当你昨天问了几乎相同的问题时()有人向你指出你使用random.sample()
错误,他们建议改为random.choice()
。random.sample
返回一个列表,因此str(计算机对象)
永远不会等于“R”
,“P”
,等等。。试着打印random.sample(set([“R”,“P”,“S”),1)
看看我的意思,然后使用random.sample(set([“R”,“P”,“S”),1)[0]
并注意差异。当你昨天问了几乎相同的问题时()有人向你指出你使用random.sample()
错误,他们建议改为random.choice()
。或者跳过索引并使用random.choice(seq)
。或者跳过索引并使用random.choice(seq)
。
Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['R'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['P'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['S'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['S'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['R'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['P'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?