Follow Logic Versus Be Logic

Hi there,

I read from cover to cover Allen B. Downey’s book “Think Python: How To Think Like a Computer Scientist”. I was able to follow the logic of the book. However, I realized that there is a significant difference between following logic and being logic.

I explain. So, as I was advancing in my reading, I had also been practicing with the examples provided in the book. It was actually not that hard … at the beginning. To answer the questions, I had to re-arrange the examples that were used to illustrate the concepts and then answer the questions. Basically, copy-paste with a slight twist. This strategy seemed to workout until Chapter 8.

The problems in Chapter 8 required me to have a complete list of past code blocks, which was fine. However, I could not just twist them a bit and answer the questions. I was wondering when I would be able to start coding by myself, meaning not using the already built code-blocks from the book.

One day as I was reviewing the book’s exercises with my mentor; he asked me this crucial and yet simple question: “Why do you use a for loop“. “Because this is how the book solves it” I replied.

“Understanding the mechanics of a for loop is part of the basics” my mentor concluded.

I then realized that my pledge for this project was to fully understand the logic and concepts behind Python. There was no point for me to surf the contents of the book if I could not swim in them, create with them.

That day, my mentor and I had a brainstorming session. The goal was to make coding logic part of me. So, we came with this curriculum:

  • Algorithms I
  • Algorithms II
  • Object orientation
  • Project

At all levels, practice will predominate.

For the section “Algorithms I”, I found a website ( CodingBat.com ) that helped me start little and let me build coding confidence.

No cheat-sheet; just the problems and my logic! CodingBat.com tests the code block for you. It is rewarding that after a series of tests, you code works.

Aside from the practice problems that my mentor gives me, I am looking for more practice problems. Let me know if you have some.

Happy coding!

***

NEWS:

 

 

***

 

Blue - Shade no1

Blue – Shade no1

Blue - Shade no2

Blue – Shade no2

Blue - Shade no3

Blue – Shade no3

 

 

 

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

 

 

PyCon 2014: What A Journey!

Hi there,

My experience at #pycon2014 was extraordinary. Here is why.

 

Networking @PyCon :

  • I met inspiring programmers/developers who were willing to share their experience and time. Amazing.
  • I talked with 99% of the booth presenters. The companies that were present in PyCon shared one characteristic: their hunger for innovation. Here is the complete list of the companies that were present:
  • I met women who code from around the world through PyLadies, Girl Develop It, MongoDB, and many other companies/institutions.
    • Kudos to all women who have paved my way into coding. Thank you!
PyLadies Booth - PyCon 2014

PyLadies Booth – PyCon 2014

 

PyCon 2014

PyCon 2014

 

PyCon 2014 - Palais de Congrès Montréal

PyCon 2014 – Palais de Congrès Montréal

 

Open Source Community :

  • What is Open Source?

Free and open-source software (FOSS) is computer software that can be classified as both free software and open source software. That is, anyone is freely licensed to use, copy, study, and change the software in any way, and the source code is openly shared so that people are encouraged to voluntarily improve the design of the software.

Source: Wikipedia / Free and Open Source Software

  •  How is the FOSS notion related to Python?

CPython, the reference implementation of Python, is free and open source software and has a community-based development model, as do nearly all of its alternative implementations. CPython is managed by the non-profit Python Software Foundation.

Source: Wikipedia / Python (programming language)

  •  PyCon 2014 gave me the opportunity to realize that there is a great Open Source Community that exists, collaborates, and thrives. I like to call it “Python Ecosystem”.
    • Moreover, I had the privilege to chat with a developer from Fastly. If I recall well, he mentioned something like “Just remember to give back whenever you develop something great”.  I will keep those wise words with me.
    • Here is a Tweet that illustrates the collaboration spirit at PyCon:

      This is the first day of Sprints at #pycon2014!! Looking forward for these 4 days of intensive learning, development and camaraderie! @pycon

      Source: Tryolabs / April 14th, 2014

 

Broadening my horizons @PyCon :

  • I attended several workshops and talks. All of them taught me something new.
    • Kudos to the Google team who presented on April 10th, 2014. The workshop was great and they kept their cool when they answered an inappropriate question. Greatness and Wisdom!

 

Programming Bucket List :

  • Professor Allen B. Downey: The Python knowledge I have acquired is mostly thanks to Professor Downey and the free book he wrote, Think Python: How to Think Like a Computer Scientist (2012)
    • On April 10th, 2014 I met and thanked Professor Downey in person at the O’Reilly booth at PyCon! Until today, I have spent dozens and dozens of hours learning with his book. As I previously mentioned, I read some chapter two or three times. The book includes some subtle humor. So, meeting him was definitely on my Programming Bucket List.
    • The second best quality of this book (the fist being that it is free!) is that it is written as if Professor Downey was standing before you trying to help you understand the concepts. Priceless! A great teacher is someone who teams up with you to successfully transmit knowledge.
  • Guido van Rossum: Guido, as everybody called him @PyCon (and not Mr van Rossum) gave a presentation on April 13th, 2014.
    • I am disappointed. I missed it.
    • I must make it to PyCon 2015 now!

 

