Chapter 7: Iteration – Think Python

Hi there!

So, we have made it to Chapter 7.

In case you have not noticed, I have not worked on the exercises from chapter 5 to chapter 7 yet. My goal is to speed up with the theory and then practice for a week. I will organize a session of “Code til you drop” with exercises from Chapter 5 to 8. I hope you can join. This will help us consolidate our knowledge before we tackle Chapter 9’s case study.

The title of chapter 7 is Iteration.

Here is a quick definition in order for us to start:

Iteration is the act of repeating a process with the aim of approaching a desired goal, target or result. Each repetition of the process is also called an “iteration”, and the results of one iteration are used as the starting point for the next iteration.

Source: Wikipedia/Iteration

7.1 Multiple assignment

Let us recall the notion of assignment from Chapter 3 – Functions (Part II):

>>> x = 3 # Read, variable x gets the value of 3.

>>> xx + 1 # Read, variable x gets the value of itself plus 1.

In addition, we were introduced to Boolean expressions on Chapter 5 / Section 5.1.

>>> 5 == 5 # Read, verify if 5 equals 5.

[…] With multiple assignment it is especially important to distinguish between an assignment operation [ “=” ] and a statement of equality [ “==” ].

Here is the definition that Professor Downey provides for multiple assignment.

Multiple assignment : Making more than one assignment to the same variable during the execution of a program [or code block]

7.2 Updating variables

Do you remember when we first saw this assignment statement “x = x + 1″ in Chapter 3? Today we learn that it is called an assignment update, since the new value of the variable x depends on the old value of x.

>>> xx + 1 # Read, “get the current value of x, add one (1), and then update x with the new value”.

In order to update a variable, you must initialize the variable first. Otherwise, Python will not recognize the variable.

Python evaluates the right side before it assigns a value to x.

>>> x = 0 # Read, variable x gets the value of zero (0). This assignments is also considered as the initialization of variable x.

>>> xx + 1  #”Updating a variable by adding one (1) is called an increment“.

>>> xx 1 1  #”Updating a variable by subtracting one (1) is called an decrement“.

7.3 The while statement

Iteration : Repeated execution of a set of statements using either a recursive function call or a loop.

Python statements that make recursion easier are:

  • for statement : ” for i in range ( n ): “
  • while statement : ” while Boolean expression : “
Recursion versus For Loop versus While Loop

Recursion versus For Loop versus While Loop

NOTE: I was looking for a way to improve the “countdown” function with a for loop, and I found inspiration in PythonicProse and Docs/Python.

Here is the flow of execution for the while loop:

  1. Evaluate the condition, yielding True or False.
  2. If the condition is false, exit the while statement and continue execution at the next statement.
  3. If the condition is true, execute the body and loop back to step 1.

The loop’s body should aim to prove the condition false, so that the loop terminates. The body may do so by changing the value of one or more variables.

The objective is to avoid infinite loops.

Infinite loop : A loop in which terminating condition is never satisfied.

>>> def sequence (n):
…     while n != 1:
…             print n,
…             if n%2 == 0:    # n is even
…                     n = n/2
…             else:           #n is odd
…                     n = n * 3 + 1

>>> sequence (16)
16, 8, 4, 2
>>> sequence (3)
3, 10, 5, 16, 8, 4, 2
>>>

7.4 Break

The break statement can be used to exit a loop. To illustrate this notion, Professor Downey provides this example:

>>> while True:
…     line = raw_input (‘> ‘)
…     if line == ‘done’:
…             break            # The condition (if line == ‘done’) allows us to stop the condition affirmatively (“stop when this happens”).
…     print line

> Hi there!
Hi there!
> done
>>>

The loop condition is True, which is always true, so the loop runs until it hits the break statement.

Each time through, it prompts the user with an angle bracket. If the user types done, the break statement exits the loop.

Exercise 7.1

Re-write the function print_n from Section 5.8 using iteration instead of recursion.

Exercise 7.1) Print_n using a while statement

Exercise 7.1) Print_n using a while statement

I tried a couple of times to re-write the print_n function using a while statement. This helped me get it right :

  • First, it is useful to remind ourselves that the while statement will execute as long as the conditional is True.
    • So, we can include in the while-block whatever we want to do or display while the function is True.
    • In the print_n function from exercise 7.1, we want to print the variable s as long that the conditional ” n > 0 ” is True.
  • Second, a great quality of the while statement is that whenever the conditional is False it ends. Isn’t this great?
7.5 Square roots
Not long ago, I began reviewing some mathematical concepts in order to better tutor mathematics.
So, as we progress in learning the theory and logic behind Python, it amazes me to realize the closeness of mathematics and programming.

For instance, if we were to write a program that computes numerical results, we could use loops in order to start with approximate answers and iteratively improving it.

The book (Think Python) demonstrates this by working with the Newton’s method for computing a square root.

y = ( x + a/x )/2
Netwon's Method

Netwon’s Method

Professor Downey points out that we must be cautious to test float equality since “floating-point values are only approximately right”.
For instance, irrational numbers such as ∏ (pi) and √2, cannot be represented exactly with a float.
Speaking of ∏ (pi), the book Moonwalking with Einstein: the Art and Science of Remembering Everything mentions that there are people that have memorized hundreds of digits from pi. This give us a sense of how the float 3.1416 is a rough approximation.

Rather than checking whether x and y are exactly equal, it is safer to use the built-in function abs to compute the absolute value, or magnitude, of the difference between them:

if abs (y – x) < epsilon:
    break
Where epsilon has a value like 0.0000001 that determines how close is close enough.

Exercise 7.2) Encapsulate this loop in a function called square_root that takes a as a parameter, chooses a reasonable value of x, and returns an estimate of the square root of a.

In interactive mode (using Python in the Terminal), I wrote:
>>> a = 4.0
>>> x = 3.0
>>> while True:
…     print x
…     y = (x + a/x)/2
…     if abs (y-x) < epsilon:
…             break
…     x = y
>>>
NOTE: I had the following error when I wrote the code block:
Traceback (most recent call last):
File “<stdin>”, line 4, in <module>
NameError: name ‘epsilon’ is not defined
>>>
So, I tried to write it in script mode (using Sublime Text and then executing it with the Terminal) and importing the math module.
Also, I looked for more information and I found an interesting/useful links:

Here is the code block in script mode (using Sublime Text):

from math import *
EPSILON = 0.0000001
a = 4.0
x = 3.0
while True:
print x
y = (x + a/x)/2
if abs (y-x) < EPSILON:
break
x = y
To verify the answer, I executed the file (sqroot_epsilon.py) via the Terminal. Here is the outcome!
MacBook-Air-xxxx:Desktop xxxx$ python sqroot_epsilon.py
3.0
2.16666666667
2.00641025641
2.00001024003
2.00000000003
MacBook-Air-xxxx:Desktop xxxx$
Later, I realized that the variable named epsilon had to be set before hand. So, the code block can perfectly work in script or interactive mode.
7.6 Algorithms
So, here we are on the verge of understanding the algorithm notion. I asked countless times what was an algorithm. The best answer I got was that it was like a recipe. Fair enough. However, I could not understand why a simple recipe was so fascinating in the programming world.
Again, Professor Downey has done a tremendous work explaining the coveted notion. He starts his explanation by explaining what an algorithm is not. He provides the memorization of the multiplication tables as an example.
However, he points out an interesting fact. As kids, we developed shortcuts or tricks.

For example, to find the product of n and 9, you can write n – 1 as the first digit and 10 – n as the second digit. This trick is a general solution for multiplying any single-digit number by 9. That’s an algorithm!

We can link this explanation with the recipe one. However, the later is crystal clear.
7.7 Debugging

The bigger the program is, the greater the possibility of making errors. Thus, we can say that a program’s length and the possibility of making an error are positively correlated.

Nevertheless, we can save time and many hair pulled by “debugging by bisection”. We can roughly cut the program in two and  test one part and then the other. We can use the incremental development technique we learned in Chapter 6 and use the print statements to verify line by line (or small code blocks) if we want.

