### Thread: Help me out with understanding codes

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2013
Posts
7
Rep Power
0

#### Help me out with understanding codes

Hi I just started learning python a week ago without any previous experience. There is this piece of code which I do not understand how it works so if you guys can help me out that'd be great.

The example shown in the tutorial is this:

Code:
```## This program runs a test of knowledge

# First get the test questions
# Later this will be modified to use file io.
def get_questions():
# notice how the data is stored as a list of lists
return [["What color is the daytime sky on a clear day? ", "blue"],
["What is the answer to life, the universe and everything? ", "42"],
["What is a three letter word for mouse trap? ", "cat"]]

# This will test a single question
# it takes a single question in
# it returns True if the user typed the correct answer, otherwise False

# extract the question and the answer from the list
# This function takes a list with two elements, a question and an answer.
# give the question to the user
print("Correct")
return True
else:
return False

# This will run through all the questions
def run_test(questions):
if len(questions) == 0:
print("No questions were given.")
# the return exits the function
return
index = 0
right = 0
while index < len(questions):
# Check the question
#Note that this is extracting a question and answer list from the list of lists.
if check_question(questions[index]):
right = right + 1
# go to the next question
index = index + 1
# notice the order of the computation, first multiply, then divide
print("You got", right * 100 / len(questions),\
"% right out of", len(questions))

# now let's get the questions from the get_questions function, and
# send the returned list of lists as an argument to the run_test function.

run_test(get_questions())```
which when run is supposed to look something like this:

What color is the daytime sky on a clear day? green
Incorrect, correct was: blue
What is the answer to life, the universe and everything? 42
Correct
What is a three letter word for mouse trap? cat
Correct
You got 66 % right out of 3

I don't understand this part:

Code:
```while index < len(questions):
# Check the question
#Note that this is extracting a question and answer list from the list of lists.
if check_question(questions[index]):
right = right + 1```

how does it calculate if the answer is right or wrong? Am I missing out something? Because I thought that in order for the number of rights to go up one, then the answer == question, so isn't there supposed to be a line of code making that condition? As opposed to simply saying "check_question(questions[index])". Where is that line is there a check for the correct answer? It's really confusing me. Please help.

P/S: I know the function check_question was defined up there as if the answer is correct then return True and if incorrect return False. But "check_question(questions[index])" isn't relying on the True or False to make right = right + 1... or does it?
Last edited by r3val4ti0n; September 9th, 2013 at 10:05 AM. Reason: Didn't know how to write the first time
2. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2013
Posts
7
Rep Power
0
Ok so I rewrote some of my code and got to this:

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

print("Correct")
return True
else:
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))

print("1. Take the test")
print("3. Quit")

run_test(get_questions())
for c in range(len(get_questions())):
print(get_questions[[c]])

print("Have a good day")```

While options 1 and 3 are working fine, with option 2 this message was return:

Traceback (most recent call last):
File "C:\Users\Jason\Desktop\Python\Variables with more than one value.py", line 44, in <module>
print("[', c, ']: ", get_questions[c])
TypeError: 'function' object is not subscriptable

Last edited by r3val4ti0n; September 9th, 2013 at 10:03 AM. Reason: Didn't know how to write the first time
3. Interesting, when I run your program it gives IndentationError .
4. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2013
Posts
7
Rep Power
0
Sorry. I fixed it. Tell me if it's working.
5. No Profile Picture
Contributing User
Devshed Novice (500 - 999 posts)

Join Date
May 2009
Posts
530
Rep Power
34
get_questions is a function, so you would use parens not brackets
print("[', c, ']: ", get_questions(c))
but that still isn't correct as get_questions doesn't receive any parameters. It would have to be something like
Code:
```        elif menu_choice == 2:
## iterate through the list returned by get_questions()
## the following is the same as
## return_list = get_questions()
## for c in return_list:
for c in get_questions():
## the following line calls get_questions again and returns another list
## so you would have to capture the list and use return_list[c] which
## duplicates the for() loop above
##print(get_questions[[c]])
print c```
6. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2013
Posts
7
Rep Power
0
Originally Posted by dwblas
get_questions is a function, so you would use parens not brackets
print("[', c, ']: ", get_questions(c))
but that still isn't correct as get_questions doesn't receive any parameters. It would have to be something like
Code:
```        elif menu_choice == 2:
## iterate through the list returned by get_questions()
## the following is the same as
## return_list = get_questions()
## for c in return_list:
for c in get_questions():
## the following line calls get_questions again and returns another list
## so you would have to capture the list and use return_list[c] which
## duplicates the for() loop above
##print(get_questions[[c]])
print c```
Can you possibly rephrase what you said in layman's term? I can understand part of it but I'm totally clueless about some of the things you say.

Also, can you explain the question I have above? About how the program calculate right and wrong answers?

Thank you by the way. The software is working properly now.
7. Python's container objects list, set, tuple, str, dict are iterable.

for i in range(len(LIST)): act_on(LIST[i])

write

for OBJECT in LIST: act_on(OBJECT)

This is a general solution. For instance,

for i in range(len(SET)): act_on(SET[i])
fails. Sets don't have a __getitem__ method. Sets do have an __iter__ method.

Looks like you're using
http://en.wikibooks.org/wiki/Non-Programmer's_Tutorial_for_Python_2.6/Lists
I wish I had something better to recommend---this program isn't very good. How about the regular python tutorial?
http://docs.python.org/3/tutorial/index.html

Let's look at one of the objects in the list of questions.
["What color is the daytime sky on a clear day? ", "blue"]
It's a list of two str objects. As you can see, the first is the question and the second str is the answer. Next look at check_question . The argument is question_and_answer. Name's don't matter, you need to investigate how variables are actually used. In this case the name is apt. The question and answer are separated by indexing.

I'd modify the program to look like this, which is probably why they don't let me write tutorials. No, seriously, the tutorial you've got was written by a c programmer who didn't bother taking any more time to learn python than it took him to write python in a way that looks familiar to him. It works, but it sux.
Code:
```# runs in python3

