Coursera: Programming for Everybody (Summer 2015)

Hi there,

I hope you are getting ready for summer weather (… if you live in the northern hemisphere).

Spring NYC 2015

Spring NYC 2015

 

If you are planning on tackling programming this summer, here are some good news.

Professor Charles Severance‘s class: “Programming for Everybody” at the University of Michigan has just started. As you know, I have tried several ways to learn python. Also, if you remember, when I started I did not know how to open the terminal of my computer. The books and classes I attended all assumed that I knew how to navigate in the Terminal. So, when I was in class they jumped from screen to screen with little opportunity for me to even take notes. Stressful? Yes. Frustrating? Yes. Giving up? Never!

So, in my journey to learn Python, I have secretly hoped to find a teacher or a method that would help me bridge memory (vocabulary) and true understanding. Professor Severance uses tons of analogies to transmit information. That is priceless. Not only it is good for memory but also to grab and truly understand concepts.

 

This is not a regular class. This is a class where you’re supposed to learn something.

 

His teaching approach is quite unique and his pedagogy is among the best I have seen in my years in school. For instance, he emphasizes the human aspect of learning.

 

Accept the fact that you are going to be confused. Relax. Enjoy it. — Charles Severance

 

It is impressive that he succeeds in “connecting” with the audience given that it’s an MOOC (Massive Open Online Course). The last time I attended a MOOC, classes lasted one hour or even a little longer. The camera was at the end of the auditorium and the teacher was giving a monologue. In Programming for Everybody, Professor Severance talks directly to the camera and you will find moments when he asks you to try something (game, video, etc.) during the lecture. There is a pause for you to experiment and then come back to “class”. So, the interactive aspect of the class and the fact that the videos are 30 minutes long or so are definitely a wining combination.

So, if you are new to programming or want to give it another try, here is a great opportunity.

 

Have fun coding and enjoy summer!

 

Dare to begin

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

 

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