Chapter 11: Dictionaries (Notes from Think Python)

Dictionary

Dictionary

 Dictionaries :

It is best to think of a dictionary as an unordered set of  key: value  pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

Source: Python Software Foundation / 5.5 Dictionaries

  • Elements of a dictionary are never indexed.
  • Indices are called “keys”
  • A ” KeyValue ” pair is an Item
  • To add items (Key-Value pairs), we can use [ ] :

>>> eng2span [‘one’] = [‘uno’]
>>> print eng2span
{ ‘one’ : ‘uno’ }   key     value

>>> eng2span = {‘one’:’uno’ , ‘two’:’dos’ , ‘three’:’tres’}

Python uses Keys to look up the corresponding values.

>>> print eng2span [‘two’]
‘dos’

Operators :

  • in : It tells you whether something appears as a Key in the dictionary.
    >>> ‘one’ in eng2span
    True
  • NOTE 1 : Python uses an algorithm called a hashtable for the in operator.
  • NOTE 2 : Hash is a function that takes a value (of any kind) and returns an integer. Dictionaries use integers, called Hash Values, to store and look up Key-Value pairs.
  • TIP : Use Hash with immutable keys.

Built-in functions :

  • len ( ) : works on dictionaries
    >>> len (eng2span)
    3
  • dict ( ) : creates a new dictionary with no items { }

Methods :

  • values ( ) :
    >>> vals = eng2span.values()
    >>> ‘uno’ in vals    #Recall that ‘uno’ is a Value
    True
  • items ( ) : This method returns a list of tuples, where each tuple is a key-value pair.
    >>> d = { ‘a’: 0, ‘b’:1, ‘c’:2}
    >>> t = d.items()
    >>> print t
    [  (‘a’, 0),       (‘b’,1),           (‘c’,2) ]    # List of Tuples
    tuple           tuple             tuple
    key-value     key-value       key-value   #Each pair of key-value is an item.NOTE : The items of the dictionary are in no particular order.

Memo :

In order to keep track of values that have already been computed, we can store them in a dictionary.

[…] A previously computed value that is stored for later use is called a memo.

Source: Think Python by Allen B. Downey

Global Variables :

Variables in _ _main_ _ are sometimes called global because they can be accessed from any function. Unlike local variables, which disappear when their function ends, global variables persist from one function call to the next from any function. They persist from one function call to the next.
Source: Think Python by Allen B. Downey

  • Common use: Use Global Variables for flags, that is, Boolean variables that indicate (“flag”) whether a condition is true.
  • To reassign a Global Variable we have to declare the Global Variable before we use it:
    – been_called = False
    – def example2 ( ):
    – TAB global been_called
    – TAB been_called = TrueNOTE: If the Global Variable is mutable, we can modify it without declaring it.

Dictionaries as a set of counters :

Implentation no1 :
  • Create 26 variables one of each letter of the alphabet.
    – Traverse strings, and chained conditional to increment the corresponding counter.
Implentation no2 :
  • List with 26 elements.
    – Convert each character into a number, using the built-in function ord ( ).
    – Use the number as an index into the list, and increment the appropriate counter.
Implementation no3:
  • Create a dictionary with { character : counters }
    keys            values
  • We could add new items to the dictionary.
  • We could also increment the value of an existing item.

Looping and Dictionaries

  • The for statement traverses the keys of the dictionary.
    – def print_hist (h):   # where variable ‘h’ is a dictionary
    – TAB for c in h :
    – TAB TAB print  c,  h[c]
    key  value

Statements :

  • for

Lookups :

  • Given dictionary ‘d’
  • Given a Key ‘k’
  • Given the corresponding value of k, v   #where variable ‘v’ is a value
  • Forward Lookup : v = d [ k ]
  • No simple syntax to do a Reverse Lookup.

Long integers

>>> fibonacci (50)
12586269025L     #where L stands for Long Integer

Mathematical operators work with long integers, and the functions in the math module, too, so in general any code that works with int will also work with long.

Source: Think Python by Allen B. Downey

