0% found this document useful (0 votes)
0 views

Python

The document outlines a course on Object-Oriented Programming (OOP) using Python, covering key concepts such as classes, objects, inheritance, and polymorphism. It details the course objectives, learning outcomes, and a comprehensive syllabus that includes topics like variables, functions, iteration, and file handling. The course aims to equip students with advanced programming skills and practical mastery of OOP concepts in Python, culminating in a project that integrates Python with MySQL.

Uploaded by

jonathanelimu26
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Python

The document outlines a course on Object-Oriented Programming (OOP) using Python, covering key concepts such as classes, objects, inheritance, and polymorphism. It details the course objectives, learning outcomes, and a comprehensive syllabus that includes topics like variables, functions, iteration, and file handling. The course aims to equip students with advanced programming skills and practical mastery of OOP concepts in Python, culminating in a project that integrates Python with MySQL.

Uploaded by

jonathanelimu26
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Object Oriented Programming

(Python)
DIT 6202

March 2025
Contents
1 Introduction .............................................................................................................. xiii

1.1 Over view of OBJECT-ORIENTED programming ......................................... xiii

1.1.1 What is Object-Oriented Programming (OOP)? ...................................... xiii

1.1.2 Key Features of OOP: .............................................................................. xiii

1.1.3 Classes and Objects.................................................................................. xiii

1.1.4 Encapsulation ........................................................................................... xiii

1.1.5 Inheritance................................................................................................ xiv

1.1.6 Polymorphism .......................................................................................... xiv

1.1.7 Abstraction ............................................................................................... xiv

1.1.8 Importance of OOP ................................................................................... xv

1.2 What is Python? ................................................................................................ xv

1.2.1 What can Python do? ................................................................................ xv

1.2.2 Why Python? ............................................................................................. xv

1.2.3 Python Syntax compared to other programming languages .................... xvi

1.2.4 Python Install ........................................................................................... xvi

1.2.5 Python Quickstart..................................................................................... xvi

1.2.6 The Python Command Line .................................................................... xvii

1.3 Python IDEs and Code Editors ...................................................................... xviii

1.3.1 IDLE ...................................................................................................... xviii

1.3.2 Sublime Text 3 ....................................................................................... xviii

1.3.3 Atom ........................................................................................................ xix

1.3.4 Thonny ...................................................................................................... xx

1.3.5 PyCharm .................................................................................................. xxi

1.3.6 Visual Studio Code ................................................................................. xxii

PAGE 2
1.3.7 Vim ........................................................................................................ xxiii

1.3.8 Spyder .................................................................................................... xxiv

1.4 Python Syntax ................................................................................................ xxvi

1.4.1 Execute Python Syntax .......................................................................... xxvi

1.4.2 Python Indentation ................................................................................. xxvi

1.5 Terminology: Interpreter and compiler ......................................................... xxvii

1.6 What could possibly go wrong? ................................................................... xxviii

1.7 Debugging .................................................................................................... xxviii

2 Chapter 2: Variables, expressions, and statements ................................................ xxix

2.1 Comments ...................................................................................................... xxix

2.1.1 Multiline Comments .............................................................................. xxix

2.2 Variables ......................................................................................................... xxx

2.2.1 Creating Variables .................................................................................. xxx

2.2.2 Casting .................................................................................................... xxx

2.2.3 Get the Type ........................................................................................... xxxi

2.2.4 Single or Double Quotes? ...................................................................... xxxi

2.2.5 Case-Sensitive ........................................................................................ xxxi

2.2.6 Variable Names ...................................................................................... xxxi

2.2.7 Snake Case ........................................................................................... xxxiii

2.2.8 Many Values to Multiple Variables ..................................................... xxxiii

2.2.9 One Value to Multiple Variables ......................................................... xxxiii

2.2.10 Output Variables .................................................................................. xxxiii

2.3 Statements .................................................................................................... xxxiv

2.4 Operators and operands................................................................................ xxxiv

2.4.1 Python Arithmetic Operators ................................................................ xxxv

PAGE 3
2.4.2 Python Assignment Operators .............................................................. xxxv

2.4.3 Python Comparison Operators .............................................................. xxxv

2.4.4 Python Logical Operators .................................................................... xxxvi

2.4.5 Python Identity Operators .................................................................... xxxvi

2.4.6 Python Membership Operators ............................................................ xxxvi

2.5 Asking the user for input.............................................................................. xxxvi

2.6 Exercises ..................................................................................................... xxxvii

3 Chapter 3: Conditional execution ...................................................................... xxxviii

3.1 Boolean expressions................................................................................... xxxviii

3.2 Logical operators ....................................................................................... xxxviii

3.3 Conditional execution ................................................................................ xxxviii

3.4 Alternative execution ................................................................................... xxxix

3.5 Chained conditionals .................................................................................... xxxix

3.6 Nested conditionals ............................................................................................ xl

3.7 Catching exceptions using try and except .......................................................... xl

4 Chapter 4: Functions ................................................................................................ xlii

4.1 Function call..................................................................................................... xlii

4.2 Built-in functions ............................................................................................ xliii

4.3 Creating a Function ......................................................................................... xliii

4.3.1 Calling a Function ................................................................................... xliii

4.3.2 Arguments ............................................................................................... xliii

4.3.3 Parameters or Arguments? ...................................................................... xliv

4.3.4 Number of Arguments ............................................................................ xliv

4.3.5 Arbitrary Arguments, *args ..................................................................... xlv

4.4 Why functions? ................................................................................................ xlv

PAGE 4
4.5 Exercises .......................................................................................................... xlv

5 Chapter 5: Iteration ................................................................................................ xlvii

5.1 The while Loop .............................................................................................. xlvii

5.1.1 The break Statement ............................................................................. xlviii

5.1.2 The continue Statement......................................................................... xlviii

5.1.3 The else Statement ................................................................................ xlviii

5.2 TPython For Loops ......................................................................................... xlix

5.2.1 Looping Through a String ....................................................................... xlix

5.2.2 The break Statement ............................................................................... xlix

5.2.3 The continue Statement................................................................................ l

5.2.4 Nested Loops ............................................................................................... l

5.2.5 The pass Statement ..................................................................................... li

5.3 Loop patterns ...................................................................................................... li

5.3.1 The range() Function................................................................................... li

5.3.2 Else in For Loop......................................................................................... lii

5.3.3 Counting and summing loops ................................................................... liii

5.3.4 Maximum and minimum loops ................................................................. liii

5.4 Exercises ........................................................................................................... liii

6 Python Strings ......................................................................................................... liv

6.1 Strings ............................................................................................................... liv

6.1.1 Assign String to a Variable ....................................................................... liv

6.1.2 Strings are Arrays ...................................................................................... lv

6.1.3 Traversal through a String ......................................................................... lv

6.1.4 String Length ............................................................................................. lv

6.1.5 Check String............................................................................................... lv

PAGE 5
6.1.6 Check if NOT ............................................................................................ lvi

6.2 Slicing Strings ................................................................................................... lvi

6.2.1 Slice From the Start .................................................................................. lvi

6.2.2 Slice To the End ....................................................................................... lvii

6.2.3 Negative Indexing .................................................................................... lvii

6.3 Modify strings .................................................................................................. lvii

6.3.1 Upper Case ............................................................................................... lvii

6.3.2 Lower Case .............................................................................................. lvii

6.3.3 Remove Whitespace................................................................................. lvii

6.3.4 Replace String ......................................................................................... lviii

6.3.5 Split String .............................................................................................. lviii

6.4 string concatenation ........................................................................................ lviii

6.5 String Format .................................................................................................. lviii

6.6 Escape Character ............................................................................................... lix

6.6.1 Escape Characters ..................................................................................... lix

