[Tutor] help understanding part of the tutorial...

Magnus Lycka magnus@thinkware.se
Thu Jan 9 07:11:18 2003


At 08:24 2003-01-09 +0000, Guess Who? Me wrote:
>I don't understand how this if loop returns a value using true and false

There is no such thing as an "if loop". The indented code block following an
if statement is executed once if the value of the expression between "if"
and ":" is true, and it will be skipped if the value of the expression was
false. The concepts of true and false has nothing to do with any names of
variables in the program. As far as Python is concerned, the fact that there
is a varaible called true with the value 1, and a variable false with the
value 0 is completely irrelevant. They could have been called stilton and
cheddar instead.

 From the Language Reference Manual, section 5.10:
"In the context of Boolean operations, and also when expressions are used by
control flow statements, the following values are interpreted as false:
None, numeric zero of all types, empty sequences (strings, tuples and
lists), and empty mappings (dictionaries). All other values are interpreted
as true."

1 and 0 are often used for true and false, but 5 and "" would also work.

In this case, the function called check_question will return 1 or 0. If it
returns 1 (true) the expression "right = right + 1" will be executed, if it
returns 0 (false) it will be skipped, and right will remain unchanged. In
other words, right is only incremented if you give the right reply to the
question.

>  - I know that true=1 and false=0, but I don't get how right=right+1 
> works out - does it mean that if the statement returns a false answer, 
> the rest of the if loop doesn't get carried out?

The next line won't get executed. The while loop continues.

># 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
>        if check_question(questions[index]): <<<<problem
>            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)



-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se