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

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

Arts and Science

Day 1: Getting to know Python

Hi there!

I decided to start with the book: “Think Python: How to Think Like a Computer Scientist”.

Here is the link to download the PDF version:

http://www.greenteapress.com/thinkpython/thinkpython.html

Think Python is an introduction to Python programming for beginners. It starts with basic concepts of programming, and is carefully designed to define all terms when they are first used and to develop each new concept in a logical progression. Larger pieces, like recursion and object-oriented programming are divided into a sequence of smaller steps and introduced over the course of several chapters.

 

Here is the first weekly lesson plan:

Objective :

Read the first chapter of the book “Think Python”, understand and incorporate the new terminology into daily life.

Readings :

Think Python

How to Think Like a Computer Scientist

by Allen B. Downey

Preface + Chapter 1

Incorporation :

Python and even computer science terms and expression are new to me. So my goal this week is to try to incorporate as much of new terms as possible.

Play with color and graphs in order to better grasps new concepts.

Assessment :

Exercises: 1.1 – 1.4

 

Arts and Science

Python Lesson Plan: Preface and Chapter 1

Hi there!

Here is my first weekly lesson plan:

Objective :

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

Readings :

Think Python

How to Think Like a Computer Scientist

by Allen B. Downey

Preface + Chapter 1

Incorporation :

Python and even computer science terms and expression are new to me. So my goal this week is to try to incorporate as much of new terms as possible.

Play with color and graphs in order to better grasps new concepts.

Assessment :

Exercises: 1.1 – 1.4

Arts and Science

Arts and Science