***

Acknowledgments :

These notes represent my understanding from the book Think Python: How to Think Like a Computer Scientist written by Allen B. Downey.

Part of the chapter is transcribed and all the quotes unless specified otherwise come directly from his book.

Thank you Professor Downey for making this knowledge available.

 

Also, I would like to thank the open source community for their valuable contribution in making resources on programming available.

Thank you

Chapter 6: Fruitful functions – Think Python

Hi there,

In this chapter, Allen B. Downey, the author draws attention to the fact that all the functions we have written so far are void (their return value is None).

It was a disappointing revelation. I thought I was already coding elaborate functions; specially with all the hair pulled on exercise 4.3.

By the way, last year I took an “Intro to Python” class with Girl Develop It . It was a hands on class. The Pythonista in charge, Bethany cleverly demonstrated how to jump into coding. Nevertheless, one of the notions I stumbled upon was the “return” concept. The idea of a “phantom” return that was somehow kept on hold without manifesting itself was a bit confusing.

Fortunately, Allen B. Downey, the author dedicates a whole chapter to fully explain return values and its ramifications.

6.1 Return values

[… ]in a fruitful function the return statement includes an expression. This statement means: “Return immediately from this function and use the following expression as a return value”

def area(radius):
temp = math.pi * radius**2
return temp

This function returns the area of a circle with the given radius.

Temporary variable : A variable used to store an intermediate value in a complex calculations.

In addition, let us consider this function including an alternative conditional:

Absolute_Value definition (alternative conditional)

Absolute_Value definition (alternative conditional)

[It is important to note that] as soon as a return statement executes, the function terminates without executing any subsequent statements.

Code that appears after a return statement, or any other place the flow of execution can never reach, is called dead code.

None :  A special value returned by functions that have no return statement or a return statement without an argument.

In order to excel as programmers, we should be able to foresee all possible paths that the program might take so it can hit a return statement.

In the example above, our function would be stuck if we asked for the absolute value of 0 (zero).  We would get the return value None.

Exercise 6.1 Write a compare function that :

  • returns 1 if x > y,
  • returns 0 if x == y, and
  • returns -1 if x < y.
Exercise_6_1_compare

Exercise_6_1_compare

P.S. Have you ever wondered what is the difference between print statement and return statement in Python? For those who know the difference, this question might seem trivial. However, this is a perfectly pertinent question to ask.

When we use Python in interactive mode (Terminal running the Python interpreter), here are the scenarios:

Scenario no1 – Interactive mode

  • Code block #1: using the return statement

>>> def absolute_value(x):
…     if x < 0:
…             return -x
…     if x > 0:
…             return x

>>> absolute_value(3)
3
>>>

Scenario no2 – Interactive mode

  • Code block #2: using the print statement

>>> def absolute_value(x):
…     if x < 0:
…             print -x
…     if x > 0:
…             print x

>>> absolute_value(3)
3
>>>

Both code blocks give the exact same result. So, what is the difference?  We can clearly see the difference using the script mode.

When we write code in script mode (with Sublime Text for instance), here are the scenarios:

Scenario no1 – Script mode

  • Code block #1: using the return statement

def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x

absolute_value(3)

Since we wrote the code in Sublime Text (and saved it as a “abs_val.py” document for instance), we must verify the the outcome using the Terminal.

We travel in our terminal to find our “abs_val.py” document.

MacBook-Air-xxxx:Desktop xxxx$ python abs_val.py

The outcome will be … humm, nothing. Nothing appears on our screen.
If this is the first time it happens to you, you might say: “My code block did not work!”.

The good news is that it DID work. On the bright side, your program worked and the function evaluated abs_val(3). However, we did not ask our code block to print anything. Although the computation was correctly performed, nothing was demonstrated in the terminal.

Scenario no2 – Script mode

  • Code block #2: using the print statement

def absolute_value(x):
if x < 0:
print -x
if x > 0:
print x

absolute_value(3)

Again, we travel in our terminal to find our “abs_val.py” document.

MacBook-Air-xxxx:Desktop xxxx$ python abs_val.py

This time, we will see:

3

Which is the answer of abs_val(3).

To recapitulate, on the one hand, the return statement will execute the function and return the value without printing it (if you are in script mode). On the other hand, the print statement will print the return value you obtained from executing your function.

Does this help?

If you can explain it better, let me know as well.

6.2 Incremental development

As we write more elaborate programs, incremental development can be a way to tackle daunting programming challenges.

The goal of incremental development is to avoid long debugging sessions by adding and testing only a small amount of code at a time.

In order to demonstrate the reasoning behind incremental development, let us create a function capable of calculating the distance of two points.

Step 1 : If we follow George Polya’s method, the first step is to understand the problem or just the equation we are trying to translate into coding.

So, the Pythagorean theorem states that the hypotenuse (c) to the power of two (2) is equal to the sum of the square of side a and the square of side b.

c² = a² + b²

Pythagoream_Theorem

Pythagoream_Theorem

distance  = (  ( x2x1 )2 + (  y2 – y1 )2  )1/2

NOTE: If you want to know how far the Pythagorean theorem can take you, I recommend to read Why Does E=mc2?: And Why Should We Care? written by Dr. Brian Cox and Professor Jeff Forshaw.

At this step we can establish the input (the parameters) and the output (that it the return value).

  • Parameters: two points
    m = ( x1y1 )
    n = x2 , y2 )
  • Return value: the distance from point m to point n

Step 2 : Elaborate a plan (according to Polya’s problem solving strategy).

The plan is to use incremental development in order to build the code block that calculates the distance of two points (m and n).

Step 3 : The third step is to carry out the plan:

  • Incremental plan – step (i): Start with a working program and make small incremental changes.
    Verify that the function is syntactically correct.

>>> def distance (x1, y1, x2, y2):
…     return 0.0

>>> distance (1, 2, 4, 6)    #By using simple arguments, we can test the function easily.
0.0
>>>

  • Incremental plan – step (ii): Use temporary variables to hold intermediate values so you can display and check them.
    Find the differences.

>>> def distance (x1, y1, x2, y2):
…     dx = x2 – x1
…     dy = y2 – y1
…     print ‘dx is ‘, dx
…     print ‘dy is ‘, dy
…     return 0.0

>>> distance (1, 2, 4, 6)
dx is  3
dy is  4
0.0
>>>

[At this stage we know that] the function is getting the right arguments and performing the first computation correctly.

  • Incremental plan – step (iii): Use temporary variables to hold intermediate values so you can display and check them.
    Compute the sum of the squares dx and dy :

>>> def distance (x1, y1, x2, y2):
…     dx = x2 – x1
…     dy = y2 – y1
…     dsquared = dx**2 + dy**2
…     print ‘dsquared is ‘, dsquared
…     return 0.0

>>> distance (1, 2, 4, 6)
dsquared is  25
0.0
>>>

  • Incremental plan – step (iv): Compute the square root of dsquared in order to find the distance between point m and n.

>>> import math    #If you want to use the built-in function “sqrt” from Python, you must import the math module first.
>>> def distance (x1, y1, x2, y2):
…     dx = x2 – x1
…     dy = y2 – y1
…     dsquared = dx**2 + dy**2
…     result = math.sqrt(dsquared)
…     return result

>>> distance (1, 2, 4, 6)
5.0
>>>

NOTE: The “print” statements we wrote in step (ii) and (iii) are useful for debugging. If the function is working, we can condense the code block by removing them.

Scaffolding : Code that is used during program development but it not part of the final version.

NYC scaffolding

NYC scaffolding

Step 4 : Once the program is working, you might want to remove some of the scaffolding or consolidate multiple statements into compound expressions. The goal is to balance conciseness and easily comprehension of the code.

George Polya suggests to answer this question: How could it be better?

Exercise 6.2

This function is the exact same as the function “distance (x1, y1, x2, y2)”.

6.3 Composition

Composition : is the ability to call one function from within another.

Circle (xc, yc)