6.7 String Methods ................................................................................................... lx

6.8 Parsing strings ................................................................................................... lxi

6.9 Format operator ................................................................................................ lxii

6.10 Exercises ......................................................................................................... lxiii

7 Chapter 7: Files ....................................................................................................... lxiii

7.1 Opening files ................................................................................................... lxiv

7.2 Text files and lines .......................................................................................... lxiv

7.3 Reading files .................................................................................................... lxv

7.4 Searching through a file ................................................................................... lxv

7.5 Letting the user choose the file name ............................................................. lxvi

PAGE 6
7.6 Using try, except, and open............................................................................. lxvi

7.7 Python File Write........................................................................................... lxvii

7.7.1 Write to an Existing File ........................................................................ lxvii

7.7.2 Create a New File.................................................................................. lxviii

8 Chapter 8: Lists ..................................................................................................... lxviii

8.1 A list is a sequence ........................................................................................ lxviii

8.2 Lists are mutable ............................................................................................. lxix

8.3 Traversing a list............................................................................................... lxix

8.4 List operations .................................................................................................. lxx

8.5 List slices ......................................................................................................... lxx

8.6 List methods .................................................................................................... lxxi

8.7 Lists and strings ............................................................................................. lxxii

8.8 Parsing lines ................................................................................................... lxxii

8.9 Exercise ......................................................................................................... lxxiii

9 Chapter 9: Dictionaries .......................................................................................... lxxv

9.1 Dictionary as a set of counters ...................................................................... lxxvi

9.2 Dictionaries and files .................................................................................... lxxvi

9.3 Exercises ...................................................................................................... lxxvii

10 Chapter 10: Tuples .................................................Error! Bookmark not defined.

PAGE 7
Course Outline
Course name: Object Oriented Programming (Python)

Course code: DIT 62102

Course level: CORE

Course credit unit: 4

Contact hours 60

Course Description

This course introduces advanced programming skills and focuses on the core concepts of
object-oriented programming and design using a high-level language python. Object-
oriented programming represents the integration of software components into a large-scale
software architecture. Software development in this way represents the next logical step
after learning coding fundamentals, allowing for the creation of sprawling programs. The
course focuses on the understanding and practical mastery of object-oriented concepts such
as classes, objects, data abstraction, methods, method overloading, inheritance and
polymorphism. Practical applications in the domain of data science and as seen in stacks,
queues, lists, and trees will be examined.
Learners will learn: how Python works and its place in the world of programming
languages; to work with and manipulate strings; to perform math operations; to work with
Python sequences; to collect user input and output results; flow control processing; to write
to, and read from, files; to write functions; to handle exception; and work with dates and
times. This Python course will be taught using Python 3.
Course Objectives
Upon successful completion of this course, a student will be able to:
1. Employ control structures, functions, and arrays to create Python programs.
2. Apply object-oriented programming concepts to develop dynamic interactive
Python applications.
3. Employ Python sequences and mappings to store and manipulate data.
4. Use SQL commands and the MySQL database together with Python.
5. Create an advanced project using MySQL, Python and a Model-View-Controller
framework.

PAGE 8
Learning outcomes
Upon successful completion of this course, a student will meet the following outcomes:
1. Employ control structures, functions, and arrays to create Python programs.
2. Apply object-oriented programming concepts to develop dynamic interactive
Python applications.
3. Employ Python sequences and mappings to store and manipulate data.
4. Use SQL commands and the MySQL database together with Python.
5. Create an advanced project using MySQL, Python and a Model-View-Controller
framework.
Detailed Course Outline

S/N Topic Sub-topic Contact


Hours

1. Understanding ➢ Words and sentences 3


programming ➢ Terminology
➢ Writing a program
➢ Debugging

2. Variables, Values and types 6


expressions, and Variables
statements Statements
Operators and operands
Expressions
Order of operations
Modulus operator.
String operations
Asking the user for input
Comments

3. Conditional • Logical expressions 6


execution • Boolean expressions
• Conditional execution
• Alternative

PAGE 9
• Chained
• Nested conditionals
• Catching exceptions using try and
except

4. Functions • Function calls 3


• Built-in functions
• Adding new functions
• Parameters and
• Fruitful functions and void functions

5. Iteration • The while statement 6


• Infinite loops
• Finishing iterations with continue
• Definite loops using for

6. Strings Getting the length of a string 6


• String slices
• Looping and counting
• The in operator
• String comparison
• String methods

7. Files ➢ Opening files 6


➢ Reading files
➢ Searching through a file
➢ Using try, except, and open
➢ Writing files

8. Lists • Traversing a list 3


• List operations

PAGE 10
• List slices
• List methods

9. Dictionaries • Dictionary as a set of counters 6


• Dictionaries and files
• Looping and dictionaries
• Advanced text parsing

10. Object-oriented Using objects 9


programming Starting with programs
Classes as types
Constructors and destructors
Multiple instances
Inheritance and polymorphism
Abstraction and Data hiding
Exception and Exception hiding

11. Using Databases and ➢ What is a database? 6


SQL ➢ Database concepts
➢ Structured Query Language summary
➢ Basic data modeling
➢ Programming with multiple tables

TOTAL CONTACT HOURS 60

Teaching/ Study aids and tools:


i. Computer
ii. Hand Outs
iii. Projector
iv. White Board and Markers
v. Learning Management System
Mode of Delivery:
The course will be delivered by:
i. Open Distance e-Learning (Blended Approach)
ii. Lecture Methods/Practical sessions

PAGE 11
iii. Case studies and class discussions.

Mode of Assessment
NO ACTIVITY SCORE
1 Coursework 50 %
2 End of semester examination 50 %
Total 100 %

Reading list
1. Charles R. Severance (2015) Python for Everybody Exploring Data Using Python:
Creative Commons Attribution-NonCommercial
2. Pilgrim M, Willison S. 2009.Dive Into Python 3. Vol. 2. Springer;
3. Hunt J (2014) Python in CS1, Journal of Computing Sciences in Colleges, 30:2,
(237-239), Online publication date: 1-Dec-2014. Cookbook, P., Essentials, P.,
Programming, F. and Edition, P., 2016. A Brief History of Python | PACKT Books.
[online] Packtpub.com. Available at:
<https://www.packtpub.com/books/content/brief-history-python> [Accessed 30
January 2016].

PAGE 12
1 Introduction
1.1 OVER VIEW OF OBJECT-ORIENTED PROGRAMMING

1.1.1 What is Object-Oriented Programming (OOP)?


Object-Oriented Programming (OOP) is a programming paradigm that structures programs
around objects and classes, enabling modular, reusable, and scalable software
development.

1.1.2 Key Features of OOP:


• Encapsulation – Restricting direct access to certain details of an object.
• Abstraction – Hiding complex implementation and exposing only necessary
details.
• Inheritance – Allowing new classes to inherit properties from existing ones.
• Polymorphism – Enabling objects of different classes to be treated similarly.

1.1.3 Classes and Objects


• Classes define the blueprint or template for creating objects.
• Objects are instances of a class, representing real-world entities with properties
(attributes) and behaviors (methods).
Example:
• A Car class can have attributes like brand and model and methods like start() or
stop().
• A Student class can have attributes like name and age and methods like study().

1.1.4 Encapsulation
Encapsulation helps in:
• Bundling related data and methods together in a class.
• Preventing direct modification of sensitive data.
• Using getter and setter methods to control access.
Example:
• A BankAccount class can have a private balance that can only be modified through
deposit and withdrawal methods.

