Skip to main content
 首页 » 编程设计

Python:如何通过 randChoice 选择另一个变量来打印一个变量

2025年02月15日8zhenyulu

我是一名 APCSP 高中学生,我们的一项开放式作业是创建一个具有教育功能的程序。这是我将在主程序中调用的特定 Python 函数:

def worldStudyQuestions(): 
    worldStudying = True 
    while worldStudying: 
        print ("Thanks for studying world history!") 
        print ("This study guide consists of ten questions about ancient religions. \n") 
        w1 = "Which religion focused on the preservation of all natural things?" 
        w1Ans = "Jainism required adherents to move slowly so as to not kill souls living in different objects." 
        w2 = "Was the Roman state religion monotheistic or polytheistic?" 
        w2Ans = "Polytheistic; they based their gods on the Greek gods." 
        w3 = "What was the Buddha's original name?" 
        w3Ans = "Siddhartha Gautama" 
        w4 = "Which Greek cult often fled to the mountains to drink wine?" 
        w4Ans = "Cult of Dionysus" 
        w5 = "How many tribes of Israel existed?" 
        w5Ans = "Twelve" 
        w6 = "Did Confucians look up to a god?" 
        w6Ans = "No, they were primarily philosophical." 
        w7 = "Where did Gabriel first make contact with Muhammad?" 
        w7Ans = "In a cave near Mecca." 
        w8 = "What attracted the lower classes to Hinduism?" 
        w8Ans = "Hinduism disregarded the traditional caste system of imperial India." 
        w9 = "" 
        w9Ans = "" 
        w0 = "" 
        w0Ans = "" 
        worldQuestionList = [w1, w2, w3, w4, w5, w6, w7, w8, w9, w0] 
        worldAnsList = [w1Ans, w2Ans, w3Ans, w4Ans, w5Ans, w6Ans, w7Ans, w8Ans, w9Ans, w0Ans] 
        print ("Question 1:", random.choice(worldQuestionList)) 
        worldStudying = False 

假设 random.choice 从 worldQuestionList 中选择 w5,我希望在用户输入空字符串时显示 w5Ans,然后在下一次迭代时将 w5 从随机化过程中删除。我如何实现这一点?

请您参考如下方法:

简单,只需在用户回答后从列表中弹出问题和答案。就像

ch=random.randint(0,len(worldQuestionList)) 
print ("Question 1:",worldQuestionList[ch]) 
#Use same for answer like worldAnsList[ch] 
# Finally Remove both like below 
worldQuestionList.pop(ch) 
worldAnsList.pop(ch)