Circle (xc, yc)

Step 1) Find the radius of the circle (which is the distance between two points).

Recall:
>>> def distance (x1, y1, x2, y2):
…     dx = x2 – x1
…     dy = y2 – y1
…     dsquared = dx**2 + dy**2
…     result = math.sqrt(dsquared)
…     return result

>>>

radius = distance (xc, yc, xp, yp)

Step 2) Find the area of a circle with a radius.

Recall:
>>> def area (radius):
…     return math.pi * radius**2

>>>

result = area (radius)

In order to link the distance function and the area function, remember that the radius is our distance formula.

>>> def circle_area (xc, yc, xp, yp):
…     radius = distance (xc, yc, xp, yp)    #Consider the variable “radius” as a temporary variable
…     result = area (radius)    #Consider the variable “result” as a temporary variable
…     return result

>>> circle_area (1, 2, 4, 6)
78.53981633974483
>>>
“How could it be better?”

If we want to answer the question, we can make our code block more concise by composing the function calls as follows:

>>> def circle_area (xc, yc, xp, yp):
…     return area (distance(xc, yc, xp, yp))

>>> circle_area (1, 2, 4, 6)
78.53981633974483
>>>

6.4 Boolean functions

Functions can return booleans, which is often convenient for hiding complicated test inside functions.

Let us consider this example:

>>> def is_divisible(x, y):
…     if x % y == 0:
…             return True
…     else:
…             return False

>>> is_divisible (8, 2)
True
>>> is_divisible (5, 3)
False
>>>

NOTE: By definition, the result of a Boolean expression is either True or False. Therefore, we can re-write the the function more concisely.

>>> def is_divisible (x, y):
…     return x % y == 0

>>> is_divisible (8, 2)
True
>>> is_divisible (5, 3)
False
>>>

Boolean functions are often used in conditional statements.

Exercise 6.3 Write a function is_between (x, y, z) that returns True if x ≤ y ≤ z or False otherwise.

>>> def is_between (x, y, z):
…     return x <= y <= z

>>> is_between (1, 3, 9)
True
>>> is_between (3, 7, 4)
False
>>>

6.5 More recursion

Here is an exiting announcement from the author, Allen B. Downey:

We have only covered a small subset of Python, but you might be interested to know that this subset is a complete programming language, which means that anything that can be computed can be expressed in this language. Any program ever written could be rewritten using only the language features you have learned so far (actually, you would need a few commands to control devices like the keyboard, mouse, disks, etc., but that’s all).

The statement above was proven by Alan Turing. The author of the book (Think Python), Professor Downey recommends to read Michael Sipser’s book Introduction to the Theory of Computation to learn more about this computer science pioneer.

Who is Alan Turing?

Alan Mathison Turing (23 June 1912 – 7 June 1954) was a British mathematician, logician, cryptanalyst and computer scientist. He was influential in the development of computer science, giving a formalisation of the concepts of “algorithm” and “computation” with the Turing machine, which can be considered a model of a general purpose computer. Turing is widely considered to be the father of the theoretical computer science and artificial intelligence.
Source: http://en.wikipedia.org/wiki/Alan_Turing

Moreover, the concepts learned that we have learned so far can be gauged with a few recursively defined mathematical functions.

A recursive definition is similar to a circular definition, in the sense that the definition contains a reference to the thing being defined. A truly circular definition is not very useful.

At this point, we are ready to apply the concepts we have learned so far to recursively mathematical functions.

A recursive definition is similar to a circular definition, in the sense that the definition contains a reference to the thing being defined. A truly circular definition is not very useful.

Professor Downey mentioned the word vorpal. I looked for the definition in Wikipedia just to realized that I was even more puzzled after I read it. Let us just stick to the definition provided by Professor Downey.

vorpal : An adjective used to described something that is vorpal.

Factorial function

0! = 1n! = n (n – 1)!

For instance:

Factorial function

Factorial function

If you can write a recursive definition of something, you can usually write a Python program to evaluate it.

Let us recall Polya’s first step to problem solving (or if we extrapolate, the first step into writing a programing function):

  • Step 1) Understand the problem (or the function you wish to write).
    • Understand how a factorial function works.
    • Decide what the parameters should be: A factorial takes an integer.
    • Decide how the result should look like: If the argument happens to be 0, the our function must return 1.
  • Step 2) Make a plan
    • The factorial function looks very similar to the countdown function that we wrote in Chapter 5, section 8. We might just go back in order to find some inspiration for our plan.
Stack diagram 3!

Stack diagram 3!

  • Step 3) Carry out the plan

>>> def factorial (n):
…     if n == 0:
…             return 1
…     else:            # Otherwise, execute a recursive call to find the factorial of n – 1 and then multiply by n.
…             recurse = factorial (n-1)
…             result = n * recurse
…             return result

>>> factorial (3)
6
>>>

  • Step 4) Look back at your work. How can it be better?

6.6 Leap of faith

Trust in the code blocks you created and tested.

Here is another example of a leap of faith!

6.7 One more example

Another example of a recursively defined mathematical function is the fibonacci sequence of numbers :

In the Fibonacci sequence of numbers, each number is the sum of the previous two numbers. Fibonacci began the sequence […] with 1,1, 2, etc. […]
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377
Source: Wikipedia / Fibonnacci

  • fibonnaci (0) = 0
  • fibonnaci (1) = 1
  • fibonnaci (n) = fibonnaci (n – 1) + fibonnaci (n – 2)
fibonacci function

fibonacci function

If you try to follow the flow of execution here, even for fairly small values of n, your head explodes. But according to the leap of faith, if you assume that the two recursive calls work correctly, then it is clear that you get the right result by adding them together.

6.8 Checking types

The built-in function isinstance is introduced in this section. The function verifies the type of argument.

On section 6.5, we developed a function called factorial. Let us take another step further and check the type of the argument and make sure it is positive.

Factorial function improved

Factorial function improved

>>> factorial (‘banana’)
Factorial is only defined for integers.
>>> factorial (3.5)
Factorial is only defined for integers.

>>> factorial (-1)
Factorial is not defined for negative integers.

>>> factorial (8)
40320
>>>

This program demonstrates a pattern sometimes called a guardian. The first two conditionals act as guardians [(not isinstance) and  (elif n < 0)] , protecting the code that follows from values that might cause an error.

The guardians make it possible to prove the correctness of the code.

6.9 Debugging

Playing Lego with coding allows us to work on very small pieces of code. This makes debugging sessions less burdensome as it provides “natural checkpoints” for debugging.

If a function is not working, Professor Downey considers three possibilities:

  • Arguments: Verify that the function is getting the correct arguments.
    A precondition is violated.

    • “To rule out the first possibility [Arguments], you can add a print statement at the beginning of the function and display the values of the parameters (and maybe their types)”.
    • We can also write code to verify the preconditions explicitly: “Add a print statement before each return statement that displays the return value”.
  • Function: Verify that the function is syntactically correct. A postcondition is violated.
    • The Picking Number strategy to verify code blocks can be an option to check the function’s results.
    • “If the function seems to be working, look at the function call to make sure the return value is being used correctly (or used at all!)”
  • Return value: Verify that the return value is what you expect (type and form) or how the return value is being used.
    • Trace the flow of execution by adding print statements.
    • Temporary variables often render debugging easier easier.

 

***

Acknowledgments :

These notes represent my understanding from the book Think Python: How to Think Like a Computer Scientist written by Allen B. Downey.

Part of the chapter is transcribed and all the quotes unless specified otherwise come directly from his book.

Thank you Professor Downey for making this knowledge available.

 

Also, I would like to thank the open source community for their valuable contribution in making resources on programming available.

Thank you

Chapter 5 – Conditionals and recursion

Hi there,

The tip to read the chapter once (and taking notes on where I might find some obstacles) and then read it again a second time helped me tremendously.

The impression of “déjà vu” makes my second reading far more efficient. I am aiming to pick-up some speed with this reading tactic.

5.1 Modulus operator

