How do I initialize an array in python?

0 votes
asked 4 days ago by (160 points)
from random import random, randint
correct = 0
n = 1
j = 0
k = 1
a = randint(0,10)
b = randint(0,10)
test = True
questions = []
print("Welcome to the multiplication math quiz")
print("In this quiz there will be 5 questions")
print("Good Luck!")
while test == True:
    for i in range(6):
        x = questions[i+i]
        y = questions[i+n]
        print(x, "*", y, "=")
        answer = input()
        if answer is (x*y):
            correct = correct + 1
        n += 1
        j += 2
        k += 2
    print("You got", correct, "/" , "5" , " correct and have a percentage of " , (correct/5)*100 , "%")
    correct = 0
    print("would you like to play again? yes/no")
    user = raw_input()
    if user is "yes":
        test = False

This is my code but when ever I try to fetch from my array it says it's out of scope.

1 Answer

0 votes
answered 3 days ago by (2,870 points)
You're trying to fetch from a position that does not exist in your list. "i+i" at minimum gives you 0 in first loop iteration, but 2 in the second, 4 in the third, 6 in the fourth and so on. Similarly with "i+n" but that goes even faster since you have 2 lines with n+=1 which effectively gives you n+=2 per iteration.  

Both could be swapped with "i" and "i+1" respectively or "0" and "1" if you want to ".clear()" your list. That's not the only problem though:

1. Unless you intend to put your numbers in, well, kind of random place in your array you should use ".append()" instead of ".insert()". Difference between those is in insert you decide after which element you add your new element, while append just adds it at the end of the list (array).

2. Your code doesn't check user answer correctly since "answer" variable has type of string (basically text) and the type of "(x*y)" is an integer (number). Because of this algorithm thinks they are always different no matter what.

3. I suppose you think "a" and "b" always a randomized number from 0 to 10 on each question, but no. They are picked once and then they stay the same. If they were in "for" loop they would be different on each loop iteration.

I don't remember whether that was all or not but anyways here's my version of your code with example fixes:
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.