【发布时间】:2020-06-20 08:24:42
【问题描述】:
此代码将让 2 名玩家从列表中随机回答一个问题,然后比较他们的分数。
问题:
- 由于
randint,问题不断重复,尝试使用random.shuffle— 不成功。 - 如果我输入的答案在不同问题的答案列表中,它仍会打印“正确”
可能是因为这个代码
if guess.lower() == answers[a].lower():。 - 我不能让它工作,如果答案是错误的,它会打印“错误”。 我尝试添加此代码并且它有效,但如果我输入正确答案,它仍然返回“错误”。
elif guess.lower() != answers[a].lower():
print("Wrong!")
break
我的代码
from random import randint
print("====== Quiz Game ======")
print("")
questions = [
"What star is in the center of the solar system?:",
"What is the 3rd planet of the solar system?:",
"What can be broken, but is never held?:",
"What part of the body you use to smell?:",
"How many days in one year?:",
"How many letters in the alphabet?:",
"Rival of Intel?:",
"No.8 element on periodic element?:",
"What is the galaxy that contains our solar system?:",
"What animal is the king of the jungle?:"
]
answers = [
"Sun",
"Earth",
"Promise",
"Nose",
"365",
"26",
"AMD",
"Oxygen",
"Milky Way",
"Lion"
]
p1score = 0
p2score = 0
def playerOne():
global p1score
for i in range(5):
q = randint(0,9)
guess = input(questions[q])
for a in range(len(answers)):
if guess.lower() == answers[a].lower():
print("Correct!")
p1score += 1
break
else:
continue
print("Your score is:",p1score)
print("")
def playerTwo():
global p2score
for i in range(5):
q = randint(0,9)
guess = input(questions[q])
for a in range(len(answers)):
if guess.lower() == answers[a].lower():
print("Correct!")
p2score += 1
break
else:
continue
print("Your score is:",p2score)
print("")
def quiz():
global p1score
global p2score
print("======Student no.1======")
playerOne()
print("======Student no.2======")
playerTwo()
if p1score > p2score:
print("Student 1 has the highest score!")
elif p1score < p2score:
print("Student 2 has the highest score!")
elif p1score == p2score:
print("Students are tied!")
else:
print("Invalid")
quiz()
【问题讨论】:
-
欢迎来到 Stack Overflow。请阅读Why is "Can someone help me?" not an actual question?
-
我会这样做,创建一个空列表 seen_questions 并将问题附加到列表中,因此每次随机选择一个问题时,请检查 seen_questions 如果问题已经被选中,则首先打印出问题。制作一个问题和答案字典,其中键=问题,值=答案。
-
您可以在开始时使用
random.shuffle(list)- 以随机顺序获取元素 - 稍后仅使用for-loop 从这个随机列表中获取问题。但是您必须将问题和答案放在一个列表中 - 将它们混在一起。
标签: python python-3.x list python-2.7 random