PAGE 13
1.1.5 Inheritance
Inheritance allows a class (child) to derive properties and behaviors from another class
(parent), promoting code reuse.
Types of inheritance:
• Single Inheritance – One class inherits from another.
• Multiple Inheritance – A class inherits from multiple classes.
• Multilevel Inheritance – A class inherits from a class that already inherited from
another.
Example:
• A Dog class can inherit attributes from an Animal class.

1.1.6 Polymorphism
Polymorphism allows different classes to use the same interface, making code more
flexible and dynamic.
Types:
• Method Overriding – A child class modifies a method from its parent class.
• Method Overloading (not native in Python) – Using the same method name with
different parameters.
Example:
• A Bird and Dog class can both have a speak() method, but each produces a different
sound.

1.1.7 Abstraction
Abstraction simplifies complex systems by exposing only relevant details and hiding
implementation logic.
• Achieved using abstract classes and methods.
• Encourages separation between implementation and usage.
Example:
• A Vehicle class might define a general "startengine()" method, but the actual
implementation differs for a car or a bike.

PAGE 14
1.1.8 Importance of OOP
• Code Reusability – Inheritance allows reuse of existing code.
• Modularity – Code is organized into logical units.
• Maintainability – Easier to update and modify programs.
• Scalability – Facilitates growth and extension of software applications.

1.2 WHAT IS PYTHON?


Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
• web development (server-side),
• software development,
• mathematics,
• System scripting.

1.2.1 What can Python do?


• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
• Python can be used for rapid prototyping, or for production-ready software
development.

1.2.2 Why Python?


• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon
as it is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a functional
way.
Good to know

PAGE 15
• The most recent major version of Python is Python 3 during the course. However,
Python 2, although not being updated with anything other than security updates, is
still quite popular.

1.2.3 Python Syntax compared to other programming languages


• Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as the scope
of loops, functions and classes. Other programming languages often use curly-
brackets for this purpose.
Example
print("Hello, World!")

1.2.4 Python Install


If you find that you do not have Python installed on your computer, then you can download
it for free from the following website: https://www.python.org/

1.2.5 Python Quickstart


Python is an interpreted programming language; this means that as a developer you write
Python (.py) files in a text editor and then put those files into the python interpreter to be
executed.
The way to run a python file is like this on the command line:
C:\Users\Your Name>python helloworld.py
Where "helloworld.py" is the name of your python file.
Let's write our first Python file, called helloworld.py, which can be done in any text editor.
helloworld.py
print("Hello, World!")
Simple as that. Save your file. Open your command line, navigate to the directory where
you saved your file, and run:
C:\Users\Your Name>python helloworld.py
The output should read:

PAGE 16
Hello, World!
Congratulations, you have written and executed your first Python program.

1.2.6 The Python Command Line

To test a short amount of code in python sometimes it is quickest and easiest not to write
the code in a file. This is made possible because Python can be run as a command line
itself.

Type the following on the Windows, Mac or Linux command line:

C:\Users\Your Name>python
Or, if the "python" command did not work, you can try "py":
C:\Users\Your Name>py

From there you can write any python, including our hello world example from earlier in
the tutorial:

C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")

Which will write "Hello, World!" in the command line:

C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
Hello, World!

Whenever you are done in the python command line, you can simply type the following to
quit the python command line interface:

exit()

PAGE 17
1.3 PYTHON IDES AND CODE EDITORS
Here we are learning about Python IDEs and code editors for beginners and professionals.

1.3.1 IDLE

For: Beginner Pricing: Free


When you install Python, IDLE is also installed by default. This makes it easy to get started
in Python. Its major features include the Python shell window (interactive interpreter),
auto-completion, syntax highlighting, smart indentation, and a basic integrated debugger.
IDLE is a decent IDE for learning as it's lightweight and simple to use. However, it's not
for optimum for larger projects.

1.3.2 Sublime Text 3


For: Beginner, Professional Pricing: Freemium
Sublime Text is a popular code editor that supports many languages including Python. It's
fast, highly customizable and has a huge community.

PAGE 18
It has basic built-in support for Python when you install it. However, you can install
packages such as debugging, auto-completion, code linting, etc. There are also various
packages for scientific development, Django, Flask and so on. Basically, you can
customize Sublime text to create a full-fledged Python development environment as per
your need.
You can download and use evaluate Sublime text for an indefinite period of time. However,
you will occasionally get a pop-up stating "you need to purchase a license for continued
use".

Learn more:
• Download Sublime text ----- https://www.sublimetext.com/3
• Setting up Python for Sublime text --
https://www.youtube.com/watch?v=xFciV6Ew5r4

1.3.3 Atom
For: Beginner, Professional Pricing: Free

PAGE 19
Atom is an open-source code editor developed by Github that can be used for Python
development (similar Sublime text).
Its features are also similar to Sublime Text. Atom is highly customizable. You can install
packages as per your need. Some of the commonly used packages in Atom for Python
development are autocomplete-python, linter-flake8, python-debugger, etc.

Learn more:
Download Atom ----https://atom.io/
Setting up Python for Atom--
https://www.youtube.com/watch?v=DjEuROpsvp4&t=633s

1.3.4 Thonny
For: Beginner Pricing: Free
• Thonny is a Python dedicated IDE that comes with Python 3 built-in. Once you
install it, you can start writing Python code.

PAGE 20
• Thonny is intended for beginners. The user interface is kept simple so that
beginners will find it easy to get started.
• Though Thonny is intended for beginners, it has several useful features that also
make it a good IDE for full-fledged Python development. Some of its features are
syntax error highlighting, debugger, code completion, step through expression
evaluation, etc.

Learn more: Thonny Official site -----https://thonny.org/

1.3.5 PyCharm
For: Professional Pricing: Freemium
PyCharm is an IDE for professional developers. It is created by JetBrains, a company
known for creating great software development tools.
There are two versions of PyCharm:

PAGE 21
• Community - free open-source version, lightweight, good for Python and scientific
development
• Professional - paid version, full-featured IDE with support for Web development as
well
PyCharm provides all major features that a good IDE should provide: code completion,
code inspections, error-highlighting and fixes, debugging, version control system and code
refactoring. All these features come out of the box.
PyCharm is resource-intensive. If you have a computer with a small amount of RAM
(usually less than 4 GB), your computer may lag.

Learn more:
• PyCharm Download ------https://www.jetbrains.com/pycharm/download
• PyCharm Features ----------https://www.jetbrains.com/pycharm/features/

1.3.6 Visual Studio Code


For: Professional Pricing: Free

PAGE 22
Visual Studio Code (VS Code) is a free and open-source IDE created by Microsoft that can
be used for Python development.
You can add extensions to create a Python development environment as per your need in
VS code. It provides features such as intelligent code completion, hinting for potential
errors, debugging, unit testing and so on.
VS Code is lightweight and packed with powerful features. This is the reason why it
becoming popular among Python developers.

Learn more:
• Download VS Code ---https://code.visualstudio.com/download
• Python in Visual Studio Code----https://code.visualstudio.com/docs/languages/python

1.3.7 Vim
For: Professional Pricing: Free
Vim is a text editor pre-installed in macOS and UNIX systems. For Windows, you need to
download it.

PAGE 23
Some developers absolutely adore Vim, its keyboard shortcuts, and extendibility whereas,
some just hate it.
If you already know how to use Vim, it can be a good tool for Python development. If not,
you need to invest time learning Vim and its commands before you can use it for Python.
You can add plugins for syntax highlighting, code completion, debugging, refactoring, etc.
to Vim and use it as a Python IDE.

Learn more: Vim for Python development -----https://stackabuse.com/vim-for-python-


development/

1.3.8 Spyder
For: Beginner, Professional Pricing: Free
Spyder is an open-source IDE usually used for scientific development.
The easiest way to get up and running up with Spyder is by installing Anaconda
distribution. If you don't know, Anaconda is a popular distribution for data science and
machine learning. The Anaconda distribution includes hundreds of packages including
NumPy, Pandas, scikit-learn, matplotlib and so on.

