Help with understanding an example code (I'm a new learner)

The source code is

def get_questions():
return[[“What color is the daytime sky on a clear day?”, “blue”],
[“What is the answer to life, the universe and everuthing?”, “42”],
[“What is a three letter word for a mouse trap?”, “cat”,]]

def check_question(question_and_answer):

question = question_and_answer[0]
answer = question_and_answer[1]
                                        
given_answer = input(question)
                                        
if answer == given_answer:
    print("Correct")
    return True
else:
    print("Incorrect, correct was:", answer)
    return False

def run_test(questions):
if len(questions) == 0:
print(“no questions were given.”)

    return
index = 0
right = 0
while index < len(questions):
                                        
    if check_question(questions[index]):
        right = right + 1
                                        
    index = index + 1
print("you got", right * 100 / len(questions),\
      "%right out of", len(questions))

run_test(get_questions())

I am very stuck at ‘if check_question(questions[index]):’
The book I am learning from doesn’t go over this part at all. Does ‘[index]’ here refer to the local variable index? Or is this the function of indexing? If so I thought that was written only like list.index().
Please correct anything I said wrong, I’ll take all the help I can get! Thank you!

The source code is

def get_questions():
return[[“What color is the daytime sky on a clear day?”, “blue”],
[“What is the answer to life, the universe and everuthing?”, “42”],
[“What is a three letter word for a mouse trap?”, “cat”,]]

A list of [question,answer] pairs.

def check_question(question_and_answer):
[… ask the question, copy response to the expected answer …]]
def run_test(questions):
index = 0
right = 0
while index < len(questions):
if check_question(questions[index]):
right = right + 1
index = index + 1
[…]

I am very stuck at ‘if check_question(questions[index]):’
The book I am learning from doesn’t go over this part at all. Does ‘[index]’ here refer to the local variable index?

Yes. So that means questions[0] on the first loop iteration,
questions[1] on the second and so forth.

Or is this the function of indexing?

No. There isn’t “a function of indexing” as such. Lists have an index
method which has a particular operation.

If so I thought that was written only like list.index().

That is correct.

The word “index” is not special. Used alone, it must mean a variable
that is available. So it means your local “index” variable, because you
have a local index variable.

The expression “list.index” means to look in the attributes of “list”
for an attribute named “index”.

“list” names the built in class “list”, which is the type of Python
lists (types and classes are the same thing in Python). That class has
an “index()” method, and “list.index” therefore accesses that method.
Which does whatever the method does - in this case searching the list
for a value and reporting its psition.

So “list.index” returns the method for the “list” class. “str.index”
returns a method from the str (string) class, which could do anything
else. Because strings are sequences and lists are sequences they in fact
do very similar things. But that is a design choice, not anything tied
to the name “index”.

But it gets better: the word “list” is not special either. When you say
“list.index” Python must first look up the name “list”. It isn’t a local
variable, so it then looks in the outer scopes and finds the name “list”
in the builtin names. But they’re just names!

Please correct anything I said wrong, I’ll take all the help I can get!
Thank you!

Your reading is correct.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like

Hi Caius,

You ask:

I am very stuck at ‘if check_question(questions[index]):’
The book I am learning from doesn’t go over this part at all.

Which book are you learning from? My guess is that it is “Learn Python
The Hard Way”. Am I right?

Does ‘[index]’ here refer to the local variable index?

The word index refers to the local variable index. The syntax:

questions[index]

is called “subscripting” or sometimes “indexing”. It means to take the
list (or string, or tuple, or other sequence of items) and return the
item at position index. For example:

sequence = ['a', 'b', 'c', 'd']
sequence[0]  # --> returns 'a'
sequence[1]  # --> returns 'b'
sequence[2]  # --> returns 'c'
sequence[3]  # --> returns 'd'

So the index (or position, or subscript) inside the square brackets
starts counting at 0 instead of 1 like you may be used to. If that feels
a bit weird, well, yes, kinda, but there are good reasons for it, and
you will soon get used to it.

Or is this the function of indexing? If so I thought that was written
only like list.index().

The list index() method goes the other way: it returns the index (or
position) of the given item.

sequence = ['a', 'b', 'c', 'd']
sequence.index('a')  # --> returns 0
sequence.index('b')  # --> returns 1
sequence.index('c')  # --> returns 2
sequence.index('d')  # --> returns 3

So if you know the position (index) that you want, use the subscripting
notation to return the item in that position:

sequence[0]  # return the zeroeth item of the sequence
sequence[45]  # return the 45th item of the sequence

If you know the item, and want to find out which position it is sitting
in, use the .index() method call:

sequence.index('hello')  # return the position of 'hello'
1 Like

Ah I see this makes a lot more sense now. So when you input the value of the local variable ‘index’ into questions[index] it returns whatever is at that position starting with 0 and, in this particular code, it ends with 2. And also I’m currently using the book called “Non-programmer’s tutorial to python 3.”