A couple of months ago, I had to refresh my memory in order to explain the concept of remainder. However, I never thought that this concept would be helpful learning Python as well.

Wikipedia provides a full and comprehensive explanation of the modulo operation. I recommend to read it.

Basically, a remainder is the number that is left when you divide two numbers that are not multiples.

Modulo operation finds the remainder of a division

Modulo operation finds the remainder of a division

In Python, the modulus operator is the percent sign %.

If the remainder of x divided by y is zero, then we infer that x is divisible by y or x is a multiple of y.

Multiple and Factors

Multiple and Factors

The book provides a clear example:

>>> quotient = 7/3
>>> print quotient
2
>>> remainder = 7 % 3
>>> print remainder
1

5.1 Boolean expressions

A Boolean expression is an expression that is either true or false.

The operator == compares two operands and verify whether they are equal or not.

>>> 5 == 5
True

>>> 5 == 6
False

If we verify the type of True and False, we discover that they belong to the type bool.

>>> type (True)<type ‘bool’>

>>> type (False)
<type ‘bool’>

Relational operators :

  • x == y   # x is equal to y
  • x !=  y   # x is not equal to y
  • x > y   # x is greater than y
  • x < y   # x is less than y
  • x >= y   # x is greater or equal to y
  • x <= y   # x is less or equal to y

A common error is to use a single equal sign (=) instead of a double equal sign ( == ). Remember that (=) is an assignment operator and ( == ) is a relational operator.

x = y    # x gets the value of y

versus

x == y    # x is equal to y

Who is Boole? George Boole was an English mathematician, philosopher and logician of the 19th century. You may click on his name in order to find out more about him.

5.3 Logical operators

  • and
    x > 0 and x < 10 is true if both relations are true
  • or
    x > 0 or x < 10 is true if either relation is true
  • not
    The not operator negates a Boolean expression.
    not ( x < 10 ) is true if x is greater than 10 and it is false if x is less than 10.

5.4 Conditional execution

This is where the fun starts.

Conditional statements provide Python users with the ability to to check conditions and change the behaviour of the program accordingly.

Conditional execution

Conditional execution

 

There is no limit on the number of statements that can appear in the body, but there has to be at least one.

As we advance and write more elaborate functions and eventually programs, there is a useful statement called pass which does nothing. It is a place keeper for code to be written.

For instance:

if x < 0:    pass       # code to be written at a later time

5.5. Alternative execution

The alternative execution provides two (2) possibilities and the condition determines which one gets executed.

This is a second form of the if statement. The syntax looks like this:

if x % 2 == 0:    print ‘x is even’
else:
print ‘x is odd’

The condition can either be true or false. So only one alternative will be executed.

The alternatives are called branches, because they are branches in the flow of execution.

5.6 Chained conditionals

When we have more than two possibilities, then we need more than two branches. Chained conditionals enable us to express a computation with more than two alternatives.

if x < y :    print ‘x is less than y
elif x > y :
print ‘x is greater than y
else:
print ‘x and y are equal’

As soon as Python finds a True Boolean expression, then the branch will be executed.

elif

  • It is the abbreviation of “else if”.
  • There is no limit on the number of elif statements.

else

  • If there is an else statement, it has to be at the end.
  • The else statement is optional.

Python’s flow of execution:

Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes.

5.7 Nested conditionals

Conditionals can also be nested within another. This concept reminded me of the nested functions we saw on Chapter 3 and the Matryoshka image.

Python Nested Conditionals

Python Nested Conditionals

Love-Hate relationship with nested conditionals:

Love: Indentation provides nested conditionals with an apparent structure.

Hate: Beware, it is easy to get frustrated trying to find indentation bugs.

The author, Allen B. Downey points out that nested conditionals become difficult to read at a glance.

Logical operators often provide a way to simplify nested conditionals.

Nested conditionals versus logical operators

Nested conditionals versus logical operators

NOTE: In this chapter, the author used the word trichotomy. I looked up in Wikipedia and it means “splitting into three parts”.

5.8 Recursion

In the Python world, a function can call another function and a function can call itself as well.

A function that calls itself is recursive; the process is called recursion.

Recursive function with a return statement

Recursive function with a return statement

5.9 Stack diagrams for recursive functions

Stack diagrams are helpful to illustrate a function call or a recursive function.

Every time a function gets called, Python creates a new function frame, which contains the function’s local variables and parameters. For a recursive function, there might be more than one frame on the stack at the same time.

Think Python: Exercise 5.1

Think Python: Exercise 5.1

Exercise 5.2

Let us make a break and laugh a bit.

When I read this exercise I had the impression I was in the same situation as this:

School and Homework verus Exam questions

School and Homework verus Exam questions

Source: So Relatable

Here is the question:

Write a function called do_n that takes a function object and a number, n, as arguments, and that calls the given function n times.

What blocked me was the expression “function object“. So, I had to go back to Chapter 3 (p.22 and p. 29) to recall the definition.

A function object is a value you can assign to a variable or pass as an argument. For example, do_twice is a function that takes a function object as an argument and calls it twice:

def do_twice ( f ):
f ( )

f ( )

Here is an example that uses do_twice to call a function named print_spam twice.

def print_spam( ):    print ‘spam’

do_twice ( print_spam )

Inspiring me from this reference, here is what I found:

>>> def do_n (f, n):
…     if n <= 0:
…             return
…     else:
…             f()
…             do_n(f, n-1)

>>> def lyrics ():
…     print “I’m singing in the rain ”

>>> do_n (lyrics, 3)
I’m singing in the rain
I’m singing in the rain
I’m singing in the rain
>>>

5.10 Infinite recursion

If a recursion never reaches a base case, it goes on making recursive calls forever, and the program never terminates. This is known as infinite recursion, and it is generally not a good idea.

Once Python reaches 1000 recurse frames on the stack it will report an error.

5.11 Keyboard input

We will begin to write code blocks that require the user to interact.

In Python 2: raw_input function

In Python 3: input function

When this function is called, the program stops and waits for the user to type something. When the user presses “Enter“, the program resumes and raw_input returns what the user typed as a string.

When you ask the user for some input. It is best to state the question. For instance:

>>> sports = raw_input (‘Do you play any volley-ball or football?’\n’)
volleyball

>>> print sports
volleyball

The sequence \n at the end of the prompt represents a newline, which is a special character that causes a line break. That is why the user’s input appears below the prompt.

By default, the user’s answers are considered stings. However, we can change that like this:

>>> prompt = “What is the speed of sound in meters per second in dry air?\n”
>>> speed_sound = raw_input(prompt)
What is the speed of sound in meters per second in dry air?
343.2

>>> speed_sound
‘343.2’
>>> float(speed_sound)
343.2
>>>

5.12 Debugging

Python provides a hints for debugging such as:

  • What kind of error it was, and
  • Where it occurred.

Beware of these mistakes because they are a bit tricky to find:

  • whitespace errors: spaces and tabs are invisible to Python
  • runtime errors: watch for integer numbers versus floating numbers when dividing.

Python can indicate the line where the error occurred. However, verify the previous lines as well in order to correct the error more quickly.

So, this is it for the theory of chapter 5!

 

It does not matter how slowly you go, so long as you do not stop — Confucius, Chinese philosopher (551 BC – 479 BC)

 

***

Acknowledgments :

These notes represent my understanding from the book Think Python: How to Think Like a Computer Scientist written by Allen B. Downey.

Part of the chapter is transcribed and all the quotes unless specified otherwise come directly from his book.

Thank you Professor Downey for making this knowledge available.

 

Also, I would like to thank the open source community for their valuable contribution in making resources on programming available.

Thank you

Chapter 4 – Case Study: Interface Design

4.1 Turtle World

A package: is a collection of modules

In this chapter, the author, Allen B. Downey wrote a package called Swampy. You can download it via http://thinkpython.com/swampy.

One of the modules in Swampy is TurtleWorld, which provides a set of functions for drawing lines by steering turtles around the screen.