@PyCon presentations :

Here are some links that can be useful to see PyCon 2014 presentations:

 

Special Thanks :

My PyCon journey was possible thanks to the support from PyLadies, Caktus Group and NumFocus.

Thank you for believing in me and offering me this opportunity.

 

PyCon Experience

Hi there,

I first heard of PyCon on my very first meeting with NYC PyLadies back in September 2013. Kat, an accomplished and creative Pythonista mentioned that it was a truly great and enriching experience to attend PyCon. If I remember well, I think that a member of NYC Python Meetup Group was present as well and corroborated Kat’s anecdote.

I was curious. I wished really hard to have one day the possibility to attend PyCon.

Today, I am having the privilege to attend PyCon 2014 thanks to the support of NYC PyLadies, Caktus Group and NumFocus. Can you imagine? I am ecstatic right now!

My objectives for PyCon 2014 are:

  • Thank in person PyLadies, Caktus Group and NumFocus.
  • Network with Pythonistas from around the world.
  • Learn from the conferences and fellow Pythonistas.
  • Visit every single booth and chat with the representatives.
  • Have a clear idea on what are the next steps in becoming an excellent programmer/Pythonista.
  • Have fun!

My dreams for PyCon 2014 are:

  • Meet a mentor.
  • Create long lasting connections with inspiring Programmers/Pythonistas.
  • Be inspired.

I will be at the PyLadies booth on Friday (11:00a.m. – 12:00 p.m. ). Come and say hi!

NYC PyLadies stamp

NYC PyLadies stamp

 

Developing Art!

Hi there,

I found a project that harmonizes art and coding!

DevArt

Learning Python is great. If I can play with it and create art, that would be amazing!

This is it!

Paul Kinlan and Karsten Schmidt share great tips and resources to play with code.

P.S. The interview below is quite long. Nevertheless, there are great tips and resources shared.

Enjoy!

 

Chapter 9: Case Study – Word Play

 

 

Think Python Chapter 9: Case Study / Word Play

Think Python Chapter 9: Case Study / Word Play

Hi there!

 

I talked to my mentor (yes, after all this time I just found one!) about my increased frustration in solving certain problems from the book. For instance, I spend two weeks trying to solve by my own the exercises from chapter 4. It drove me literary crazy! Plus, I had the impression I was stagnating and start thinking about … maybe I am not good enough for this! … I know, hard stuff!

 

My mentor’s advice was: “Try to solve the problems in a given time (15, 30, 60 minutes). Then, peek at the answers and spend some time comparing your logic with the answer from the book.”

So, with this piece of advice, let us start Chapter 9.

9.1 Reading word lists

 

Python can read plain text files.

 

The built-in function open takes the name of the file as a parameter and returns a file object you can use to read the file.

 

file object: A value that represents an open file.

 

 

Open text files with Python

Open text files with Python

Python has several opening modes:

  • ‘r’ indicates that the file is open for reading
  • ‘w’ indicates that the file is open for writing

 

The file object provides several methods for reading including readline , reads characters from the file until it gets to a newline and returns the result as a string.

 

Assume that the file “names.txt” includes this list:

alexandra

alibaba

alysson

bethany

catherine

eleanor

francesca

giovanna

 

The first word in the ‘names’ list is “alexandra”.

 

Read text files with Python

Read text files with Python

 

We can get rid of the whitespace with the string method strip.

 

>>> fin = open ( ‘names.txt’ )

>>> line = fin.readline ( )

>>> name = line.strip ( )

>>> print name

alibaba

 

A file object can also be part of a for loop:

 

fin = open ( ‘names.txt’ )

for line in fin:

name = line.strip ( )

print name

 

9.3 Reading word lists

 

In this section Professor Downey points out that the exercises from Section 9.2 could be solved with the search pattern in Section 8.6.

problem recognition: It basically means not to re-invent the wheel. “[You] recognize the problem you are working on as an instance of a previously-solved problem, and apply a previously-developed solution.

 

9.4 Looping with indices

When we work with indices, many ways lead to Rome.

 

Looping with indices

Looping with indices

9.5 Debugging

So far, the programs we have written can be verified by hand (computing or searching /finding ourselves). However, we should start testing programs in a more systematic way.

 

Let us test the program “has_no_e”:

  • Test no1) Test words with an “e” at the beginning
  • Test no2) Test words with an “e” at the end
  • Test no3) Test words with an “e” somewhere in the middle
  • Test no4) Test long words
  • Test no5) Test short words
  • Test no6) Test very short words
  • Test no7) Perform the special case test. This test can

 

Special case: A test tat is typical or non-obvious (and less likely to be handled correctly).

 

 

