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

Chapter 2: Variables, expressions and statements

New terms from chapter 2 (Think Python: Think Like a Computer Scientist)

  • Value: Is what a program needs to work. So far, I know two type of values: numbers and letters.
  • Value types:
    – The type of value of the number 2 is an integer (‘int’)– The type of value of the letters ‘Hello World!’ is a a string (‘str’). We can view it as a string/chain of letters
    – Numbers with a decimal point belong to a value type called float (‘float’) because these numbers are represented in a format called floating-point.

NOTE: If I want to know what type of value it is, we can ask the interpreter. For instance:

Example no1:

I ASK: >>> type (‘Hello, World!’)

The interpreter answers: <type ‘str’>

Example no2:

I ASK: >>> type (17)

The interpreter answers: <type ‘int’>

Example no3:

I ASK: >>> type (2.5)

The interpreter answers: <type ‘float’>

  •  Variables: It is a name that refers to a value
    I also read in Chapter 2:

One of the most powerful features of a programming language is the ability to manipulate variables […] An assignment statement creates new variables and gives them values […]

For the notion of variable, algebra comes to mind!

x = Variable x corresponds to the the value that will solve a given equation. For instance:

Equation: 3 + x = 8

Find variable x

Variable x = 5  ( x = 8 – 3)

Also, it is useful to note that the type of a variable is the type of the value it refers too.

More variable names can contain both letters and numbers. However, they must begin with a letter.
Lowercase and uppercase are legal. However, it is highly recommended to begin variable names with a lowercase letter. Apparently, we will understand all this later on.
Finally, the underscore character can be used in variable names.N.B. If we give a variable an illegal name, we will get a syntax error.

  • Assignment statement: The book “Think Python” defines this term as “An assignment statement creates new variables and gives them values”. However, I had to dig more to link this concept into my mind.
    I found a definition that works better for me:

Assignment statements carry out assignment operations, which consist of taking the value on the right side of the assignment operator (=) and storing it in the element on the left, as in the following example: v = 42

Source: Microsoft Developer Network: http://msdn.microsoft.com/en-us/library/z2wkh0tk%28v=vs.90%29.aspx
Therefore, I understand it as follows:
An assignment statement is the relationship of the two parties on each side of the assignment operator (=)
N.B.2 If I err, you are welcomed to share your logic.
  • A state diagram is a graphic/more visual way to write an assignment statement.

For instance, consider this assignment statement:

Variable           =              Value

The statement diagram will look as follow:

my_project_name   ——>    ‘Python Project’

  • Keywords: are word that are used by the interpreter. Therefore, we cannot used them in our variable names.
  • Operators: What do you use your calculator for? For computations such as:
    Add: +
    Substract: –
    Multiply: *
    Divide: /
    Exponentiation (“to the power of”):  ** (For instance 3 to the power of 1 is written: 2**3)
  • Floor division: Try to divide: 3/60 or 6/8 or any two numbers which you know the answer will include decimals,

The reason for the discrepancy is that Python is performing floor division. When both of the operands are integers, the result is also an integer; floor division chops off the fraction part, so in this example it rounds down to zero.
In Python 3, the result of this division is a float. The new operator // performs floor division.
If either of the operands is a floating-point number, Python performs floating-point division, and the result is a float

  • An expression is a combination of values, variables, and operators.
  • A statement:

A statement is a unit of code that the Python interpreter can execute. We have seen two kinds of statement: print and assignment.
[…]The important difference [between an expression and a statement]is that an expression has a value; a statement does not

The main difference is that: an expression has a value; a statement does not.

For instance:

>>> miles = 26.2     (This is an assignment since it assigns a value to the word “miles” without any other consequence.)

>>> miles * 1.61      (This is an expression. It has a consequence since the interpreter evaluates it and displays the result 42.182)
42.182

2.6) INTERACTIVE MODE versus SCRIPT MODE

NOTE: Advantage of working with an interpreted language: you can test bits of code in interactive mode before you put them in a script

Interactive mode: You will have values and expressions. In turn, the interpreter evaluates it and displays the result.

In script mode: You can have an expression as well. Nonetheless, the expression will not have and effect (or consequence or output) if you do not ask Python to evaluate it and display a result. A script usually contains a sequence of statements.

2.7) ORDER OF OPERATIONS
If a script has more than one statement, Python will display the results one at a time as the statements execute.

Exercise 2.2. Type the following statements in the Python interpreter to see what they do:

5
x=5
x+1

Here is the script:

>>> print 5
>>> x = 5
>>> print x+1

Here is the output of the script:

5
6
Now put the same statements into a script and run it. What is the output?

>>> 5
5
>>> x = 5
>>> x + 1
6

Modify the script by transforming each expression into a print statement and then run it again.

>>> print 5
5
>>> x = 5
>>> print x+1
6

To recap, a script usually contains a sequence of statements.

When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. For mathematical operators, Python follows mathematical convention.

  1. Parentheses
  2. Exponentiation
  3. Multiplication and Division
  4. Addition and Subtraction

Operators with the same precedence are evaluated from left to right (except exponentiation)

2.8) STRING OPERATIONS
RECALL: The type of value of the number 2 is an integer (‘int’)– The type of value of the letters ‘Hello World!’ is a a string (‘stg’). We can view it as a string/chain of letters
  • The + operator it performs string concatenation, which means joining the strings by linking them end-to-end.