PAGE 24
Spyder has some great features such as autocompletion, debugging and iPython shell.
However, it lacks in features compared to PyCharm.

Learn more: Spyder Official site ---https://www.spyder-ide.org/

Honorable Mentions
• Jupyter Notebook - open-source software that allows you to create and share live
code, visualizations, etc.
• Eclipse + PyDev - Eclipse is a popular IDE that can be used for Python
development using PyDev plugin.
• Google Colab- Colab is a hosted Jupyter Notebook service that requires no setup
to use and provides free access to computing resources, including GPUs and TPUs.
For this course we shall mainly use Google Colab and few demonstrations in IDLE

PAGE 25
1.4 PYTHON SYNTAX
1.4.1 Execute Python Syntax

Python syntax can be executed by writing directly in the Command Line:

>>> print("Hello, World!")


Hello, World!

Or by creating a python file on the server, using the .py file extension, and running it in the
Command Line:

C:\Users\Your Name>python myfile.py

1.4.2 Python Indentation

Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.

Python uses indentation to indicate a block of code.

Example
if 5 > 2:
print("Five is greater than two!")

Python will give you an error if you skip the indentation:

Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")

The number of spaces is up to you as a programmer, the most common use is four, but it
has to be at least one.

Example
if 5 > 2:
print("Five is greater than two!")

PAGE 26
if 5 > 2:
print("Five is greater than two!")

You have to use the same number of spaces in the same block of code, otherwise Python
will give you an error:

Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")

1.5 TERMINOLOGY: INTERPRETER AND COMPILER


• Python is a high-level language and other high-level languages include Java, C++,
PHP, Ruby, Basic, Perl, JavaScript, and many more.
• The actual hardware inside the Central Processing Unit (CPU) does not understand
any of these high-level languages.
• The CPU understands a language we call machine language.
• Machine language is very simple and frankly very tiresome to write because it is
represented all in zeros and ones: 001010001110100100101010000001111
11100110000011101010010101101101 ...
• Translators allow programmers to write in high-level languages like Python or
JavaScript and these translators convert the programs to machine language for
actual execution by the CPU.
• These programming language translators fall into two general categories: (1)
interpreters and (2) compilers.
• An interpreter reads the source code of the program as written by the programmer,
parses the source code, and interprets the instructions on the fly. Python is an
interpreter and when we are running Python interactively, we can type a line of
Python (a sentence) and Python processes it immediately and is ready for us to type
another line of Python.
• A compiler needs to be handed the entire program in a file, and then it runs a
process to translate the high-level source code into machine language and then the

PAGE 27
compiler puts the resulting machine language into a file for later execution. If you
have a Windows system, often these executable machine language programs have
a suffix of “.exe” or “.dll” which stand for “executable” and “dynamic link library”
respectively.

1.6 WHAT COULD POSSIBLY GO WRONG?


As your programs become increasingly sophisticated, you will encounter three general
types of errors:
Syntax errors: A syntax error means that you have violated the “grammar” rules of
Python.
Logic errors: A logic error is when your program has good syntax but there is a mistake
in the order of the statements or perhaps a mistake in how the statements relate to one
another.
Semantic errors: A semantic error is when your description of the steps to take is
syntactically perfect and in the right order, but there is simply a mistake in the program.
The program is perfectly correct but it does not do what you intended for it to do.

1.7 DEBUGGING
Debugging is the process of finding the cause of the error in your code. When you are
debugging a program, and especially if you are working on a hard bug, there are four things
to try:
Reading: Examine your code, read it back to yourself, and check that it says what you
meant to say.
Running: Experiment by making changes and running different versions.
Ruminating: Take some time to think! What kind of error is it: syntax, runtime, semantic?
What information can you get from the error messages, or from the output of the program?
What kind of error could cause the problem you’re seeing? What did you change last,
before the problem appeared?
Retreating: At some point, the best thing to do is back off, undoing recent changes, until
you get back to a program that works and that you understand. Then you can start
rebuilding.

PAGE 28
2 Chapter 2: Variables, expressions, and
statements
2.1 COMMENTS
Python has commenting capability for the purpose of in-code documentation.
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Comments start with a #, and Python will render the rest of the line as a comment:
Example
#This is a comment.
print("Hello, World!")
Comments can be placed at the end of a line, and Python will ignore the rest of the line:
Example
print("Hello, World!") #This is a comment
A comment does not have to be text that explains the code, it can also be used to prevent
Python from executing code:
Example
#print("Hello, World!")
print("Cheers, Mate!")

2.1.1 Multiline Comments


Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a # for each line:
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Or, not quite as intended, you can use a multiline string.
Since Python will ignore string literals that are not assigned to a variable, you can add a
multiline string (triple quotes) in your code, and place your comment inside it:

PAGE 29
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the code, but then ignore
it, and you have made a multiline comment.

2.2 VARIABLES

Variables are containers for storing data values.

2.2.1 Creating Variables


Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example
x = 5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type
after they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)

2.2.2 Casting
If you want to specify the data type of a variable, this can be done with casting.
Example

PAGE 30
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0

2.2.3 Get the Type


You can get the data type of a variable with the type() function.
Example
x = 5
y = "John"
print(type(x))
print(type(y))

2.2.4 Single or Double Quotes?


String variables can be declared either by using single or double quotes:
Example
x = "John"
# is the same as
x = 'John'

2.2.5 Case-Sensitive

Variable names are case-sensitive.

Example
This will create two variables:
a = 4
A = "Sally"
#A will not overwrite a

2.2.6 Variable Names


• A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume). Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number

PAGE 31
• A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• Phython key words should not be used as variable names
Python reserves 35 keywords:

Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"

2.2.6.1 Multi Words Variable Names


Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
2.2.6.2 Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"

PAGE 32
2.2.6.3 Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"

2.2.7 Snake Case

Each word is separated by an underscore character:

my_variable_name = "John"

2.2.8 Many Values to Multiple Variables


Python allows you to assign values to multiple variables in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

Note: Make sure the number of variables matches the number of values,
or else you will get an error.

2.2.9 One Value to Multiple Variables


And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)

2.2.10 Output Variables


The Python print() function is often used to output variables.
Example
x = "Python is awesome"
print(x)
In the print() function, you output multiple variables, separated by a comma:
Example

PAGE 33
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
You can also use the + operator to output multiple variables:
Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

2.3 STATEMENTS
A statement is a unit of code that the Python interpreter can execute. We have seen two
kinds of statements: print being an expression statement and assignment. When you type a
statement in interactive mode, the interpreter executes it and displays the result, if there is
one.
A script usually contains a sequence of statements. If there is more than one statement, the
results appear one at a time as the statements execute

2.4 OPERATORS AND OPERANDS


Operators are special symbols that represent computations like addition and
multiplication. The values the operator is applied to are called operands.

Python divides the operators in the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators

PAGE 34
2.4.1 Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y

2.4.2 Python Assignment Operators


Assignment operators are used to assign values to variables:
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

2.4.3 Python Comparison Operators


Comparison operators are used to compare two values:
Operator Name Example

PAGE 35
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y

<= Less than or equal to x <= y

2.4.4 Python Logical Operators


Logical operators are used to combine conditional statements:
Operator Description Example
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

2.4.5 Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Operator Description Example
is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y

2.4.6 Python Membership Operators


Membership operators are used to test if a sequence is presented in an object:
Operator Description Example
in Returns True if a sequence with the specified value x in y
is present in the object
not in Returns True if a sequence with the specified value x not in y
is not present in the object

2.5 ASKING THE USER FOR INPUT