Tips for Debugging bigger datasets :

  •  Scale down input
    – Edit the files themselves
    or
    – Modify the program to read only the first n lines
  • Check summaries and types
    – Print summaries of the data: Number of items in a dictionary ; Total of a list of numbers
    – A common cause in runtime errors is a value that is not the right type. TO DEBUG: Print the type of a value
  • Write self-checks
    – Write code to check errors automatically
  • Pretty print the output
    – Formatting debugging output

To finish here is an image to visualize Strings, Lists and Dictionaries.

String / List / Dictionary in Python

String / List / Dictionary in Python

 

Olé to you nonetheless just for having the sheer human love and stubbornness to keep showing up.

Elizabeth Gilbert – TED Talk

 

Chapter 10: Lists

 

Lists illustration

Lists illustration

 

List :

A list is a sequence of values […] The values in a list are called elements or sometimes items.

 

Syntax:

[ 1,  2,  [ ‘three’,  ‘four’ ],  5  ]

  • Lists’ elements can be: int, strings, float, other lists
  • Lists may be nested.
  • Lists are mutable:
    • >>> numbers = [17, 123]
    • >>> numbers [1] = 5
    • >>> print numbers
    • [17, 5]

 

List Assignment :

  • We can assign list values to variables.

>>> cheeses = [‘Brie’, ‘Jarlsberg’, ‘Gouda’]    #Variable cheeses gets a list value
>>> numbers = [17, 123]    #Variable numbers gets a list value
>>> empty = []    #Empty list    #Variable empty gets a list value
>>> print cheeses, numbers, empty

[‘Brie’, ‘Jarlsberg’, ‘Gouda’] [17, 123] []

 

Boolean operators that work with Lists :

  • in
  • is

 

Traversing a list :

  • for loop

for i in cheeses:
TAB print i

 

To write or update the elements on a list :

  •  To write or update the elements in the list, we work with indices:

 

For Loop Traversing List

For Loop Traversing List

 

NOTE: “A For loop over an empty list never executes the body”

 

Python List update

Python List update

 

Operations that apply to lists :

  • + (concatenation)
  • * (multiplication)

 

List slicing :

List slicing

List slicing

 

 

List methods :

 

  • append : adds a new element to the end of a list
    >>> t = [‘a’, ‘b’, ‘c’]
    >>> t.append ( ‘d’ )
    >>> print t
    ‘a’, ‘b’, ‘c’, ‘d’

 

  • extend : takes a list as an argument and appends all of the elements
    >>> t1 = [‘a’, ‘b’, ‘c’]
    >>> t2 = [‘d’, ‘e’]
    >>> t.extend ( t2 )
    >>> print t1
    ‘a’, ‘b’, ‘c’, ‘d’, ‘e’
    NOTE: t2 was left intact/unmodified

 

  • sort : arranges the elements of the list from low to high

 

  • capitalize :

The method capitalize() returns a copy of the string with only its first character capitalized. For 8-bit strings, this method is locale-dependent.

Source: Tutorials Point / Python String capitalize() Method

 

  • split: breaks a string into words

 

  • join:

[The method] join is the inverse of split. It takes a list of strings and concatenates the elements.

[NOTE] join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter.

 

Python split method

Python split method

 

  • pop: “modifies the list and returns the element that was removed”
    It works with indices. If no index, then the pop method deletes and returns the last element.

 

  • remove: This method is useful ” if we know the element we want to remove but not the index”.
    NOTE: The return value of remove is None.

 

del statement :

  • del: modifies the list and returns the elements that were not removed.

To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting

Source: http://www.tutorialspoint.com/python/python_lists.htm

 

Built-in functions :

 

  • sum :
    >>> t = [1, 2, 3]
    >>> sum ( t )
    6#6 is the combination of the sequence elements

 

  • list :  breaks a string into individual characters (elements)
    >>> t = ‘happy’
    >>> x = list ( t )
    [‘h’, ‘a’, ‘p’, ‘p’, ‘y’]#6 is the combination of the sequence elements

 

 Conversion :

 

Conversions: Python List - Strings