For instance:
>>> first = ‘grand’
>>> second = ‘pa’
>>> print first + second
grandpa
  • The * operator also works on strings; it performs string repetition.

For example:

>>> ‘spam’*3
‘spamspamspam’

I played around with this concept and got this:

>>> First = ‘Yaba’
>>> Second = ‘dabad’
>>> Third = ‘o’
>>> First + Second + (Third*8)
‘Yabadabadoooooooo’

Silly, perhaps. However, I will not forget it!

Can you think of a property that addition has that string concatenation does not?

Here is my answer (if you disagree, a respectful comment is always welcomed):

I found a possible answer on: http://www.acrobatfaq.com/atbref5/index/ActionsRules/Concatenationversusaddit.html

the plus symbol (+) is used both to concatenate (join) strings of text and to sum figures

2.9) COMMENTS

As programs get bigger and more complicated, they get more difficult to read […] it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments, and they start with the # symbol

The comment can be on a line by itself or at the end of a code line.

It is reasonable to assume that the reader can figure out what the code does; it is much more useful to explain why

2.10) DEBUGGING

At this point, the most common syntax errors are:

  • Illegal variable names such as: class and yield, which are keywords, or odd~job and US$, which contain illegal characters.
  • Also, the temptation to use a space in a variable name, in which case Python will think it is two operands without an operator

>>> bad name = 5
SyntaxError: invalid syntax

At this point, the most common runtime errors are:

  • “use before def;” which is trying to use a variable before you have assigned a value. This can happen if you spell a variable name wrong. RECALL that variable names are case sensitive.

>>> principal = 327.68 >>> interest = principle * rate
NameError: name ‘principle’ is not defined

At this point the most likely cause of a semantic error is the order of operations.

For example, to evaluate 1/2∏ , you might be tempted to write
>>> 1.0 / 2.0 * pi

  1. The division of 1.0/2.0 will happen first
  2. Then the result will be multiplied by pi

In fact the right answer would be: 1.0 / (2.0 * pi)

2.12 EXERCISES
(Here is my answer. If you disagree with it, a respectful comment is welcomed)

Exercise 2.3) Assume that we execute the following assignment statements:
width = 17
height = 12.0
delimiter = ‘.’
For each of the following expressions, write the value of the expression and the type (of the value of the expression).
1. width/2
2. width/2.0
3. height/3
4. 1 + 2 * 5
5. delimiter * 5

ANSWERS:

>>> width = 17
>>> height = 12.0
>>> delimiter = ‘.’

>>> width/2
8
>>> type (8)
<type ‘int’>

>>> width/2.0
8.5
>>> type (8.5)
<type ‘float’>

>>> height/3
4.0
>>> type (4.0)
<type ‘float’>

>>> 1 + 2 * 5
11
>>> type (11)
<type ‘int’>

>>> delimiter * 5
‘…..’
>>> type (‘…..’)
<type ‘str’>

Exercise 2.4) Practice using the Python interpreter as a calculator:
1. The volume of a sphere with radius r is 4/3∏r**3. What is the volume of a sphere with radius 5?

Hint: 392.7 is wrong!

>>> pi = 3.1415926535897932
>>> (4/3) * pi * (r**3)
392.6990816987241

I doubt of the validity because it is actually very close of the wrong answer. To be verified.

***

I found the error!

Here is the correct answer :

>>> pi = 3.1415926535897932
>>> r = 5
>>> (4.0/3) * pi * (r**3)
523.5987755982989

The error I made is not to include a “4.0” or a “3.0” to the first part of the equation. With that omission, the answer of the first part would be just “1”.

NOTE: Apparently in Python 3, the division of two integers may give a fraction number without specifying a “.0”.

2. Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?

>>> resale_price = 24.95
>>> wholesale_price = resale_price * 0.60
>>> print wholesale_price
14.97
>>> first_copy = wholesale_price + 3
>>> print first_copy
17.97
>>> additional_copies = wholesale_price + 0.75
>>> print additional_copies
15.72
>>> total_cost = first_copy + (additional_copies)*59
>>> print total_cost
945.45

3. If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?

>>> easy_pace = 8 + (15/60.0) #time in minutes per mile
>>> tempo_pace = 7 + (12/60.0) #time in minues per mile at a fast pace
>>> running_time = easy_pace + (3 * tempo_pace) + easy_pace #total running time in min
>>> print running_time
38.1

>>> start_time = 6 + (52/60.0) # start time in terms of hours
>>> print start_time
6.86666666667

>>> running_time_hr = running_time/60.0 #running time in terms of hours
>>> print running_time_hr
0.635

Breakfast hour:

>>> breakfast_time = start_time + running_time_hr #breakfast time in terms of hour
>>> print breakfast_time
7.50166666667
>>> int(breakfast_time) #this will give me the hour of the breakfast time
7

Breakfast minutes:

>>> hour = 60 # 1 hour equals 60 minutes
>>> breakfast_time_min = (breakfast_time – int(breakfast_time))*60.0 #this will give the minutes of the breakfast time
>>> print breakfast_time_min
30.1
>>> int(breakfast_time_min)
30

Breakfast seconds:

>>> minute = 60 # 1 minutes equals 60 seconds
>>> breakfast_time_sec = (breakfast_time_min – int(breakfast_time_min))*60 #this will give the seconds of the breakfast time
>>> print breakfast_time_sec
6.0

Breakfast time: 7:30:06 am

Binary Tree - Python Project

Binary Tree – Python Project

 

***

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