Sometimes we would like to take the value for a variable from the user via their keyboard.
Python provides a built-in function called input that gets input from the keyboard. When
this function is called, the program stops and waits for the user to type something. When

PAGE 36
the user presses Return or Enter, the program resumes and input returns what the user typed
as a string.
>>> inp = input()
My name is constance
>>> print(inp)
My name is constance

Before getting input from the user, it is a good idea to print a prompt telling the user what
to input. You can pass a string to input to be displayed to the user before pausing for input:

The sequence \n at the end of the prompt represents a newline, which is a special character
that causes a line break.

2.6 EXERCISES
Exercise 1: Write a program that uses input to prompt a user for their name and then
welcomes them.
Enter your name:
Connie
Hello Connie
Exercise 2: Write a program to prompt the user for hours and rate per hour to compute
gross pay.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
We won’t worry about making sure our pay has exactly two digits after the decimal place
for now. If you want, you can play with the built-in Python round function to properly
round the resulting pay to two decimal places.
Exercise 4: Write a program which prompts the user for a Celsius temperature, convert the
temperature to Fahrenheit, and print out the converted temperature.

PAGE 37
3 Chapter 3: Conditional execution
3.1 BOOLEAN EXPRESSIONS
A Boolean expression is an expression that is either true or false. The following
examples use the operator = =, which compares two operands and produces True if
they are equal and False otherwise:

True and False are special values that belong to the class bool; they are not strings:

The == operator is one of the comparison operators

3.2 LOGICAL OPERATORS


There are three logical operators: and, or, and not. The semantics (meaning) of these
operators is similar to their meaning in English. For example,
• x > 0 and x < 10
• is true only if x is greater than 0 and less than 10.
• n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is, if the
number is divisible by 2 or 3.
Finally, the not operator negates a boolean expression, so not (x > y) is true if
x > y is false; that is, if x is less than or equal to y.

3.3 CONDITIONAL EXECUTION


In order to write useful programs, we almost always need the ability to check conditions
and change the behavior of the program accordingly. Conditional statements give us this
ability. The simplest form is the if statement:
if x > 0 :

PAGE 38
print('x is positive')
The boolean expression after the if statement is called the condition. We end the if
statement with a colon character (:) and the line(s) after the if statement are indented.

If the logical condition is true, then the indented statement gets executed. If the logical
condition is false, the indented statement is skipped.

When using the Python interpreter, you must leave a blank line at the end of a block,
otherwise Python will return an error

3.4 ALTERNATIVE EXECUTION


A second form of the if statement is alternative execution, in which there are two
possibilities and the condition determines which one gets executed. The syntax looks like
this:

3.5 CHAINED CONDITIONALS


Sometimes there are more than two possibilities and we need more than two branches. One
way to express a computation like that is a chained conditional:

PAGE 39
elif is an abbreviation of “else if.”

3.6 NESTED CONDITIONALS


One conditional can also be nested within another. We could have written the three-branch
example like this:

outer conditional contains two branches. The first branch contains a simple statement. The
second branch contains another if statement, which has two branches of its own.

3.7 CATCHING EXCEPTIONS USING TRY AND EXCEPT


Earlier we saw a code segment where we used the input and int functions to read and parse
an integer number entered by the user. Here is a sample program to convert a Fahrenheit
temperature to a Celsius temperature:

inp = input('Enter Fahrenheit Temperature: ')


fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
If we execute this code and give it invalid input, it simply fails with an unfriendly error
message

PAGE 40
The idea of try and except is that you know that some sequence of instruction(s) may have
a problem and you want to add some statements to be executed if an error occurs.
inp = input('Enter Fahrenheit Temperature:')
try:
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
except:
print('Please enter a number')

Exercises
Exercise 1: Rewrite your pay computation to give the employee 1.5 times the hourly rate
for hours worked above 40 hours.
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
Exercise 2: Rewrite your pay program using try and except so that your program handles
non-numeric input gracefully by printing a message and exiting the program. The following
shows two executions of the program:
Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input
Enter Hours: forty
Error, please enter numeric input
Exercise 3: Write a program to prompt for a score between 0.0 and 1.0. If the score is out
of range, print an error message. If the score is between 0.0 and 1.0, print a grade using the
following table:
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D

PAGE 41
< 0.6 F
Enter score: 0.95
A
Enter score: perfect
Bad score
Enter score: 10.0
Bad score
Enter score: 0.75
C
Enter score: 0.5
F
Run the program repeatedly as shown above to test the various different values for input

4 Chapter 4: Functions
4.1 FUNCTION CALL
• In the context of programming, a function is a named sequence of statements that
performs a computation.
• When you define a function, you specify the name and the sequence of statements.
Later, you can “call” the function by name. We have already seen one example of
a function call:
>>> type(32)
<class 'int'>
• The name of the function is type. The expression in parentheses is called the
argument of the function.
• The argument is a value or variable that we are passing into the function as input to
the function. The result, for the type function, is the type of the argument.
• It is common to say that a function “takes” an argument and “returns” a result.
The result is called the return value.

PAGE 42
4.2 BUILT-IN FUNCTIONS
Python provides a number of important built-in functions that we can use without needing
to provide the function definition.
The max and min functions give us the largest and smallest values in a list, respectively:
>>> max('Hello world')
'w'
>>> min('Hello world')
''
The len function tells us how many items are in its argument. If the argument to len is a
string, it returns the number of characters in the string.
>>> len('Hello world')
11

4.3 CREATING A FUNCTION


In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")

4.3.1 Calling a Function


To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function()

4.3.2 Arguments
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside the parentheses. You can
add as many arguments as you want, just separate them with a comma.
• The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function to
print the full name:

PAGE 43
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Arguments are often shortened to args in Python documentations.

4.3.3 Parameters or Arguments?

The terms parameter and argument can be used for the same thing:
information that are passed into a function.

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function


definition.

An argument is the value that is sent to the function when it is called.

4.3.4 Number of Arguments


By default, a function must be called with the correct number of arguments. Meaning that
if your function expects 2 arguments, you have to call the function with 2 arguments, not
more, and not less.
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)

my_function("Emil", "Refsnes")
If you try to call the function with 1 or 3 arguments, you will get an error:
This function expects 2 arguments, but gets only 1:
def my_function(fname, lname):
print(fname + " " + lname)

PAGE 44
my_function("Emil")
Error:
Traceback (most recent call last):
File "demo_function_args_error.py", line 4, in <module>
my_function("Emil")
TypeError: my_function() missing 1 required positional
argument: 'lname'

4.3.5 Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your function, add
a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items
accordingly:
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

4.4 WHY FUNCTIONS?


It may not be clear why it is worth the trouble to divide a program into functions.
There are several reasons:
✓ Creating a new function gives you an opportunity to name a group of
statements, which makes your program easier to read, understand, and debug.
✓ Functions can make a program smaller by eliminating repetitive code. Later, if
you make a change, you only have to make it in one place.
✓ Dividing a long program into functions allows you to debug the parts one at
✓ a time and then assemble them into a working whole.
✓ Well-designed functions are often useful for many programs. Once you write
and debug one, you can reuse it

4.5 EXERCISES
Exercise 1: What is the purpose of the “def” keyword in Python?

PAGE 45
a) It is slang that means “the following code is really cool”
b) It indicates the start of a function
c) It indicates that the following indented section of code is to be stored for later
d) b and c are both true
e) None of the above
Exercise 2: What will the following Python program print out?
def fred():
print("Zap")
def jane():
print("ABC")
jane()
fred()
jane()
a) Zap ABC jane fred jane
b) Zap ABC Zap
c) ABC Zap jane
d) ABC Zap ABC
e) Zap Zap Zap
Exercise 3: Rewrite your pay computation with time-and-a-half for overtime and create a
function called computepay which takes two parameters
(hours and rate).
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
Exercise 4: Rewrite the grade program from the previous chapter using
a function called computegrade that takes a score as its parameter and
returns a grade as a string.
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D

