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 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

Think Python Chaper 1: New terms + notes

NOTES on Chapter 1: The way of the program

1.1) Python programming language:

Low-level language sometimes referred to as “machine” or “assembly” languages
Disadvantages: Can run on only one kind of computer and have to be re-written to run on another.

Source code -> Interpreter -> Output

High-level language. Example: Python, C, C++, Java
Advantages: Easier to program, take less time to write, shorter and easier to read, are portable (meaning they can run on different kinds of computers)

Source code -> Compiler -> Object code -> Executor -> Output

Python is considered an interpreted language because Python programs are executed by an interpreter.

There are 2 ways to use the interpreter: interactive mode and script mode.

Interactive mode: You type Python programs and the interpreter displays the result. Example:
>>> 1 + 1 (you type)
2 (the interpreter replies)

Store code in a file -> Use the interpreter to execute the contents of the file

Content of a file = Script
By convention, Python scripts have names that end with .py

To execute the script, you have to tell the interpreter the name of the file. If you have   a script named mba.py and you are working in a UNIX command window, you type: python mba.py
In other development environments, the details of executing scripts are different.
For help and instructions: http://python.org

Program:

  • Input
  • Output
  • Math
  • Conditional execution
  • Repetition

Programing is the process of breaking a large, complex task into smaller and smaller substasks until the subtasks are simple enough to be performed with one of these basic instructions.

1.3) What is debugging?

– Syntax errors
Example: “1+2” is correct. However, “+7^” is a syntax error.

English language can tolerate syntax errors, think of some poems (e.e. cummings)
Python is not so forgiving. If there is a single syntax error anywhere in your program, Python will display an error message and quit, and you will not be able to run your program.

– Runtime errors: Do not appear until after the program has started running. These errors are also called exceptions. Are rare (… and bad).

– Semantic errors:
If there is a semantic error in your program, it will run successfully in the sense that the computer will not generate any error messages, but it will not do the right thing. It will do something else.

The problem is that the program you wrote is not the program you wanted to write. The meaning of the program (its semantics) is wrong.

Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing.

1.3.4) Experimental debugging

In some ways, debugging is like detective work. You are confronted with clues, and you have to infer the process and events that led to the results you see.

Debugging is also like experimental science: Hypothesis (you have an idea of what is going wrong)  – Modification (or experiment) – Your hypothesis is either correct (in that case you can predict the result) or wrong (and you have to come with a new idea).

1.4) Formal and natural languages

Natural languages (such as English, Spanish, etc.): evolve naturally, are full of ambiguity (which people deal with by using contractual clues and other information), employ lots of redundancy (as a result, they are often verbose), are full of idiom and metaphor,

Formal languages: designed by people for specific applications, have strict rules about syntax, are designed to be nearly or completely unambiguous (which means that any statement has exactly one meaning, regardless of context), are less redundant and more precise, formal languages mean exactly what the say,

Syntax rules come in two categories: tokens (basic elements of the language such as words, numbers, chemical elements, etc.) and structure of a statement (the way the tokens are arranged).

Exemple 1.1:

– Hte huose is rde.

– Red the is house.

Parsing: When you read a sentence in English or a statement in a formal language, you have to figure out what the structure of the sentence is.

For instance: The penny dropped

The penny = the subject
dropped = the predicate

Programming languages are formal languages that have been designed to express computations.

The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready.

1.5) The first program

I downloaded Python. However, since I never saw what a Python window or interface looked like, I wandered a bit.

At this step, I did not know how to open Python.

Here is how I opened it:

MAC / Utilities / Terminal

Once the Terminal opened; I typed python. A python session started. Bingo

Python 2:

>>>
>>>print ‘Hello, World!’

Python 3:
>>>print (‘Hello World!’)
The parentheses indicate that  print  is a function.

print statement = displays a value on the screen

Exercise 1.2: use print in the Python search window

Excersise 1.3:
>>>help ()
Welcome to Python 2.7!  This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type “quit”.

To get a list of available modules, keywords, or topics, type “modules”,
“keywords”, or “topics”.  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as “spam”, type “modules spam”.

Excersise 1.4: If you run a 10 kilometer race in 43 minutes 30 seconds, what is your average time per mile? What is your average speed in miles per hour? (Hint: there are 1.61 kilometers in a mile).

10km —> 43.5 minutes (… it reminds me of the state diagram)

Step 1)

If,         1.61 km = 1 mile

Then,    10 km = Variable x is the number of miles that correspond to 10km

Variable x = 10 Km * 1 mile
                         1.61 km

In Python:
>>>(10*1)/1.61
6.211180124223602

Therefore, 10 km = 6.21 miles

Step 2)

It is equivalent to say that the average speed in miles/minutes is:

6.21 miles —-> 43.5 minutes

or

6.21 miles —-> 0.725 hour (43.5 minutes/60 minutes per hour)

In Python:

>>>43.5/60
0.725

If we want to know the average speed in miles per hour, then:

6.21 miles —–> 0.725 hour

Variable y ——> 1 hour

Variable y is the miles ran in one hour.

(1 Hour * 6.21 miles)/0.725 hour =

In Python:

>>> (1*6.21)/0.725
8.565517241379311

Rounded to two decimals is 8.57 miles

ANSWER: The average speed in miles per hour is 8.57 miles/hour

Let me know if you find mistakes in my logic.

 

***

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