Вопросы о случайном умножении - PullRequest
1 голос
/ 25 марта 2020

Я пишу кусок кода для школы, чтобы задать случайный вопрос умножения, сосчитать количество вопросов и количество вопросов правильно. Когда я запускаю этот код, появляется сообщение об ошибке:

TypeError: question() принимает 0 позиционных аргументов, но 1 было дано

Что я могу сделать, чтобы почини это? , Вот мой код:

import random
noqc=0              #noqc = number of questions correct
noqtrack=1         #noqtrack = "number of questions tracker" 
def question():       
        x=random.randint(0,12)
        z=random.randint(0,12)
        y=("What is", x, "times", z, "?")
        a=int(input(y))
        if a==x*z:
                print("Correct")
                noqc=noqc+1
        else:
                print("Wrong, the answer was:",x*z,)          
noq=int(input("How many questions would you like to do?"))     #noq = number of questions
for i in range(0, noq):
        print(noqtrack)
        noqtrack=noqtrack+1  
        question(noqc)    #<------

Ответы [ 3 ]

2 голосов
/ 25 марта 2020

Ошибка возникает из-за того, что определение функции question() не принимает никаких аргументов (точные позиционные аргументы), но вместо этого вы вызываете question(noqc) с аргументом noqc.

One Чтобы исправить ваш код, можно вернуть значение из функции question. Это возвращает 1, если ответ верен, в противном случае возвращает 0.

Попробуйте:

import random
noqc=0              #noqc = number of questions correct
noqtrack=1         #noqtrack = "number of questions tracker" 

def question():
    x = random.randint(0, 12)
    z = random.randint(0, 12)
    y = ("What is", x, "times", z, "?")
    a = int(input(y))
    if a == x*z:
        print("Correct")
        return 1
    else:
        print("Wrong, the answer was:", x*z,)
        return 0


# noq = number of questions
noq = int(input("How many questions would you like to do?"))
for i in range(noq):
    print(noqtrack)
    noqtrack = noqtrack+1
    noqc += question()
0 голосов
/ 12 апреля 2020

Хорошо, вам действительно нужно использовать более описательные имена переменных ...

вместо noqc, попробуйте использовать numOfCorrectAwnsers или даже что-нибудь столь же простое, как correct, которое будет намного более читабельным и будет почти наверняка принесет вам больше очков в вашем классе.

Также я бы подошел к этому l oop по-другому:

noq = int(input("How many questions would you like to do?"))
for i in range(noq):
    print(noqtrack)
    noqtrack = noqtrack+1
    noqc += question()

Попробуйте изменить его на:

numOfCorrectQuestions = int(input("How many questions would you like to do?"))
while numOfCorrectAwnsers < numOfCorrectQuestions:
    question()
    numOfTotalQuestions += 1
0 голосов
/ 25 марта 2020

В дополнение к тому, что сказал Шубхам, я думаю, что вы не понимаете, как работают Python области. Здесь у вас есть несколько примеров кода, иллюстрирующих работу локальной и глобальной областей.

x = 0
def wont_modify_1(x):
  # this will make a copy of x in the local scope
  # then increment it by one
  x += 1
  # prints 1
  print ("x inside wont_modify_1 = {}".format(x))

wont_modify_1(x)
# prints 0, the variable outside the function wasn't modified
print ("x outside wont_modify_1 = {}".format(x))


y = 0
def won_t_modify_2():
  # variable y does not exist in this scope
  # it will be created here and assigned 1 to it
  y = 1
  # prints the value of the local variable, 1
  print ("y inside wont_modify_2 = {}".format(y))

won_t_modify_2()
# the global variable is a different object
# it wasn't modified, it prints 0
print ("y outside wont_modify_2 = {}".format(y))


z = 0
def won_t_modify_3():
  # z does not exists in this scope, so it can't be incremented by one
  # this will raise an error
  # UnboundLocalError: local variable 'z' referenced before assignment
  z += 1
  print ("z inside wont_modify_3 = {}".format(z))

won_t_modify_3()
print ("z outside wont_modify_3 = {}".format(z))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...