Python
Python
(Python)
DIT 6202
March 2025
Contents
1 Introduction .............................................................................................................. xiii
PAGE 2
1.3.7 Vim ........................................................................................................ xxiii
PAGE 3
2.4.2 Python Assignment Operators .............................................................. xxxv
PAGE 4
4.5 Exercises .......................................................................................................... xlv
PAGE 5
6.1.6 Check if NOT ............................................................................................ lvi
7.5 Letting the user choose the file name ............................................................. lxvi
PAGE 6
7.6 Using try, except, and open............................................................................. lxvi
PAGE 7
Course Outline
Course name: Object Oriented Programming (Python)
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
PAGE 9
• Chained
• Nested conditionals
• Catching exceptions using try and
except
PAGE 10
• List slices
• List methods
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.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.
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.
PAGE 16
Hello, World!
Congratulations, you have written and executed your first Python program.
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.
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!")
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
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.
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/
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.
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.
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
Or by creating a python file on the server, using the .py file extension, and running it in the
Command Line:
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
Example
if 5 > 2:
print("Five is greater than two!")
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!")
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.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!")
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
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.5 Case-Sensitive
Example
This will create two variables:
a = 4
A = "Sally"
#A will not overwrite a
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"
PAGE 32
2.2.6.3 Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"
my_variable_name = "John"
Note: Make sure the number of variables matches the number of values,
or else you will get an error.
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
• 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
PAGE 35
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
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:
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
PAGE 39
elif is an abbreviation of “else if.”
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.
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.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")
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
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.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
i = 1
while i < 6:
print(i)
i += 1
PAGE 47
5.1.1 The break Statement
With the break statement we can stop the loop even if the while condition
is true:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
With the continue statement we can stop the current iteration, and
continue with the next:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
With the else statement we can run a block of code once when the
condition no longer is true:
i = 1
while i < 6:
print(i)
i += 1
PAGE 48
else:
print("i is no longer less than 6")
The for loop does not require an indexing variable to set beforehand.
for x in "banana":
print(x)
With the break statement we can stop the loop before it has looped through
all the items:
PAGE 49
print(x)
if x == "banana":
break
Exit the loop when x is "banana", but this time the break comes before the
print:
With the continue statement we can stop the current iteration of the loop,
and continue with the next:
The "inner loop" will be executed one time for each iteration of the "outer
loop":
PAGE 50
for x in adj:
for y in fruits:
print(x, y)
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):
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:
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.
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]
Since strings are arrays, we can loop through the characters in a string, with a for loop.
for x in "banana":
print(x)
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.")
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:])
PAGE 57
6.3.4 Replace String
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
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))
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."
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
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
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”.
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.
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.
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.
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)
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)
PAGE 67
f = open("demofile3.txt", "r")
print(f.read())
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:
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.
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']
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'
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']
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
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