Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How do I initialize an array in python?

+2 votes
asked Feb 14, 2020 by Matthew Lee (250 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.

2 Answers

–1 vote
answered Feb 15, 2020 by gameforcer (2,990 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:

+1 vote
answered Feb 18, 2020 by Nando Abreu (970 points)

I took the liberty to reorganize your script. Please check it here and/or test it in https://onlinegdb.com/S1RTZotQL

print("Welcome to the multiplication math quiz!")
print("In this quiz there will be 5 equations.")
print("Good Luck!\n")

from random import randint
import sys, os

used = ["None*None"]
gi, gcorrect = 0, 0
equations = 5 # number of equations to ask per game

def clear():
    os.system("cls" if os.name == "nt" else "clear")

while True:
    correct = 0
    for _ in range(equations):
        gi += 1
        tries = 0
        x, y = None, None
        while "{}*{}".format(x, y) in used:
            if tries > 99:
                print("I think I asked all the numbers. Thanks for playing!")

            x, y = randint(1,10), randint(0,10)
            tries += 1

        used.append("{}*{}".format(x, y))
        answer = input("How much is {} * {}? ".format(x, y))
            answer = int(answer)

        print("\rHow much is {} * {}? {}".format(x, y, answer), end="")

        if answer == x * y:
            print("\tGreat! {} is correct! :-)".format(answer))
            correct += 1
            gcorrect += 1
            print("\tSorry... The correct answer is {}.".format(x * y))

    print("\nYou got {}/5: {:0.1f}% correctness.".format(correct, correct*100/5))
    choice = input("Hit Enter to play again or send any letter to quit: ")

    if choice == "":
        if gi > equations:
            print("Your global score was {}/{}: {:0.1f}% correctness.".format(gcorrect, gi, gcorrect*100/gi))

#M# keyboard input, random integer number, system/os call, console and previous line clear, carriage return, list check/append, iteration, integer input check, error prevention, format number/percentage

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.