【问题标题】:I think I'm making a function call error in the main file, but I can't figure out why我想我在主文件中犯了一个函数调用错误,但我不知道为什么
【发布时间】:2022-01-18 13:46:21
【问题描述】:

我希望考生能够将他的信息保存在 txt 文件中,然后开始考试。 我设法将候选人的个人信息保存在一个文件中并运行测试,但我不明白为什么它不打印分数。

import os

class Student:

    # constructor
    def __init__(self, name, surname):
        self.name = name
        self.surname = surname

    # ***********************************************************************************************************
    # we create a file called "candidate" in which the candidate enters his personal informations
    # don't forget to add an "r" before the path otherwise it doesn't work
    def candidate_file(self, name, surname):
        with open(r"C:\Users\Intervenant\Desktop\Projets\Python\candidate.txt", "a") as fileCandidate:
            fileCandidate.write("\n" + "Candidat's name : " + name)
            fileCandidate.write("\n" + "Candidat's surname : " + surname)
        
        # we then rename this "candidate" file with its name, all in a .txt file
        # os.rename(r"C:\Users\Intervenant\Desktop\Projets\Python\candidate.txt", name+".txt")

    # ***********************************************************************************************************

    

    # this function takes care of retrieving the answer of a candidate to a question
    def ask_answer(min, max): 
        answer = input("Your choice : ")

        try:
            answer = int(answer)
            if min <= answer <= max:
                return answer
            print("Enter a number between ", min, "and", max)

        except:
            print("Error ! Please enter a number")

        return Student.ask_answer(min, max)

    # ***********************************************************************************************************

    # this function takes care of asking questions to the candidate and counting the number of correct answers
    def ask_question(question):
        # question[1] represents the set of possible answers
        choice = question[1]
        # question[2] represents the correct answer
        rightAnswer = question[2]
        
        print("QUESTION"  )
        print("   ", question[0])

        """
        here len(choice) will calculate the size of the number of possible choices
        in the case of question 1, there are 4 possible choices
        so len(choice) = 3 (from 0 to 3)
        """
        for i in range(len(choice)):
            print(" ", i + 1, "-", choice[i])  # this is to display "2 - True" in question 1 for example

        
        answer = Student.ask_answer(1, len(choice))
        print()

        score = 0
        if choice[answer - 1] == rightAnswer:
            print()
            score += 1
        
        return score

    # ***********************************************************************************************************
    
    def set_questions(self, setQuestions):

        for question in setQuestions:
            Student.ask_question(question)
        
    

    # the set of questions of the exam
    setQuestions=(
        ("What is the output of the following code? print(5 >= 5) ",
            ("5 >= 5","True","False","None"),
            "True"
        ),
        ("Which of these data types is not a base type in Python?",
            ("Lists","Class","Dictionary","Tuples"), 
            "Class"
        ),
        ("What is the output of the following code? min(max(False,-2,-5), 1,5) ",
            ("-5","-2","1","False"),
            "False"
        ),
        ("What is the output of the following code? >>>t = (1, 2, 3) >>>t.append( (4, 5, 6) ) >>>print len(t)",
            ("3","4","6","Error"),
            "Error"
        ),
        ("What is the function that compares the elements of two lists?",
            ("cmp(list1, list2)","eq(list1, list2)","len(list1, list2)","max(list1, list2)"),
            "cmp(list1, list2)"
        )
        )
    # set_questions(setQuestions)
    # print("votre score est : ", ask_question(setQuestions),"sur", len(setQuestions))    

我尝试在 main 中调用 setQuestions 函数,但我意识到我没有什么可放入参数。 所以我将这组问题(在列表中)复制到了主目录中。 但这并没有解决问题,我不明白为什么。

# the main file

from classEtudiant import Student


name = input("Enter your name : ")
surname = input("Enter your surname : ")

print()
print("Welcome to the test Mr/Mrs", name, surname, " !")

# initialize a student
student = Student(name, surname)

# record the candidate's personal informations in a file
student.candidate_file(name, surname)

# launch the test