PAGE 46
< 0.6 F
Enter score: 0.95
A
Enter score: perfect
Bad score
Enter score: 10.0
Bad score
Enter score: 0.75
C
Enter score: 0.5
F
Run the program repeatedly to test the various different values for input

5 Chapter 5: Iteration
Python has two primitive loop commands:

• while loops
• for loops

5.1 THE WHILE LOOP


With the while loop we can execute a set of statements as long as a condition is true.

Print i as long as i is less than 6:

i = 1
while i < 6:
print(i)
i += 1

Note: remember to increment i, or else the loop will continue forever.

PAGE 47
5.1.1 The break Statement

With the break statement we can stop the loop even if the while condition
is true:

Exit the loop when i is 3:

i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1

5.1.2 The continue Statement

With the continue statement we can stop the current iteration, and
continue with the next:

Continue to the next iteration if i is 3:

i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)

5.1.3 The else Statement

With the else statement we can run a block of code once when the
condition no longer is true:

Print a message once the condition is false:

i = 1
while i < 6:
print(i)
i += 1

PAGE 48
else:
print("i is no longer less than 6")

5.2 TPYTHON FOR LOOPS


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary,
a set, or a string).
This is less like the for keyword in other programming languages, and works more like
an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.

Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

The for loop does not require an indexing variable to set beforehand.

5.2.1 Looping Through a String

Even strings are iterable objects, they contain a sequence of characters:

Loop through the letters in the word "banana":

for x in "banana":
print(x)

5.2.2 The break Statement

With the break statement we can stop the loop before it has looped through
all the items:

Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:

PAGE 49
print(x)
if x == "banana":
break

Exit the loop when x is "banana", but this time the break comes before the
print:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
break
print(x)

5.2.3 The continue Statement

With the continue statement we can stop the current iteration of the loop,
and continue with the next:

Do not print banana:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)

5.2.4 Nested Loops

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer
loop":

Print each adjective for every fruit:

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

PAGE 50
for x in adj:
for y in fruits:
print(x, y)

5.2.5 The pass Statement


for loops cannot be empty, but if you for some reason have a for loop with no content,
put in the pass statement to avoid getting an error.
for x in [0, 1, 2]:
pass

5.3 LOOP PATTERNS


Often we use a for or while loop to go through a list of items or the contents of a file and
we are looking for something such as the largest or smallest value of the data we scan
through.
These loops are generally constructed by:
• Initializing one or more variables before the loop starts
• Performing some computation on each item in the loop body, possibly changing the
variables in the body of the loop
• Looking at the resulting variables when the loop completes
We will use a list of numbers to demonstrate the concepts and construction of these

5.3.1 The range() Function


To loop through a set of code a specified number of times, we can use
the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.

Using the range() function:

for x in range(6):
print(x)
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

PAGE 51
The range() function defaults to 0 as a starting value, however it is possible to specify
the starting value by adding a parameter: range(2, 6), which means values from 2 to 6
(but not including 6):

Using the start parameter:

for x in range(2, 6):


print(x)
The range() function defaults to increment the sequence by 1, however it is possible to
specify the increment value by adding a third parameter: range(2, 30, 3):

Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):


print(x)

5.3.2 Else in For Loop


The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:

Print all numbers from 0 to 5, and print a message when the loop has
ended:

for x in range(6):
print(x)
else:
print("Finally finished!")

Note: The else block will NOT be executed if the loop is stopped by
a break statement.

Break the loop when x is 3, and see what happens with the else block:

for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")

PAGE 52
5.3.3 Counting and summing loops
For example, to count the number of items in a list, we would write the following for loop:

Another similar loop that computes the total of a set of numbers is as follows:

5.3.4 Maximum and minimum loops


To find the largest value in a list or sequence, we construct the following loop:
Code Output

To compute the smallest number, the code is very similar with one small change:
Code Output

5.4 EXERCISES
Exercises

PAGE 53
Exercise 1: Write a program which repeatedly reads numbers until the user enters “done”.
Once “done” is entered, print out the total, count, and average of the numbers. If the user
enters anything other than a number, detect their mistake using try and except and print an
error message and skip to the next number.
Enter a number: 4
Enter a number: 5
Enter a number: bad data
Invalid input
Enter a number: 7
Enter a number: done
16 3 5.333333333333333
Exercise 2: Write another program that prompts for a list of numbers as above and at the
end prints out both the maximum and minimum of the numbers instead of the average

6 Python Strings
6.1 STRINGS
Strings in python are surrounded by either single quotation marks, or double quotation
marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:


print("Hello")
print('Hello')

6.1.1 Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an equal sign
and the string:
a = "Hello"
print(a)

PAGE 54
6.1.2 Strings are Arrays
A string is a sequence of characters. You can access the characters one at a time with the
bracket operator:
>>> fruit = 'banana'
>>> letter = fruit[1]

6.1.3 Traversal through a String


A lot of computations involve processing a string one character at a time. Often they start
at the beginning, select each character in turn, do something to it, and continue until the
end. This pattern of processing is called a traversal. One way to write a traversal is with a
while loop:

Since strings are arrays, we can loop through the characters in a string, with a for loop.

Loop through the letters in the word "banana":

for x in "banana":
print(x)

6.1.4 String Length


To get the length of a string, use the len() function. a = "Hello, World!"
The len() function returns the length of a string: print(len(a))

6.1.5 Check String


To check if a certain phrase or character is present in a string, we can use the keyword in.
Check if "free" is present in the following text:

PAGE 55
txt = "The best things in life are free!"
print("free" in txt)
Use it in an if statement:
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")

6.1.6 Check if NOT


To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.
Check if "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print("expensive" not in txt)
Use it in an if statement:
print only if "expensive" is NOT present:
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")

6.2 SLICING STRINGS


You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Note: The first character has index 0.

6.2.1 Slice From the Start


By leaving out the start index, the range will start at the first character:
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])

PAGE 56
6.2.2 Slice To the End
By leaving out the end index, the range will go to the end:
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])

6.2.3 Negative Indexing


Use negative indexes to start the slice from the end of the string:
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2])

6.3 MODIFY STRINGS


Python has a set of built-in methods that you can use on strings.

6.3.1 Upper Case


The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())

6.3.2 Lower Case


The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())

6.3.3 Remove Whitespace


Whitespace is the space before and/or after the actual text, and very often you want to
remove this space.
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

PAGE 57
6.3.4 Replace String
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))

6.3.5 Split String


The split() method returns a list where the text between the specified separator becomes
the list items.
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

6.4 STRING CONCATENATION


To concatenate, or combine, two strings you can use the + operator.
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)

6.5 STRING FORMAT


As we learned in the Python Variables chapter, we cannot combine strings and numbers
like this:
age = 36
txt = "My name is John, I am " + age
print(txt)
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places them in the
string where the placeholders {} are:
Use the format() method to insert numbers into strings:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

PAGE 58
The format() method takes unlimited number of arguments, and are placed into the
respective placeholders:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

6.6 ESCAPE CHARACTER


To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by
double quotes:
You will get an error if you use double quotes inside a string that is surrounded by double
quotes:
txt = "We are the so-called "Vikings" from the north."

To fix this problem, use the escape character \":

The escape character allows you to use double quotes when you normally would not be
allowed:
txt = "We are the so-called \"Vikings\" from the north."

6.6.1 Escape Characters

Other escape characters used in Python:

Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace

PAGE 59
\f Form Feed
\ooo Octal value
\xhh Hex value

6.7 STRING METHODS