The Swampy package is actually a friendly way to start coding. It provides a visual reward for  the lines of code we write.

Instance is a member of a set.

For instance, the TurtleWorld in this chapter is a member of the set of TurtleWorlds.

4.2 Simple repetition

There are two ways of making Bob the Turtle dance:

1st way: With repetition

In Sublime Text: “mypolygon.py”

from swampy.TurtleWorld import *

world = TurtleWorld()
bob = Turtle()
print bob

fd(bob, 100)
lt(bob)

fd(bob, 100)
lt(bob)

fd(bob, 100)
lt(bob)

fd(bob, 100)

for i in range(4):
print ‘Hello!’

wait_for_user() #This function allows the program to wait for your “input” in order to proceed. If you omit to write this line of code, Python will run, execute and the close the code in a second. So, technically this function will allow you to admire your work for as long as you want.

2nd way: With a loop

from swampy.TurtleWorld import *

world = TurtleWorld()
bob = Turtle()
print bob

for i in range(4):
fd(bob,100)
lt(bob)

wait_for_user()

The syntax of a for statement is similar to a function definition. It has a header that ends with a colon and an intended body. The body can contain any number of statements.

A for statement is sometimes called a loop because the flow of execution runs through the body and the loops back to the top […] Loop: A part of a program that can execute repeatedly.

Instead of repeating commands over again, the for statement help us write code in a more concise way.

4.3 Exercises

I encourage you to solve the problems from the exercises by yourself. Although, sometimes it is frustrating; at the end it is very rewarding.

Gerren Liles, a health/fitness professional said in an interview “failure is success”. This concise sentence is very compelling because I came to realize that the only walls we stumble upon are the walls we create for ourselves.

I this chapter I realized that no matter what I stumble upon I must to keep on reading and going. I stopped for almost three (3) weeks because of problem 4.3 (parts 4 and 5). My goal was to find the answer by myself without peeking at the answers. I twisted the problem over and over and I still had an error message. Needless to say that the feeling of frustration/failure was not very far.

Here is the beauty of the experience: chapter 4 provides the answers by analyzing the problems one by one. So, if I continued reading I would have realize the answers and save precious time.

The lesson is to read the whole chapter once. Make notes on the parts that I might need some help and re-read it again. The process seems a bit cumbersome. Nevertheless, it seems optimal compared to stop reading, dreading a small problem.

So, to come back to the Gerren Liles’ sentence “failure is success”. My goal now is to transform hard problems into steps for success.

Here is my work for the exercises 4.3 (parts 1 to 5):

I must say that until today the logic of exercises 4.3 (part 5) is not very intuitive. So, here is what I found with the help of a CS:

In Sublime Text:

def polygon2 (t, n, length, m):

angle = 360 / n
# t = bob
# n = n-sided polygon
# length = length of each side
# m = number of sides to be drawn
# m = m/n
for i in range (m):
fd (t, length)
lt (t, angle)

def arc (t, r, angle):
n = 50
length = (2 * math.pi * r)/n
m = (angle * n)/360
polygon2 (t, n, length, m)

4.4 Encapsulation

Wrapping a piece of code up in a function is called encapsulation. One of the benefits of encapsulation is that it attaches a name to the code, which serves as a kind of documentation. Another advantage is that if you reuse the code, it is more concise to call a function twice than to copy and paste the body! […]

Encapsulation: The process of transforming a sequence of statements into a function definition

4.5 Generalization

In Chapter 3 (part II from my notes), the concepts of parameter and argument were first introduced. Here is some information in order to understand the purpose of parameters.

Adding a parameter to a function is called generalization because it makes the function more general.

When we call the function, we replace the parameters by the arguments. As we advance, we will use and create more functions. Keeping track of “how is how” can be done using keyword argument(s).

Keyword Argument: An argument that includes the name of the parameter as a “keyword.”

For instance, we can call our function polygon like this: polygon (bob, n=5, length=100)

4.6 Interface Design

The interface of a function is a summary of how it is used: what are the parameters? What does the function do? And what is the return value? […] A description of how to use a function, including the name and descriptions of the arguments and return value […]

An interface is like a contract between a function and a caller. The caller agrees to provide certain parameters and the function agrees to do certain work.

4.7 Refactoring

[The process of] rearranging a program to improve function interfaces and facilitate code reuse is called refactoring.

4.8 A Developmental Plan

Development plan: A process for writing programs.

In this Case Study, we started by giving simple commands (forward and left) to the Turtle. Then, we created the square function. Moreover, we developed the function polygon which is a generalization of our initial square function. When we developed the circle and the arc functions. As you can see, instead of starting with the complex problem (the arc function), we the author Allen B. Downey opted for a more heuristic approach.

The book “How to Solve it” (1945 ) from the mathematician Geoge Polya describes how the heuristic approach works. Basically, you break the big problem into small pieces to solve it.

4.9 Docstring

A docstring is a string at the beginning of a function that explains the interface (“doc” is short for “documentation”) […]

The triple-quoted string, also known as a multiline string, allows the string to span more than one line.

For instance, we can use a docstring in our square function:
from swampy.TurtleWorld import *

world = TurtleWorld()
bob = Turtle()
print bob

def square (t):
“””The function square draws a square with sides of the given length (100). Parameter t is the turtle.
“””

for i in range(4):
fd(bob,100)
lt(bob)

wait_for_user()

The purpose of the docstring is to provide the essential information on the effect of the function (what the function does) and to explain the effect each parameter has on the behaviour of the function.
4.10 Debugging
Precondition: A requirement that should be satisfied by the caller before a function starts.Postcondition: A requirement that should be satisfied by the function before it ends.

***

Acknowledgments :

These notes represent my understanding from the book Think Python: How to Think Like a Computer Scientist written by Allen B. Downey.

Part of the chapter is transcribed and all the quotes unless specified otherwise come directly from his book.

Thank you Professor Downey for making this knowledge available.

 

Also, I would like to thank the open source community for their valuable contribution in making resources on programming available.

Thank you

Python lesson plan: Chapter 4

Hi there!

Here is the weekly lesson plan for the third week.

Objective :

Read chapter four (4) “Case Study: Interface Design” of the book “Think Python”. My goal is to understand and link the new terminology.

Readings :

Think Python

How to Think Like a Computer Scientist

by Allen B. Downey

Chapter 4
Case Study: Interface Design

Incorporation :

The format of this chapter is a case study. So, it is time to play around with all the concepts we have seen so far.

Attending meetup meetings about Python and hang out with people who love to code has been very useful.

Assessment :

Exercises: 4.1 – 4.4

Exercises from chapter 3 – Think Python

Let us play with the concepts from chapter 3.

Exercise 3.3) p. 29

Python provides a built-in function called len that returns the length of a string, so the value of len(‘allen’) is 5.
Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.

>>> right_justify('allen')
                                                   allen
Here is the answer:
>>> def right_justify(s):
…     print (70 – len(s)) * ” ” + s

>>> right_justify(‘allen’)
allen
>>>
Logic:

I knew that:
70 = padding (blank characters) + s
Following the same logic, the padding would be equal to 70 – s.

****

Exercise 3.4) p. 29

A function object is a value you can assign to a variable or pass as an argument.

You can go back to the first part of Chapter 3 in order to recall the concept.

Exercise 3.4) p. 29

A function object is a value you can assign to a variable or pass as an argument. For example, do_twice is a function that takes a function object as an argument and calls it twice:

def do_twice(f):        # The function 'do_twice' uses the parameter 'f'.
    f()                 # If parameter 'f' happens to be a function, then it will be called twice. 
    f()

Here’s an example that uses do_twice to call a function named print_spam twice.

def print_spam():
    print 'spam'

