首页 > 解决方案 > 从另一个函数获取数据

问题描述

但是,我有一个简短的问题,我正在尝试制作一个测验程序。我希望在整个程序中共享函数数据,

那么我该如何让 ask 函数 gen 从 getQuestion 中获取数据呢?

import random

All_questions = ["whats obamas last name ","Riclug is snygg ","Are traps gay "]
questions_Right = ["care","no","no"]
points = 0
tries = 3
ListNumber = len(All_questions)

def getQuestion():
    question_number = random.randint(0, ListNumber - 1)
    right_anwser = questions_Right[question_number]
    Question = All_questions[question_number]

def ask(Question,right_anwser):
    print("The question is: ")
    anwser = input(Question+": ").casefold()
    if anwser == right_anwser:
        print("yes,", right_anwser,"was right\n")
        All_questions.remove(Question)
        questions_Right.remove(right_anwser)
    else:
        print("Sorry, but the answer was", right_anwser,"\n")
while True:
    if ListNumber == 0:
        print("Game over")
        break
    else:
        print(ListNumber)
        getQuestion()
        ask()
        print(All_questions)

标签: python

解决方案


只需简单地使用return

def getQuestion():
    # ... your code
    return (Question,  rightAnswer)

#... your code

Question, rightAnswer = getQuestion()

也许尝试使用字典,而不是问题和答案数组。那会更合适。

在继续进行问答游戏之前,我建议您进一步阅读并制作一些教程:

  1. 关于函数: https ://www.programiz.com/python-programming/function
  2. 关于字典: https ://www.programiz.com/python-programming/dictionary

推荐阅读