***

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

Code time!

Hi there!

Let us code for a whole week and practice with the exercises from chapter 5-7 from the book, Think Python. This will solidify all the concepts we have learned so far.

I am reluctant to post all the answers. The reason is that it is very rewarding (and I admit at times very frustrating) to create, develop and find our own answers.

Nevertheless, here is a fun twist:

I will be online most of this week working on the exercises. So, if you are stuck or just want to code in tandem, let me know.

There are great events in order to code in groups. Here are a few:

If you have ideas on how to make it more challenging, interactive and interesting let me know.

Code time!

****

I know I said I would code for a whole week. However, it took me a bit more time to fully understand Swampy World and finish questions from chapter 4. I did not want to just surf through the answers.

Furthermore, I will not post the answers because the questions are so masterfully thought that it is great to FINALLY understand the lines of code after the n-th attempts! If you are stuck though and want to discuss them, let me know. Now, I can help.

By the way, if you see a mistake or want to improve something, let me know. I will be glad to correct it.

March 3-7: I devoted a whole week to understand the intricacies of the code blocks for questions 4.1 to 4.5 from Section 4.12. So, as I mentioned above, playing with Bob (the Turtle) was somehow frustrating. Here are some of the outputs for those questions.

Exercise 4.1 (2)

Exercise 4.1 (2) Stack Diagram of the Circle Function

Exercise 4.1 (2) Stack Diagram of the Circle Function

Exercise 4.2 (Section 4.12)

Exercise 4.2 / Section 4.12: Three Flowers

Exercise 4.2 / Section 4.12: Three Flowers

Exercise 4.3 (Section 4.12)

Section 4.12 Exercise 4.3

Section 4.12 Exercise 4.3

March 10:

March 12:

March 14 (Pi Day):

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

Chapter 7: Iteration – Think Python

Hi there!

So, we have made it to Chapter 7.

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

The title of chapter 7 is Iteration.

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

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

Source: Wikipedia/Iteration

7.1 Multiple assignment

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

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

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

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

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

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

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

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

7.2 Updating variables

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

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

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

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

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

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

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

7.3 The while statement

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

Python statements that make recursion easier are:

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

Recursion versus For Loop versus While Loop

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

Here is the flow of execution for the while loop:

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

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

The objective is to avoid infinite loops.

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

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

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

7.4 Break

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

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

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

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

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

Exercise 7.1

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

Exercise 7.1) Print_n using a while statement

Exercise 7.1) Print_n using a while statement

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

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

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

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

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

Netwon’s Method

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

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

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

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

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

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

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

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

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

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

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

***

Acknowledgments :

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

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

Thank you Professor Downey for making this knowledge available.

 

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

Thank you

Chapter 6: Fruitful functions – Think Python

Hi there,

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

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

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

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

6.1 Return values

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

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

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

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

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

Absolute_Value definition (alternative conditional)

Absolute_Value definition (alternative conditional)

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

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

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

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

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

Exercise 6.1 Write a compare function that :

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

Exercise_6_1_compare

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

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

Scenario no1 – Interactive mode

  • Code block #1: using the return statement

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

>>> absolute_value(3)
3
>>>

Scenario no2 – Interactive mode

  • Code block #2: using the print statement

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

>>> absolute_value(3)
3
>>>

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

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

Scenario no1 – Script mode

  • Code block #1: using the return statement

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

absolute_value(3)

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

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

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

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

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

Scenario no2 – Script mode

  • Code block #2: using the print statement

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

absolute_value(3)

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

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

This time, we will see:

3

Which is the answer of abs_val(3).

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

Does this help?

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

6.2 Incremental development

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

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

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

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

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

c² = a² + b²

Pythagoream_Theorem

Pythagoream_Theorem

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

NYC scaffolding

NYC scaffolding

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

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

Exercise 6.2

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

6.3 Composition

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

Circle (xc, yc)

Circle (xc, yc)

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

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

>>>

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

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

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

>>>

result = area (radius)

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

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

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

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

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

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

6.4 Boolean functions

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

Let us consider this example:

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

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

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

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

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

Boolean functions are often used in conditional statements.

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

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

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

6.5 More recursion

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

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

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

Who is Alan Turing?

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

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

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

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

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

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

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

Factorial function

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

For instance:

Factorial function

Factorial function

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

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

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

Stack diagram 3!

  • Step 3) Carry out the plan

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

>>> factorial (3)
6
>>>

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

6.6 Leap of faith

Trust in the code blocks you created and tested.

Here is another example of a leap of faith!

6.7 One more example

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

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

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

fibonacci function

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

6.8 Checking types

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

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

Factorial function improved

Factorial function improved

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

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

>>> factorial (8)
40320
>>>

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

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

6.9 Debugging

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

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

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

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

 

***

Acknowledgments :

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

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

Thank you Professor Downey for making this knowledge available.

 

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

Thank you