do_twice(print_spam)
Remember about “nested functions” and the metaphor of the Matryoshka, here is the perfect example:
Questions:
  1. Type this example into a script and test it:
    >>>
    def do_twice(f):

    …     f()
    …     f()

    >>> def print_spam():
    …     print ‘spam’

    >>> do_twice(print_spam)
    spam
    spam
    >>>

  2. Modify do_twice so that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument.

    >>>def do_twice (f, bingo):        # The function ‘do_twice’ has two parameters. ‘f’ is a function object and ‘bingo’ is a parameter referring to a particular value.
    …    f (bingo)                                    # Here we will call function ‘f’ twice with the variable ‘bingo’ as an argument.
    …    f (bingo)

  3. Write a more general version of print_spam, called print_twice, that takes a string as a parameter and prints it twice.
    >>> def print_twice(banana):
    …     print banana
    …     print banana

    >>>
  4. Use the modified version of do_twice to call print_twice twice, passing ‘spam’ as an argument.
    >>> def do_twice (f, bingo):
    …     f(bingo)
    …     f(bingo)

    >>>
    >>> def print_twice (banana):
    …     print banana
    …     print banana

    >>>
    >>> do_twice (print_twice,’spam’)
    spam
    spam
    spam
    spam
    >>>
  5. Define a new function called do_four that takes a function object and a value and calls the function four times, passing the value as a parameter. There should be only two statements in the body of this function, not four.
    Working on what we already defined as a function, I will use:
    >>> def print_twice(banana):
    …     print banana
    …     print banana

    >>>
    >>> def do_four (g, cat):
    …     g(cat)
    …     g(cat)

    >>>
    >>> do_four(print_twice, ‘Eureka’)
    Eureka
    Eureka
    Eureka
    Eureka
    >>>
    NOTE: My answer does not match the solution provided by the link below. So, I still have to double-check it.

Solution: http://thinkpython.com/code/do_four.py

Exercise 3.5) p.29-30

This exercise can be done using only the statements and other features we have learned so far.

1. Write a function that draws a grid like the following:

Exercise 3-5 Think Python

Exercise 3-5 Think Python

Hint: to print more than one value on a line, you can print a comma-separated sequence:

print '+', '-'

If the sequence ends with a comma, Python leaves the line unfinished, so the value printed next appears on the same line.

print '+',
print '-'

The output of these statements is ‘+ -‘.
A print statement all by itself ends the current line and goes to the next line.

Write a function that draws a similar grid with four rows and four columns.

So, here are the early stages of me coding:

Step 1) Write the code in Sublime Text :

x = ‘+’
y = ‘ -‘
w = ‘ ‘
z = ‘|’

f = (x + 4*y + w) * 2 + x
g = (z + 9*w)*2 + z

def print_twice (banana):
print banana
print banana

def do_twice (f, apple):
f(apple)
f(apple)

def box ():
print f
do_twice(print_twice,g)
print f
do_twice(print_twice,g)
print f

box()

Step 2) Save the code under small_box.pyStep 3) Run the program in the Terminal :

Here is the grid:

 

2. Write a function that draws a similar grid with four rows and four columns.

Step 1) Write the code in Sublime Text :

x = ‘+’
y = ‘ -‘
w = ‘ ‘
z = ‘|’

f = (x + 4*y + w) * 4 + x
g = (z + 9*w)*4 + z

def print_twice (banana):
print banana
print banana

def do_twice (f, apple):
f(apple)
f(apple)

def box ():
print f
do_twice(print_twice,g)
print f
do_twice(print_twice,g)

def big_box():
box()
box()
print f

big_box()

Step 2) Save the code under big_box.py

Step 3) Run the program in the Terminal :

Here is the grid:

 

Solution: http: // thinkpython. com/ code/ grid. py.

Credit: This exercise is based on an exercise in Oualline, Practical C Programming, Third Edition, O’Reilly Media, 1997.

Problems and Solutions

Problems and Solutions

Chapter 3: Functions (Part III)

New terms from chapter 3 (Think Python: Think Like a Computer Scientist) – PART III

At this stage, we can define our own functions.

For instance, we defined the function ‘print_bruce’ which prints twice the parameter ‘bruce’.

>>> def print_twice(bruce):          # Here we define the function ‘print_twice’. The function has one (1) parameter: ‘bruce’.
…     print bruce                                 # The function will print the parameter ‘bruce’ two (2) times (or twice).
…     print bruce

>>>

Also, we can nest one function into another. I think of it like a computer programming Matryoshka.

For example:

>>> def sing_song (part1, part2): # Here we define the function ‘sing_song’. The function has two (2) parameters: ‘part1’ and ‘part2’
…     cat = part1 + part2                    # The variable ‘cat’ gets the value of the concatenation of parameter 1 and parameter 2.
…     print_twice (cat)                       # Here the function ‘print_twice’ is called and uses variable ‘cat’ as an argument.

>>>

Let us see what happens when we call the function ‘sing_song’ with the arguments: “Jingle” and “Bell”

>>> sing_song (“Jingle”, “Bell”)
JingleBell
JingleBell

Matryoshka dolls - Python nested functions

Matryoshka dolls – Python nested functions

Here is a more complete definition of what I am trying to convey :

In computer programming, a nested functions […] is a function which is lexically (textually) encapsulated within another function, with lexical scope […]

Due to nesting, the scope of the nested function is inside the enclosing function. This means that it can access local variables and other local functions in the enclosing function, while all of this is invisible outside the enclosing function.

Source: Wikipedia: Nested Function

3.10 Stack Diagrams

Stack diagrams are illustrations that can help us track who is who in nested functions and what sequence the program will follow in order to execute functions.

Stack diagrams show the value of each variable, but they also show the function each variable belongs to.

Each function is represented by a frame. A frame is a box with the name of a function beside it and the parameters and variables of the function inside it.

The frames are arranged in a stack that indicates which function called which, and so on.

Here is an example:

What happens if an error occurs during a function call ?

Python will help us trace the error back to its origin ( __main__ ).

– Traceback : Is a list that will help you find the error. It will provide:

  • the program file the error occurred in,
  • the line of code that caused the error, and
  • the functions that were executing at the time of the error.

3.11 Fruitful functions and void functions

– Fruitful functions: Allen B. Downey, Think Python’s author refers to fruitful functions, all the functions that will yield results (or return a value).

For instance, try this in the Python Shell (interactive mode):>>> import math     # First, you need to import that module math.
>>> math.sqrt(4)     # Then, let us remember the format to use in order to use a function from a module:  module . function (argument or variable)
2.0                               # This is the result that Python returns.
>>>

– Void functions: Void functions are functions, like ‘print_twice’ (that we defined earlier), that perform an action (either display something on the screen or perform some other action). However, they do not return a value.

For instance, we defined the function ‘print_twice’. The function is meant to perform the action of printing twice the parameter ‘bruce’.

In interactive mode:
Python will display the result of a void function if and only if we call a function in interactive mode.
In script mode:
When we call a fruitful function all by itself in script mode, the return value is lost forever if we do not store or display the result.
For instance:
>>> def print_twice(bruce):
…     print bruce
…     print bruce

>>> result = print_twice(‘Bing’)
Bing
Bing
>>> print result
None
>>>
It is important to note that although Python displayed the value of result earlier, the result displayed:
Bing
Bing
is lost forever since we did not store it anywhere.
In order to transmit this idea Python created the notion of ‘None’. It is a special value that has its own type.
>>> print type(None)
<type ‘NoneType’>
>>>

3.12 Why divide a program into functions?

  • By using functions, we are able to group statements. Thus, reading and debugging the program becomes easier. Just like playing with Lego blocks, a long program can be divided into functions (Lego blocks) that allow us to debug functions one at a time and the assembled them into a working whole.
  • By using functions, we can eliminate repetitive code. Therefore, functions are useful to make a program concise.
  • Well-designed functions can be useful for many programs.

3.13 Importing with from

We can use functions in modules in three different ways:

  • Import a module object in Python:

If you import math, you get a module object named math. The module object contains constants like pi and functions like sin and exp.

>>> import math
>>> print math
<module 'math' (built-in)>
>>> print math.pi          #Remember the format: module . function
3.14159265359
  • Import an object from a module in Python

>> from math import pi
Now you can access pi directly, without dot notation.