Python has a set of built-in methods that you can use on strings.
Note: All string methods return new values. They do not change the original string.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of
where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of
where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title

PAGE 60
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified
value
rfind() Searches the string for a specified value and returns the last
position of where it was found
rindex() Searches the string for a specified value and returns the last
position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning

6.8 PARSING STRINGS


Often, we want to look into a string and find a substring. For example if we were presented
a series of lines formatted as follows:

PAGE 61
From [email protected] Sat Jan 5 09:14:16 2008
and we wanted to pull out only the second half of the address (i.e., uct.ac.za) from each
line, we can do this by using the find method and string slicing.
First, we will find the position of the at-sign in the string. Then we will find the position of
the first space after the at-sign. And then we will use string slicing to extract the portion of
the string which we are looking for.

We use a version of the find method which allows us to specify a position in the string
where we want find to start looking. When we slice, we extract the characters from “one
beyond the at-sign through up to but not including the space character”.

6.9 FORMAT OPERATOR


The format operator, % allows us to construct strings, replacing parts of the strings with
the data stored in variables. When applied to integers, % is the modulus operator. But when
the first operand is a string, % is the format operator.
The first operand is the format string, which contains one or more format sequences that
specify how the second operand is formatted. The result is a string
For example, the format sequence %d means that the second operand should be
formatted as an integer (“d” stands for “decimal”):
>>> camels = 42
>>> '%d' % camels
'42'
The result is the string ‘42’, which is not to be confused with the integer value 42

PAGE 62
6.10 EXERCISES
Exercise 1: Write a while loop that starts at the last character in the string and works its
way backwards to the first character in the string, printing each letter on a separate line,
except backwards.
Exercise 2: Given that fruit is a string, what does fruit[:] mean?
Exercise 3: There is a string method called count . Read the documentation of this method
at: https://docs.python.org/library/stdtypes.html#string-methods
Write an invocation that counts the number of times the letter a occurs in “banana”.

7 Chapter 7: Files
We have learned how to write programs and communicate our intentions to the Central
Processing Unit using conditional execution, functions, and iterations. We have learned
how to create and use data structures in the Main Memory. So up to now, our programs
have just been transient fun exercises to learn Python.

In this chapter, we start to work with Secondary Memory (or files). Secondary memory is
not erased when the power is turned off. Or in the case of a USB flash drive, the data we

PAGE 63
write from our programs can be removed from the system and transported to another
system.
We will primarily focus on reading and writing text files such as those we create in a text
editor. Later we will see how to work with database files which are binary files, specifically
designed to be read and written through database software.

7.1 OPENING FILES


When we want to read or write a file (say on your hard drive), we first must open the file.
Opening the file communicates with your operating system, which knows where the data
for each file is stored.
In this example, we open the file mbox.txt, which should be stored in the same folder that
you are in when you start Python. You can download this file from
www.py4e.com/code3/mbox.txt or Access it from the Folder - Python_Working_Files in
your course files

7.2 TEXT FILES AND LINES


A text file can be thought of as a sequence of lines, much like a Python string can be thought
of as a sequence of characters. For example, this is a sample of a text file which records
mail activity from various individuals in an open source project development team:

The entire file of mail interactions is available from www.py4e.com/code3/mbox.txt


and a shortened version of the file is available from www.py4e.com/code3/mbox-short.txt
or Access them from the Folder - Python_Working_Files in in your course files

PAGE 64
So when we look at the lines in a file, we need to imagine that there is a special invisible
character called the newline at the end of each line that marks the end of the line. So the
newline character separates the characters in the file into lines.

7.3 READING FILES


While the file handle does not contain the data for the file, it is quite easy to construct a for
loop to read through and count each of the lines in a file:
fhand = open('mbox-short.txt')
count = 0
for line in fhand:
count = count + 1
print('Line Count:', count)

We can use the file handle as the sequence in our for loop. Our for loop simply counts the
number of lines in the file and prints them out.
If you know the file is relatively small compared to the size of your main memory, you can
read the whole file into one string using the read method on the file handle.

This form of the open function should only be used if the file data will fit comfortably in
the main memory of your computer.

7.4 SEARCHING THROUGH A FILE

It is a very common pattern to read through a file, ignoring most of the lines and only
processing lines which meet a particular condition.
We can combine the pattern for reading a file with string methods to build simple search
mechanisms.
For example, to read a file and only print out lines which started with the prefix “From:”,
we could use the string method startswith to select only those lines with the desired prefix:

PAGE 65
fhand = open('mbox-short.txt')
for line in fhand:
if line.startswith('From:'):
print(line)

The output looks great since the only lines we are seeing are those which start with
“From:”, but why are we seeing the extra blank lines? This is due to that invisible newline
character
The rstrip method which strips whitespaces from the right side of a string as follows hence
removing extra lines:

fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if line.startswith('From:'):
print(line)

7.5 LETTING THE USER CHOOSE THE FILE NAME


We really do not want to have to edit our Python code every time we want to process a
different file. It would be more usable to ask the user to enter the file name string each time
the program runs so they can use our program on different files without changing the
Python code. This is quite simple to do by reading the file name from the user using input
as follows:

fname = input('Enter the file name: ')


fhand = open(fname)
count = 0
for line in fhand:
if line.startswith('Subject:'):
count = count + 1
print('There were', count, 'subject lines in', fname)

7.6 USING TRY, EXCEPT, AND OPEN


In case a user inputs a wrong file name in the above program, the program will throw an
exception and crash.
So now that we see the flaw in the program, we can elegantly fix it using the try/except
structure. We need to assume that the open call might fail and add recovery code when the
open fails as follows:

PAGE 66
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
count = 0
for line in fhand:
if line.startswith('Subject:'):
count = count + 1
print('There were', count, 'subject lines in', fname)

7.7 PYTHON FILE WRITE


7.7.1 Write to an Existing File

To write to an existing file, you must add a parameter to


the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Open the file "demofile2.txt" and append content to the file:


f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())
Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the overwriting:

PAGE 67
f = open("demofile3.txt", "r")
print(f.read())

Note: the "w" method will overwrite the entire file.

7.7.2 Create a New File


To create a new file in Python, use the open() method, with one of the following
parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Result: a new empty file is created!
Create a new file if it does not exist:
f = open("myfile.txt", "w")

8 Chapter 8: Lists
8.1 A LIST IS A SEQUENCE

