-2

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

那么我该如何让 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)
4

2 回答 2

1

只需简单地使用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
于 2020-06-20T11:53:28.097 回答
1
import random

All_questions = ["whats obamas last name ","Riclug is snygg ","Are traps gay "]
questions_Right = ["care","no","no"]



def getQuestion(All_questions, questions_Right):
    question_number = random.randint(0, len(All_questions) - 1)
    
    right_answer = questions_Right[question_number]
    question = All_questions[question_number]
    
    return question, right_answer # added this to return the data



def ask():
    Question, right_answer = getQuestion(All_questions, questions_Right)
    
    answer = input(f"The question is :\n{Question} :").casefold()
    
    if answer == right_answer:
        print(f"Yes, {right_answer} was right\n")
        All_questions.remove(Question)
        questions_Right.remove(right_answer)
    
    else:
        print(f"Sorry, but the answer was {right_answer}\n")



while True:
    if len(All_questions) == 0:
        print("Game over")
        break
    else:
        ask()

1 - 您可以通过执行以下操作返回所需的数据:

return question, right_answer

2 - 由于问题列表每轮都会改变,因此最好将其传递给 getQuestion 方法,而不是直接使用全局方法并用于len(All_questions)每轮获取新长度:

def getQuestion(All_questions, questions_Right)

3 - 一些建议:

  • 使用蛇皮
get_question
# instead of :
getQuestion
  • 不要在函数内部使用全局变量:
A = 1
def add(a, b):
    return a + b
add(A, 5)

# instead of

A = 1
def add_to_A(b):
    return A + b
add_to_A(5):
  • 正确格式化代码并确保正确命名变量。
于 2020-06-20T11:59:48.977 回答