Conversions: Python List – Strings

 

 Object and Values :

List: Objects and Values

List: Objects and Values

 

To verify whether two variables refer to the same object, we can use the Boolean is operator:

>>> d = [1, 2, 3]

>>> g = [1, 2, 3]

>>> d is g
False

 

Logic:

  • Variable d is equivalent to variable g because they have the same element.
  • Variable d is not identical to variable g because they are not the same object.
  • If two objects are identical, then they are also equivalent.
  • If two objects are equivalent, they are not necessarily identical.

NOTE: An object has a value.

 

Aliasing :

An object with more than one reference has more than one name, so we say the object is aliased.

 

>>> a = [1, 2, 3]

>>> b = a

>>> b is a
True

  • “If the aliased object is mutable, changes made with one alias affect the other”

 

Aliasing

Aliasing

 

Beware, working with mutable objects and aliasing is error-prone. For immutable objects (like strings), aliasing is not much of a problem.

 

***

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 8: Strings

DNA String

DNA String

8.1 A String is a sequence

A string is a sequence of characters.

Since it is a sequence, we can access the characters one at a time with the bracket operator [].

The expression in brackets is called an index. The index indicates which character in the sequence you want (hence the name).

String / Sequence / Index

String / Sequence / Index

It is important to note that “the index is an offset from the beginning of the string, and the offset of the first letter is zero”.

Inside the bracket operator, we can use integers, variables and operators as indexes.

8.2 len

The function len is a built-in function that counts and returns the number of characters in a string.

Here is an example of how we use the len built-in function:

len function / Sequence / Indices

len function / Sequence / Indices

In order to find a character in our string, we can go by two ways:

  • Start from the beginning of the string and move forward:
    • However, we must remember that the first character is position (or index) 0, the next character is position (or index) 1, and so on.
    • When we move forward (from the beginning to the end of the string) we use positive integers.
  • Start at the end of the string and move backward:
    • When we move backward (from the end to the beginning of the string) we use negative integers.
    • -1 index indicates the first character from the end.

8.3 Traversal with a for loop

Soon we will be able to “scan” a string one character at a time. Usually, iteration (“or the scanning process”) starts at the beginning. The objective is to select each character, do something to it, and continue until the end of the sequence (or string).

This pattern of processing is called a traversal […]

Traverse: To iterate through the items in a sequence, performing a similar operation on each.

traversal with while and for loops

traversal with while and for loops

On the right column (using the while loop), the loop displays the string and displays each letter on a line by itself.

  • the variable “fruit” gets the string ‘banana’
    • the sequence of the characters in the string ‘banana’ is:
    • b    a   n   a   n   a
    • 0    1   2   3   4   5
  • the variable “index” is initialized with the number 0.
  • loop condition: index <len(fruit)
    • The built-in function len calculates the number of characters in the string ‘banana’, which is 6.
  • The while statement may be readas follow:
    • while index < len(fruit):
      • While this is true: variable “index” is less than 6 (which is the length of the string ‘banana’),
      • index < 6
    • letter = fruit [index]
      • the variable “letter” gets the value of the character at the position set by variable “index” in the string ‘banana’ (or variable ‘fruit’).
    • print letter
      • print variable “letter”
    • index = index + 1
      • variable “index” gets the value of itself incremented by one (1).
      • the last character accessed is the one with the “index” len(fruit) – 1, which is the last character in the string.

On the left column (using the for loop), the loop displays the string and displays each letter on a line by itself.

  • the variable “fruit” gets the string ‘banana’
    • the sequence of the characters in the string ‘banana’ is:
    • fruit:   b    a   n   a   n   a
    • index: 0    1   2   3   4   5
  • The for statement may be readas follow:
    • for char in fruit:
    • iterate for every item (“char”) in the sequence provided in variable “fruit”
    • print char
  • “Each time through the loop, the next character in the string is assigned to the variable . The loop continues until no characters are left.”

Exercise 8.1) Write a function that takes a string as an argument and displays the letters backward, one per line.