Like a string, a list is a sequence of values. In a string, the values are characters; in a list,
they can be any type. The values in list are called elements or sometimes items.
There are several ways to create a new list; the simplest is to enclose the elements in square
brackets (“[" and “]”):
[10, 20, 30, 40]
['crunchy frog', 'ram bladder', 'lark vomit']
The first example is a list of four integers. The second is a list of three strings.
The elements of a list don’t have to be the same type.
The following list contains a string, a float, an integer, and (lo!) another list:

PAGE 68
['spam', 2.0, 5, [10, 20]]
A list within another list is nested.
A list that contains no elements is called an empty list; you can create one with
empty brackets, [].
As you might expect, you can assign list values to variables:

8.2 LISTS ARE MUTABLE


The syntax for accessing the elements of a list is the same as for accessing the characters
of a string: the bracket operator. The expression inside the brackets specifies the index.
Remember that the indices start at 0:
>>> print(cheeses[0])
Cheddar
Unlike strings, lists are mutable because you can change the order of items in a list or
reassign an item in a list.
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print(numbers)
[17, 5]
List indices work the same way as string indices
The in operator also works on lists.
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False

8.3 TRAVERSING A LIST


The most common way to traverse the elements of a list is with a for loop. The syntax is
the same as for strings:

PAGE 69
for cheese in cheeses:
print(cheese)

If you want to write or update the elements, you need the indices. A common way to do
that is to combine the functions range and len:
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
This loop traverses the list and updates each element. len returns the number of
elements in the list. range returns a list of indices from 0 to n − 1, where n is
the length of the list.

8.4 LIST OPERATIONS


The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6]
Similarly, the * operator repeats a list a given number of times:
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The first example repeats four times. The second example repeats the list three times.

8.5 LIST SLICES


The slice operator also works on lists:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c', 'd']
>>> t[3:]

PAGE 70
['d', 'e', 'f']
If you omit the first index, the slice starts at the beginning. If you omit the second, the slice
goes to the end. So if you omit both, the slice is a copy of the whole list.
>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']

A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print(t)
['a', 'x', 'y', 'd', 'e', 'f']

8.6 LIST METHODS


Python provides methods that operate on lists. For example, 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']
>>> t1.extend(t2)
>>> print(t1)
['a', 'b', 'c', 'd', 'e']
sort arranges the elements of the list from low to high
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print(t)
['a', 'b', 'c', 'd', 'e']

PAGE 71
8.7 LISTS AND STRINGS
A string is a sequence of characters and a list is a sequence of values, but a list of characters
is not the same as a string. To convert from a string to a list of characters, you can use list:
>>> s = 'spam'
>>> t = list(s)
>>> print(t)
['s', 'p', 'a', 'm']
The list function breaks a string into individual letters. If you want to break a string into
words, you can use the split method:
>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print(t)
['pining', 'for', 'the', 'fjords']
>>> print(t[2])
The
You can call split with an optional argument called a delimiter that specifies which
characters to use as word boundaries. The following example uses a hyphen as a delimiter:
>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter)
['spam', 'spam', 'spam']

join is the inverse of split. It takes a list of strings and concatenates the elements. join is a
string method, so you have to invoke it on the delimiter and pass the list
as a parameter:
>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> delimiter.join(t)
'pining for the fjords'

8.8 PARSING LINES


Usually when we are reading a file we want to do something to the lines other than just
printing the whole line. Often we want to find the “interesting lines” and then parse the line
to find some interesting part of the line. What if we wanted to printout the day of the week
from those lines that start with “From”?
From [email protected] Sat Jan 5 09:14:16 2008

PAGE 72
The split method is very effective when faced with this kind of problem. We can write a
small program that looks for lines where the line starts with “From”, split those lines, and
then print out the third word in the line:
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
count = 0
for line in fhand:
if line.startswith('Subject:'):
count = count + 1
print('There were', count, 'subject lines in', fname)

8.9 EXERCISE
Exercise 1: Find all unique words in a file Shakespeare used over 20,000 words in his
works. But how would you determine that? How would you produce the list of all the words
that Shakespeare used? Would you download all his work, read it and track all unique
words by hand?
Let’s use Python to achieve that instead. List all unique words, sorted in alphabetical order,
that are stored in a file romeo.txt containing a subset of Shakespeare’s work.
To get started, download a copy of the file www.py4e.com/code3/romeo.txt.
Create a list of unique words, which will contain the final result. Write a program to open
the file romeo.txt and read it line by line. For each line, split the line into a list of words
using the split function. For each word, check to see if the word is already in the list of
unique words. If the word is not in the list of unique words, add it to the list. When the
program completes, sort and print the list of unique words in alphabetical order
Enter file: romeo.txt
['Arise', 'But', 'It', 'Juliet', 'Who', 'already',
'and', 'breaks', 'east', 'envious', 'fair', 'grief',
'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft',
'sun', 'the', 'through', 'what', 'window',

PAGE 73
'with', 'yonder']

Exercise 5: Minimalist Email Client.


MBOX (mail box) is a popular file format to store and share a collection of emails. This
was used by early email servers and desktop apps.
Without getting into too many details, MBOX is a text file, which stores emails
consecutively. Emails are separated by a special line which starts with From (notice the
space). Importantly, lines starting with
From: (notice the colon) describes the email itself and does not act as a separator. Imagine
you wrote a minimalist email app, that lists the email of the senders in the user’s Inbox and
counts the number of emails.
Write a program to read through the mail box data and when you findline that starts with
“From”, you will split the line into words using the split function. We are interested in who
sent the message, which is the second word on the From line.

From [email protected] Sat Jan 5 09:14:16 2008

You will parse the From line and print out the second word for each From line, then you
will also count the number of From (not From:) lines and print out a count at the end. This
is a good sample output with a few lines removed:
python fromcount.py
Enter a file name: mbox-short.txt
[email protected]
[email protected]
[email protected]
[...some output removed...]
[email protected]
[email protected]
[email protected]
[email protected]
There were 27 lines in the file with From as the first word

PAGE 74
Exercise 6: Rewrite the program that prompts the user for a list of numbers and prints out
the maximum and minimum of the numbers at the end when the user enters “done”. Write
the program to store the numbers the user enters in a list and use the max() and min()
functions to compute the maximum and minimum numbers after the loop completes.
Enter a number: 6
Enter a number: 2
Enter a number: 9
Enter a number: 3
Enter a number: 5
Enter a number: done
Maximum: 9.0
Minimum: 2.0

9 Chapter 9: Dictionaries
A dictionary is like a list, but more general. In a list, the index positions have to be integers;
in a dictionary, the indices can be (almost) any type.
It is a mapping between a set of indices (keys) and a set of values to form a key-value pair
(item)
lug=dict()
lug['emu']='one'
print(lug)
or
lug={'emu':'one','biri':'two','saatu':'three'}
print(lug)
output:
{'emu': 'one', 'biri': 'two', 'saatu': 'three'}
The len function works on dictionaries; it returns the number of key-value pairs:

len(lug)

The in operator works on dictionaries; it tells you whether something appears as a key in
the dictionary (appearing as a value is not good enough).
>>> 'emu'in lug

PAGE 75
True
>>> 'nnya' in lug
False
>>>

To see whether something appears as a value in a dictionary, you can use the method
values, which returns the values as a type that can be converted to a list, and then use the
in operator:

>>> vals=list(lug.values())
>>> 'emu' in vals
False

9.1 DICTIONARY AS A SET OF COUNTERS


Suppose you are given a string and you want to count how many times each letter appears.
There are several ways you could do it:
word = 'brontosaurus'
d = dict()
for c in word:
if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
print(d)

9.2 DICTIONARIES AND FILES


One of the common uses of a dictionary is to count the occurrence of words in a file with
some written text.

We will write a Python program to read through the lines of the file, break each line into a
list of words, and then loop through each of the words in the line and count each word
using a dictionary. You will see that we have two for loops. The outer loop is reading the
lines of the file and the inner loop is iterating through each of the words on that particular
line.
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()

counts = dict()
for line in fhand:

PAGE 76
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1

print(counts)

9.3 EXERCISES
Exercise 1: Download a copy of the file www.py4e.com/code3/words.txt Write a program
that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter
what the values are. Then you can use the in operator as a fast way to check whether a
string is in the dictionary.

Exercise 2: Write a program that categorizes each mail message by which day of the week
the commit was done. To do this look for lines that start with “From”, then look for the
third word and keep a running count of each of the days of the week. At the end of the
program print out the contents of your dictionary (order does not matter).
Sample Line:
From [email protected] Sat Jan 5 09:14:16 2008 Sample
Execution: python dow.py Enter a file name: mbox-short.txt {'Fri':
20, 'Thu': 6, 'Sat': 1}

Exercise 3: Write a program to read through a mail log, build a histogram using a
dictionary to count how many messages have come from each email address, and print the
dictionary.

PAGE 77
10 Chapter 10: Object Oriented Programming
This chapter and the rest of the remaining chapters will be shared independently

PAGE 78

You might also like