setQuestions=(
        ("Quelle est la sortie du code suivant? print(5 >= 5) ",
            ("5 >= 5","True","False","None"),
            "True"
        ),
        ("Lequel de ces types de données n’est pas un type de base en Python?",
            ("Lists","Class","Dictionary","Tuples"), 
            "Class"
        ),
        ("Quelle est la sortie du code suivant? min(max(False,-2,-5), 1,5) ",
            ("-5","-2","1","False"),
            "False"
        ),
        ("Quelle est la sortie du code suivant? >>>t = (1, 2, 3) >>>t.append( (4, 5, 6) ) >>>print len(t)",
            ("3","4","6","ERREUR"),
            "ERREUR"
        ),
        ("Quelle est la fonction qui compare les éléments des deux listes?",
            ("cmp(list1, list2)","eq(list1, list2)","len(list1, list2)","max(list1, list2)"),
            "cmp(list1, list2)"
        )
        )
    
student.set_questions(setQuestions)

# print the score of the student
print("Your score is : ", student.ask_question(setQuestions),"/", len(setQuestions))





【问题讨论】:

  • 它确实为我提出了这个问题!你能告诉我们运行脚本时发生了什么吗? python main.py Enter your name : Some Enter your surname : Guy Welcome to the test Mr/Mrs Some Guy ! QUESTION Quelle est la sortie du code suivant? print(5 &gt;= 5) 1 - 5 &gt;= 5 2 - True 3 - False 4 - None Your choice : 2 QUESTION Lequel de ces types de données n’est pas un type de base en Python? 1 - Lists 2 - Class 3 - Dictionary 4 - Tuples Your choice : 2
  • 5个问题后,出现的就是这个。它不打印分数Traceback (most recent call last): File "c:\Users\Intervenant\Desktop\Projets\Python\Formulaire d'evaluation en Console\main.py", line 43, in &lt;module&gt; print("Your score is : ", student.ask_question(setQuestions),"/", len(setQuestions)) TypeError: Student.ask_question() takes 1 positional argument but 2 were given

标签: python python-3.x list


【解决方案1】:

我已对您的代码进行了更改!方法ask_questionask_answer 应该是类方法(cls 作为第一个参数)或实例方法(self 作为第一个参数)。我选择它们作为实例方法!

以下代码有效! 警告:因为我不知道您的完整要求,所以我做了一些假设。这些变化基于假设。更改后,代码给出了我无法验证的输出!

文件:classEtudiant.py

import os

class Student:

    # constructor
    def __init__(self, name, surname):
        self.name = name
        self.surname = surname
        self.score = 0

    def reset_score(self):
        self.score = 0

    # ***********************************************************************************************************
    # we create a file called "candidate" in which the candidate enters his personal informations
    # don't forget to add an "r" before the path otherwise it doesn't work
    def candidate_file(self, name, surname):
        with open(r"candidate.txt", "a") as fileCandidate:
            fileCandidate.write("\n" + "Candidat's name : " + name)
            fileCandidate.write("\n" + "Candidat's surname : " + surname)

        # we then rename this "candidate" file with its name, all in a .txt file
        # os.rename(r"C:\Users\Intervenant\Desktop\Projets\Python\candidate.txt", name+".txt")

    # ***********************************************************************************************************


    # this function takes care of retrieving the answer of a candidate to a question
    def ask_answer(self, min, max):
        answer = input("Your choice : ")

        try:
            answer = int(answer)
            if min <= answer <= max:
                return answer
            print("Enter a number between ", min, "and", max)

        except:
            print("Error ! Please enter a number")

        return self.ask_answer(min, max)

    # ***********************************************************************************************************

    # this function takes care of asking questions to the candidate and counting the number of correct answers
    def ask_question(self, question):
        # question[1] represents the set of possible answers
        choice = question[1]
        # question[2] represents the correct answer
        rightAnswer = question[2]

        print("QUESTION"  )
        print("   ", question[0])

        """
        here len(choice) will calculate the size of the number of possible choices
        in the case of question 1, there are 4 possible choices
        so len(choice) = 3 (from 0 to 3)
        """
        for i in range(len(choice)):
            print(" ", i + 1, "-", choice[i])  # this is to display "2 - True" in question 1 for example


        answer = self.ask_answer(1, len(choice))
        print()

        if choice[answer - 1] == rightAnswer:
            print()
            self.score += 1

    # ***********************************************************************************************************

    def set_questions(self, setQuestions):
        for question in setQuestions:
            self.ask_question(question)



    # the set of questions of the exam
    setQuestions=(
        ("What is the output of the following code? print(5 >= 5) ",
            ("5 >= 5","True","False","None"),
            "True"
        ),
        ("Which of these data types is not a base type in Python?",
            ("Lists","Class","Dictionary","Tuples"),
            "Class"
        ),
        ("What is the output of the following code? min(max(False,-2,-5), 1,5) ",
            ("-5","-2","1","False"),
            "False"
        ),
        ("What is the output of the following code? >>>t = (1, 2, 3) >>>t.append( (4, 5, 6) ) >>>print len(t)",
            ("3","4","6","Error"),
            "Error"
        ),
        ("What is the function that compares the elements of two lists?",
            ("cmp(list1, list2)","eq(list1, list2)","len(list1, list2)","max(list1, list2)"),
            "cmp(list1, list2)"
        )
        )
    # set_questions(setQuestions)
    # print("votre score est : ", self.ask_question(setQuestions),"sur", len(setQuestions))