def get_questions():
return (    # use tuples instead of lists
("What color is the daytime sky on a clear day? ", "blue"),
("What is the answer to life, the universe and everything? ", "42"),
("What is a three letter word for mouse trap? ", "cat")
)

print("Correct")
return True
return False

def run_test(questions):
if not questions:
print("No questions were given.")
return
right = sum(check_question(*qa) for qa in questions)
n = len(questions)
print("You got", right * 100 / n, # Avoid backslash for line continuation.
"% right out of", n)

print("1. Take the test")
print("3. Quit")

questions = get_questions()
run_test(questions)
for qa in questions:
print(qa)

print("Have a good day")```
8. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2013
Posts
7
Rep Power
0
Originally Posted by b49P23TIvg
Python's container objects list, set, tuple, str, dict are iterable.

for i in range(len(LIST)): act_on(LIST[i])

write

for OBJECT in LIST: act_on(OBJECT)

This is a general solution. For instance,

for i in range(len(SET)): act_on(SET[i])
fails. Sets don't have a __getitem__ method. Sets do have an __iter__ method.

Looks like you're using
http://en.wikibooks.org/wiki/Non-Programmer's_Tutorial_for_Python_2.6/Lists
I wish I had something better to recommend---this program isn't very good. How about the regular python tutorial?
http://docs.python.org/3/tutorial/index.html

Let's look at one of the objects in the list of questions.
["What color is the daytime sky on a clear day? ", "blue"]
It's a list of two str objects. As you can see, the first is the question and the second str is the answer. Next look at check_question . The argument is question_and_answer. Name's don't matter, you need to investigate how variables are actually used. In this case the name is apt. The question and answer are separated by indexing.

I'd modify the program to look like this, which is probably why they don't let me write tutorials. No, seriously, the tutorial you've got was written by a c programmer who didn't bother taking any more time to learn python than it took him to write python in a way that looks familiar to him. It works, but it sux.
Code:
```# runs in python3

def get_questions():
return (    # use tuples instead of lists
("What color is the daytime sky on a clear day? ", "blue"),
("What is the answer to life, the universe and everything? ", "42"),
("What is a three letter word for mouse trap? ", "cat")
)

print("Correct")
return True
return False

def run_test(questions):
if not questions:
print("No questions were given.")
return
right = sum(check_question(*qa) for qa in questions)
n = len(questions)
print("You got", right * 100 / n, # Avoid backslash for line continuation.
"% right out of", n)

print("1. Take the test")
print("3. Quit")

questions = get_questions()
run_test(questions)
for qa in questions:
print(qa)

print("Have a good day")```

Code:
```if not questions:
print("No questions were given.")
return```
Sorry what does that line mean?

Also, I thought in order to answer the question, isn't there supposed to be an input function somewhere? I can't see it. Sorry new to this whole programming thing.
9. Use an editor with a search function. I recommend emacs. Reassign C-s to run the command isearch-forward-regexp. Then search the program for "input". This program has a statement with input. Other programs can read information without calling the input function. "argv", "open" and "read" are other useful search strings to find data sources.

Code:
```if not questions:
print("No questions were given.")
return```
is three lines, and 3 statements. Which part don't you like? Assuming the "not questions" expression troubles you, try experiments in the interpreter,

>>> type(())
>>> not ()
>>> not not ()
>>> not not not ()
>>> not ['a', 'list']
>>> not 0
>>> not 7.8
>>> #and finally,
>>> dir(42)

knowing that numbers have many methods should free your thinking about python.
Last edited by b49P23TIvg; September 11th, 2013 at 09:16 AM.
10. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2013
Posts
7
Rep Power
0
Originally Posted by b49P23TIvg
Use an editor with a search function. I recommend emacs. Reassign C-s to run the command isearch-forward-regexp. Then search the program for "input". This program has a statement with input. Other programs can read information without calling the input function. "argv", "open" and "read" are other useful search strings to find data sources.

Code:
```if not questions:
print("No questions were given.")
return```
is three lines, and 3 statements. Which part don't you like? Assuming the "not questions" expression troubles you, try experiments in the interpreter,

>>> type(())
>>> not ()
>>> not not ()
>>> not not not ()
>>> not ['a', 'list']
>>> not 0
>>> not 7.8
>>> #and finally,
>>> dir(42)

knowing that numbers have many methods should free your thinking about python.
thank you so much i'll starting looking at the tutorial you gave me. it should clear up some of the basics I might have missed.
11. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2013
Posts
7
Rep Power
0
does anyone have good python tutorials along with practice exercises so I can have a more solid improvement?