>>> def upside_down (x):    #define the function upside_down with variable parameter x
…     index = len(x) – 1
…     while index >= 0:
…             letter = x[index]
…             print letter
…             index = index – 1

>>> upside_down(‘gateman’)
n
a
m
e
t
a
g
>>>

The following example shows how to use concatenation (string addition) and a for loop to generate an abecedarian series (that is, in alphabetical order).

>>> prefixes = ‘JKLMNOPQ’
>>> suffix = ‘ack’
>>> for letter in prefixes:
…     print letter + suffix

Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack
>>>

Exercise 8.2) Modify the program to write “Ouack” and “Quak” instead of “Oack” and “Qack”.

>>> for letter in prefixes:
…     if letter == “O” or letter == “Q”:
…             print letter + “u” + suffix
…     else:
…             print letter + suffix

Jack
Kack
Lack
Mack
Nack
Ouack
Pack
Quack
>>>

8.4 String slices

A segment of a string is called a slice.

We can select a segment (or slice) of a string as follows:

>>> s = ‘Monty Python’
>>> print s [0:5]
Monty
>>> print s [6:12]
Python
>>>

It is somewhat similar than selecting a character. However, we must specify where the slice starts and where it ends in the sequence.

The operator [n : m] returns the part of the string from the “n-eth” character to the “m-eth” character, including the first but excluding the last.

String slice

String slice

Also, it is helpful to know that:

  • to start the slice from the beginning of the sequence to a position ‘m’, we can write:
    • >>> fruit = ‘banana’
      >>> fruit [:m]           # Let m = 3
      ‘ban’
  • to start the slice from the position ‘n’ to the end of the sequence, we can write:
    • >>> fruit = ‘banana’
      >>> fruit [n:]           # Let m = 3
      ‘ana’

NOTE: There is a rule for string slices to work:

The first index (for instance ‘n’) should be less than the second index (for instance ‘m’). Otherwise, it will result in an empty string represented by two quotation marks:

>>> fruit [3:3]

>>> fruit [4:3]

>>>

An empty string contains no characters and has length 0, but other than that, it is the same as any other string.

Exercise 8.3) Given that “fruit” is a string, what does “fruit [:]” mean?

>>> fruit [:]
‘banana’
>>>

It means that it goes from the first index to the last index of the string’s sequence.

Watch Minions playing with the concept of a string slice. Have fun!

8.5 Strings are immutable

[…] strings are immutable, which means you can’t change an existing string. The best you can do is create a new string that is a variation on the original:

>>> greeting = ‘Hello, world!’
>>> new_greeting = ‘J’ + greeting[1:]

#This assignment concatenates a new first letter onto a slice of the variable “greeting”.
# It has no effect on the original string ‘Hello, world!’
>>> print new_greeting
Jello, world!
>>>

Moreover, it is important to acknowledge that our understanding of the object notion is very broad. An object is the same thing as a value. In fact, we use the “object” and “value” interchangeably.

8.6 Searching

Searching in Python

Searching in Python

Professor Downey points out that this is the first time we see a return statement inside a loop.

Here is the logic broken down:

  • variable “index” is initialized at 0,
  • while it is true that the position determined by variable “index” is less than the length of the sequence in variable “word”,
    • if the character from the string in variable “word” (at position “index”) is equal to variable “letter” (the character we are looking for with the function find),
      • then, return variable “index”,
    • increment variable “index” by one,
  • while it is false that the position determined by variable “index” is less than the length of the sequence in variable “word”,
    • the function breaks and
    • it returns -1

This pattern of computation – traversing a sequence and returning when we find what we are looking for – is called search.

Exercise 8.4) Modify the equation find so that it has a third parameter, the index in word where it should start looking.

>>> def find(word, letter, index):
…     while index < len(word):
…             if word[index] == letter:
…                     return index
…             index = index + 1
…     return -1

>>> find (‘banana’, ‘n’, 0)
2
>>> find (‘banana’, ‘n’, 3)
4
>>>

8.7 Looping and counting

The following program counts the number of times [a given character] appears in a string:

>>> word = ‘banana’
>>> count = 0
>>> for letter in word:
…     if letter == ‘a’:
…             count = count + 1

>>> print count
3
>>>

The program demonstrate another pattern of computation called a counter. The variable count is initialized to 0 and the incremented each time an a is found.

When the loop exits, count contains the result – the total number of a‘s.

Exercise 8.5) Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments.

Exercise 8.6) Rewrite this function so that instead of traversing the string, it uses the three parameter version of find from exercise 8.4.

8.8 String methods

A method is a function that is associated with an object and called using dot notation.

Professor Downey points out that it is “similar to a function in the sense that it takes arguments and returns a value”.

  • upper method:

If we take the example of the method upper, the syntax works as follows:

>>> word = ‘banana’
>>> new_word = word.upper()

#The method upper takes the string in variable “word” and returns a new string will all uppercase letter.
#The empty parentheses indicate that this method takes no argument.

>>> print new_word
BANANA
>>>

Invocation : Similar than calling a function, a method is invoked. In the example above, we would say: “we are invoking upper on the [variable] word”.

  • find method :

To find a character in a string, the method called find does that:

>>> word = ‘banana’
>>> index = word.find(‘a’)   #We invoke find on [variable] word.
>>> print index
1
>>>

To find a substring in a string, the method find does that too:

>>> word.find(‘na’)

#this line of code indicates us where the first substring ‘na’ is found. In this case, the substring appears in index (or position) 2, starting from the beginning of the string.
‘ b    a   n   a   n   a ‘
0    1   2   3   4   5
2
>>>

To find a substring in a string starting from a precise index (or position) in the string, the method find is helpful too:

>>> word.find(‘na’, 3)

# Starting from index 3, the first substring ‘na’ is found in index (or position) 4.
‘ b    a   n   a   n   a
0    1   2   3   4   5
4
>>>

****

Finally, the method find may take up to three parameters, which are:

  1. the character or substring we are looking for
  2. the index (or position ) of where our search starts
  3. the index (or position ) of where our search ends

For instance:

>>> name = ‘bob’
>>> name.find(‘b’, 1, 2)

#this line of code indicates us where the first substring ‘na’ is found. In this case, the substring appears in index (or position) 4, starting from index 3.
‘ b      o     b  ‘
0      1     2
-3    -2    –1
-1
>>>

8.9 The in operator

The word in is a Boolean operator that takes two strings and returns True if the first appears as a substring in the second :

>>> ‘a’ in ‘banana’
True
>>> ‘ok’ in ‘banana’
False
>>>

Another use of the word in with strings is:

>>> def in_both (word1, word2):
…     for letter in word1:
…             if letter in word2:
…                     print letter

>>> in_both (‘apples’, ‘oranges’)
a
e
s
>>>

Think Python: in operator

Think Python: in operator

8.10 String comparison

The relational operators work on strings.

String equality:

>>> word = ‘banana’
>>> if word == ‘banana’:
…     print ‘All right, bananas.’

All right, bananas.
>>>

String inequality:

>>> word = ‘banana’
>>> if word < ‘banana’:
…     print ‘Your word, ‘ + word + ‘ , comes before banana.’
… elif word > ‘banana’:
…     print ‘Your word, ‘ + word + ‘ , comes after banana.’
… else:
…     print ‘All right, bananas.’

All right, bananas.
>>>

Python does not handle uppercase and lowercase letters the same way that people do.

This is another difference between natural language versus formal language. Remember Chapter 1?

Therefore, Python will interpret the uppercase letters as coming before all the lowercase letters.

>>> word = ‘Pineapple’
>>> if word < ‘banana’:
…     print ‘Your word, ‘ + word + ‘ , comes before banana.’
… elif word > ‘banana’:
…     print ‘Your word, ‘ + word + ‘ , comes after banana.’
… else:
…     print ‘All right, bananas.’

Your word, Pineapple , comes before banana.
>>>

A way to circumvent this problem is to “convert strings to a standard format, such as all lowercase, before performing the comparison”.

8.11 Debugging

 

 

***

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

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