文件:main.py

# the main file

from classEtudiant import Student


name = input("Enter your name : ")
surname = input("Enter your surname : ")

print()
print("Welcome to the test Mr/Mrs", name, surname, " !")

# initialize a student
student = Student(name, surname)

# record the candidate's personal informations in a file
student.candidate_file(name, surname)

# launch the test

setQuestions=(
        ("Quelle est la sortie du code suivant? print(5 >= 5) ",
            ("5 >= 5","True","False","None"),
            "True"
        ),
        ("Lequel de ces types de données n’est pas un type de base en Python?",
            ("Lists","Class","Dictionary","Tuples"),
            "Class"
        ),
        ("Quelle est la sortie du code suivant? min(max(False,-2,-5), 1,5) ",
            ("-5","-2","1","False"),
            "False"
        ),
        ("Quelle est la sortie du code suivant? >>>t = (1, 2, 3) >>>t.append( (4, 5, 6) ) >>>print len(t)",
            ("3","4","6","ERREUR"),
            "ERREUR"
        ),
        ("Quelle est la fonction qui compare les éléments des deux listes?",
            ("cmp(list1, list2)","eq(list1, list2)","len(list1, list2)","max(list1, list2)"),
            "cmp(list1, list2)"
        )
        )

student.set_questions(setQuestions)

# print the score of the student
print("Your score is : ", student.score, "/", len(setQuestions))

这是输出

18/01/2022   20:23.58   /home/mobaxterm/temp  python main.py
Enter your name : Some
Enter your surname : Guy

Welcome to the test Mr/Mrs Some Guy  !
QUESTION
    Quelle est la sortie du code suivant? print(5 >= 5)
  1 - 5 >= 5
  2 - True
  3 - False
  4 - None
Your choice : 2


QUESTION
    Lequel de ces types de données n’est pas un type de base en Python?
  1 - Lists
  2 - Class
  3 - Dictionary
  4 - Tuples
Your choice : 2


QUESTION
    Quelle est la sortie du code suivant? min(max(False,-2,-5), 1,5)
  1 - -5
  2 - -2
  3 - 1
  4 - False
Your choice : 2

QUESTION
    Quelle est la sortie du code suivant? >>>t = (1, 2, 3) >>>t.append( (4, 5, 6) ) >>>print len(t)
  1 - 3
  2 - 4
  3 - 6
  4 - ERREUR
Your choice : 2

QUESTION
    Quelle est la fonction qui compare les éléments des deux listes?
  1 - cmp(list1, list2)
  2 - eq(list1, list2)
  3 - len(list1, list2)
  4 - max(list1, list2)
Your choice : 2

Your score is :  2 / 5

【讨论】:

  • 它有效。谢谢 !我有一些疑问为什么要在构造函数后面加这个def reset_score(self): self.score = 0
  • 不习惯!你可能已经尝试过了——删除方法不会破坏代码!
猜你喜欢
  • 1970-01-01
  • 2017-10-12
  • 2023-03-03
  • 1970-01-01
  • 2023-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
相关资源
最近更新 更多