>>> print pi
3.14159265359
  • Import all objects from a module in Python
>>> from math import *

The advantage of importing everything from the math module is:
that your code can be more concise.

The disadvantage is:
that there might be conflicts between names defined in different modules, or between a name from a module and one of your variables.

3.14 Debugging

Python uses whitespaces indentation in order to delimit code blocks, a feature also termed the “off-side rule”.  An increase in indentation comes after certain statements; a decrease in indentation signifies the end of the current block.

Source: Wikipedia: Python Programming Language

Indentation bugs are difficult to find because they are invisible. The solution is to find a text editor that will manage indentation for you.

The text editor I use is “Sublime Text version 2”. So, I use tabs while writing code. However, with Sublime Text 2, I have to save my program before I run it.

Think Python’s author, Allen B. Downey provides a great advice to find errors in a particular code block. Here it is:

Debugging can take a long time if you keep running the same, incorrect, program over and over!

Make sure that the code you are looking at is the code you are running. If you’re not sure, put something like print ‘hello’ at the beginning of the program and run it again. If you don’t see hello, you’re not running the right program!

Think Python, p. 28

 

***

Acknowledgments :

These notes represent my understanding from the book Think Python: How to Think Like a Computer Scientist written by Allen B. Downey.

Part of the chapter is transcribed and all the quotes unless specified otherwise come directly from his book.

Thank you Professor Downey for making this knowledge available.

 

Also, I would like to thank the open source community for their valuable contribution in making resources on programming available.

Thank you

Chapter 3: Functions (Part II)

New terms from chapter 3 (Think Python: Think Like a Computer Scientist) – PART II

This second part is by far the more abstract and conceptual reading so far. So, let us keep moving forward.

3.7 Flow of execution

Flow of execution: the order in which statements are executed

Execution always begins at the first statement of the program. Statements are executed one at a time, in order from top to bottom.

Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is called.

A function call is like a detour in the flow of execution. Instead of going to the next statement, the flow jumps to the body of the function, executes all the statements there, and then comes back to pick up where it left off.

3.8 Parameters and arguments

Inside the function, the arguments are assigned to variables called parameters.

I must admit that the notions of parameters and arguments was very abstract.

I read it several times and I was not sure after each reading who was who. This was the perfect occasion to talk to a Computer Science (CS) professional!

If you do not know any CS professional, go to MeetUps. There are Python study groups that can be a valuable resource at this point.

  • PyLadies (is a great start)
  • Girl Develop It (They offer an Intro to Python course. Their approach is hands-on experience)
  • Python MeetUp Groups

Let us consider the following:

x = 3

My mathematical background made me read this as:

x equals to 3

So, when I saw this expression, I freaked out … literally!

x = x + 1

How can x be equal to x plus 1?!

***

After chatting with one CS professional, I understood that:

A variable is a “place holder”. Let us see how this changes our point of view:

x = 3

This statement means that variable x holds or gets the value of 3.

Knowing this, the expression: x = x + 1 is read as: variable x gets the value of x plus one (1).

Let us consider the example in Chapter Three (3):

In the Python shell, let us define a function named: ‘print_twice’

>>> def print_twice(bruce):
…     print bruce
…     print bruce

>>>

‘bruce’ is our parameter.

So, let us call the function ‘print_twice’ that we just  created in the Python shell with the argument “Laaa, lalalalala “:

>>> print_twice (“Laaa, lalalalala “)
Laaa, lalalalala
Laaa, lalalalala
>>>

I stumbled on the fact that the concepts of parameter and variable seemed identical to me. I understood why:

When we define our function, the most important is to establish what the function will do. You do not want to start thinking about what you can put in the function. At the creation stage, you just want your function to work in a particular way. In that case, you will use the concept of parameter.

Later, when you want to call the function and you know what you want to put in to make it work, you may use a variable or an argument.

Let us see how the function works with a variable named x :

Remember: Variable x gets the value of the following string “Hickory Dickory Dock”

>>> x = “Hickory Dickory Dock”
>>> print_twice (x)
Hickory Dickory Dock
Hickory Dickory Dock
>>>

So, we can make our function work with arguments and previously defined variables.

Recap: In a function (built-in or user-defined) the argument is evaluated before the function is called.

When we use built-in modules in our function definition, here is something to consider:

  • def module name . function name (parameters)

This first function definition provides the name of the module, the name of the function we want to use from the module and it states the parameter name.

Remember: A parameter is an information that I want to to consider but I still do not know the exact value.

  • def module name . function name (argument 1, argument 2, … argument n)

This second function definition provides the name of the module, the name of the function we want to use from the module and it states the value of the arguments. An argument is a precise piece of information.

3.9 Variables and parameters are local

When you create a variable inside a function, it is local, which means that it only exists inside the function

Using the user-defined function we created earlier ‘print_twice’, let us try this in the Python shell, in order to seize this concept.

1) Let us create a user-defined function called ‘cat_twice’
NOTE: My comments start with a # sign and are italicized.

>>> def cat_twice(part1, part2):
…     cat = part1 + part2                  #variable ‘cat’ gets the value of the concatenation of parameter no1 (called ‘part1’) and parameter no2 (called ‘part2’)
…     print_twice (cat)                      #we will call the function that we created earlier ‘print_twice’ with the variable ‘cat’

>>>

Moreover, let us the function we just created ‘cat_twice’ with a set of two (2) variables:

>>> line1 = “Hickory Dickory Dock”               #The variable ‘line1’ gets the value of “Hickory Dickory Dock”
>>> line2 = “The mouse ran up the clock.”    #The variable ‘line2’ gets the value of “The mouse ran up the clock”
>>> cat_twice (line1, line2)                            #We will call the function that we created ‘cat_twice’ with the variables ‘line1’ and ‘line2’
Hickory Dickory DockThe mouse ran up the clock.
Hickory Dickory DockThe mouse ran up the clock.
>>>                                                                  #The result is the concatenation of variables ‘line1’ and ‘line2’ and printed twice

Let us double-check what happens with the variable ‘cat’ that we initially defined in the function ‘cat_twice’

>>> print cat
Traceback (most recent call last):
  File “<stdin>”, line 1, in <module>
NameError: name ‘cat’ is not defined
>>>

When cat_twice terminates, the variable cat is destroyed. If we try to print it, we get an exception:

NameError: name ‘cat’ is not defined

Furthermore, it is important to notice that the parameter ‘bruce’ is useless outside the function we defined called ‘print_twice’.

This concludes the second part of Chapter Three (3).

Rubik's Cube

Rubik’s Cube

 

 

***

Acknowledgments :

These notes represent my understanding from the book Think Python: How to Think Like a Computer Scientist written by Allen B. Downey.

Part of the chapter is transcribed and all the quotes unless specified otherwise come directly from his book.

Thank you Professor Downey for making this knowledge available.

 

Also, I would like to thank the open source community for their valuable contribution in making resources on programming available.

Thank you

Chapter 3: Functions (Part I)

New terms from chapter 3 (Think Python: Think Like a Computer Scientist) – PART I

I found this chapter very dense. So, I will break it down in three (3) parts.

3.1 Function calls

  • Function : name + sequence of statements that perform a computation

The book “Think Python: Think Like a Computer Scientist” provides the following definition:

a function is a named sequence of statements that performs a computation

  • Function call:

Once the function’s name and sequence of statements have been specified, I can “call” the function by name.

Here is an example:

>>>type (32)
<type ‘int’>

The name of the function is type.

The expression in parenthesis is called an argument.

The result of this function is the type of the argument.

It is common to say that a function “takes” an argument and “returns” a result. The result is called the return value

Here is an illustration of a function that I found on Wikipedia:

Wikipedia Function machine

Wikipedia Function machine: A function f takes an input x, and returns an output f(x)

Source:http://en.wikipedia.org/wiki/Function_%28mathematics%29

3.2 Type conversion functions

Python provides built-in functions that convert values from one type to another

For instance:

The int function takes any number value and converts it to an integer. If the number is a floating-point value, the function will truncate the fraction part (NOTE: The function does not round off)

For instance:

>>> int(5.25)
5

>>>int(-2.3)-2

The float function converts integers numbers and strings numbers to floating-point numbers.

For example:

>>> float(32)
32.0
>>> float(‘3.14159’)
3.14159

The str function converts its argument to a string.

Here is an illustration:

>>> str(32)
’32’
>>> str(3.14159)
‘3.14159’

3.3 Math functions

Python has a math module that provides most of the familiar mathematical functions

  • A module: A file that contains a collection of related functions. Also, before I can use the module I have to import it.

For instance:

>>> import math
>>>

>>> print math
<module ‘math’=”” from=”” ‘=”” library=”” frameworks=”” python.framework=”” versions=”” 2.7=”” lib=”” python2.7=”” <span=”” class=”hiddenSpellError” pre=””>lib-dynload/math.so’>

Statement: >>> import math

Module object: math

The module object contains the functions and variables defined in the module

  • Dot notation the name of the module and the name of the function, separated by a dot. Do notation is used to access one of the functions in the module.

Example no1:

>>> signal_power = 10
>>> noise_power = 2.5
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> print decibels
6.02059991328

NOTE 1: This example uses the function of log10 to compute a signal-to-noise ratio in decibels.

NOTE 2: The math module provides the function log, which computes logarithms base e.

Example no2: Convert degrees to radians

>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi # To convert from degrees to radians: divide the degrees by 360 and multiply it by 2∏
>>> math.sin(radians) # Find the sin of radians
0.7071067811865475

NOTE: The name of the variable is a hint that sin and the other trigonometric functions (cos, tan, etc.) take arguments in radians.

The expression math.pi gets the variable pi from the math module. The value of the variable pi is an approximation of ∏, accurate to about 15 digits

3.4 Composition

Program components:

  • variables
  • expressions
  • statements

To compose: The ability to take small building blocks and build up with them.

the argument of a function can be any kind of expression, including arithmetic operators […] Almost anywhere you can put a value, you can put an arbitrary expression, with one exception:

the left side of an assignment statement has to be a variable name. Any other expression on the left side is a syntax error (we will see exceptions to this rule later)

Here is an illustration:

>>> degrees = 45
>>> x = math.sin(degrees / 360.0 * 2 * math.pi)
>>> print x
0.707106781187
>>> y = math.exp(math.log(x+1))
>>> print y
1.70710678119

COMPOSITION RULE: The left side of an assignment statement has to be a variable name. Any other expression on the left side is a syntax error (I will see exceptions to this rule later)

Writing an ASSIGNMENT STATEMENT this way will work:

>>> minutes = hours * 60 #The writing of this assignment statement is adequate since the left side of the assignment statement is the  variable name

>>>

Writing an ASSIGNMENT STATEMENT the way described below will generate and error:

>>> hours * 60 = minutes
File “<stdin>”, line 1
SyntaxError: can’t assign to operator
>>>

3.5 Adding new functions

– Function definition: def

A function definition specifies the name of a new function and the sequence of statements that execute when the function is called

– Function names rule of thumb:

  • letters, numbers and some punctuation marks are legal,
  • the first character of the function name can’t be a number
  • keyword as the name of a function is illegal
  • avoid having a variable and a function with the same name

The empty parentheses after the [function definition] name indicate that this function doesn’t take any arguments

– Interactive mode: If you type a function definition in interactive mode, the interpreter prints ellipses (…) to let you know that the definition isn’t complete.
For instance:

>>> def print_lyrics():

Header: It is the first line of the function definition and it has to end with a colon

– Body: All the subsequent lines after the first line of the function definition and they have to be indented. There is no limit as to the number of statements a function definition may have.
NOTE: By convention, the indentation is always four spaces (see Section 3.14)

– Strings: The strings in the print statements are enclosed in double quotes.
NOTE: Single quotes and double quotes do the same thing; most people use single quotes except in cases like this where a single quote (which is also an apostrophe) appears in the string.

– End: To end a function, I have to enter an empty line (just hit enter). This is not necessary in a script mode

Here is an example:

>>> def print_lyrics():
…     print “I’m a lumberjack, and I’m okay.”
…     print “I sleep all night and work all day.”

>>>

I can recognize the keyword that indicates that it is a function definition: def

  • I can also recognize the name of the function: print_lyrics
  • The header of the definition function is: >>> def print_lyrics():    Please note that it ends with a colon.
  • The body of the definition function is everything that follows and it is indented
  • The strings in the print statements of the function definition are enclosed in double quotes and are indented after the ellipsis (the three dots) :

…     print “I’m a lumberjack, and I’m okay.”
…     print “I sleep all night and work all day.”

  • The end of the function: After the third (3rd) ellipsis, I hit enter again and it comes back to >>>

– Defining a function: After I defined my function definition (name, header, body, strings, end), I can ask python to print it (or recall it). Python will create a variable with the same name. See below:

>>> print print_lyrics
<function print_lyrics at 0x10049acf8>
>>>

– Value type of the function definition we just created can be found as illustrated below:

>>> type (print_lyrics)
<type ‘function’>

In other words, the value of print_lyrics is a function object, which has type ‘function’.

The syntax for calling the new function is the same as for built-in functions […] Once you have defined a function, you can use it inside another function

Here is a fun example of how pop music (Lady Gaga / Poker face) and Python can mix.

  • Step 1: Define the function print_chorus_pf

>>> def print_chorus_pf():
…     print “P-p-p-poker face, p-p-poker face”
…     print “(Mum mum mum mah)”

  • Step 2: Define the function repeat_chorus_pf

>>> def repeat_chorus_pf():
…     print_chorus_pf()
…     print_chorus_pf()

  • Step 3: Call function repeat_chorus_pf

>>> repeat_chorus_pf()
P-p-p-poker face, p-p-poker face
(Mum mum mum mah)
P-p-p-poker face, p-p-poker face
(Mum mum mum mah)
>>>

3.6 Definitions and uses

This program contains two function definitions: print_chorus_pf and repeat_chorus_pf.

Function definitions get executed just like other statements, but the effect is to create function objects.

The statements inside the function do not get executed until the function is called, and the function definition generates no output […]

As you might expect, you have to create a function before you can execute it.

Exercise 3.1) Move the last line of this program to the top, so the function call appears before the definitions. Run the program and see what error message you get.

>>> repeat_chorus_pf()
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
NameError: name ‘repeat_chorus_pf’ is not defined
>>>

Exercise 3.2. Move the function call back to the bottom and move the definition of print_chorus_pf after the definition of repeat_chorus_pf. What happens when you run this program?

>>> def repeat_chorus_pf():
…     print_chorus_pf()
…     print_chorus_pf()

>>> def print_chorus_pf():
…     print “P-p-p-poker face, p-p-poker face”
…     print “(Mum mum mum mah)”

>>> repeat_chorus_pf
<function repeat_chorus_pf at 0x10049acf8>
>>>

 

***

Acknowledgments :

These notes represent my understanding from the book Think Python: How to Think Like a Computer Scientist written by Allen B. Downey.

Part of the chapter is transcribed and all the quotes unless specified otherwise come directly from his book.

Thank you Professor Downey for making this knowledge available.

 

Also, I would like to thank the open source community for their valuable contribution in making resources on programming available.

Thank you

Python lesson plan: Chapter 3

Hi there!

Here is the weekly lesson plan for the third week.

Objective :

I want to read the third chapter “Functions” of the book “Think Python”. My goal is to understand and link the new terminology into my daily life.

Readings :

Think Python

How to Think Like a Computer Scientist

by Allen B. Downey

Chapter 3: Functions

Incorporation :

At first, I could not see any remote link between the new terminology and my daily activities or conversations. However, with some practice, it is actually fun to see where the new terminology fits in.

Attending meetup meetings about Python and hang out with people who love to code helps.

Assessment :

Exercises: 3.1 – 3.5

Python Stamp Australia

Python Stamp Australia