Joe Thompson-Python Python's Companion, A Step by Step Guide For Beginners To Start Coding Today!-Amazon Digital Services LLC (2016)
Joe Thompson-Python Python's Companion, A Step by Step Guide For Beginners To Start Coding Today!-Amazon Digital Services LLC (2016)
Joe Thompson-Python Python's Companion, A Step by Step Guide For Beginners To Start Coding Today!-Amazon Digital Services LLC (2016)
Companion
Joe Thompson’s Books
Copyright
©2016 Joe Thompson - All rights reserved.
This document is geared towards providing exact and reliable information in regards to the
topic and issue covered. The publication is sold with the idea that the publisher is not
required to render accounting, officially permitted, or otherwise, qualified services. If
advice is necessary, legal or professional, a practiced individual in the profession should
be ordered.
- From a Declaration of Principles which was accepted and approved equally by a
Committee of the American Bar Association and a Committee of Publishers and
Associations.
In no way is it legal to reproduce, duplicate, or transmit any part of this document in either
electronic means or in a printed format. Recording of this publication is strictly prohibited
and any storage of this document is not allowed unless with written permission from the
publisher. All rights reserved.
The information provided herein is stated to be truthful and consistent, in that any liability,
in terms of inattention or otherwise, by any usage or abuse of any policies, processes, or
directions contained within is the solitary and utter responsibility of the recipient reader.
Under no circumstances will any legal responsibility or blame be held against the
publisher for any reparation, damages, or monetary loss due to the information herein,
either directly or indirectly.
Respective authors own all copyrights not held by the publisher.
The information herein is offered for informational purposes solely, and is universal as so.
The presentation of the information is without contract or any type of guarantee assurance.
The trademarks that are used are without any consent, and the publication of the trademark
is without permission or backing by the trademark owner. All trademarks and brands
within this book are for clarifying purposes only and are the owned by the owners
themselves, not affiliated with this document.
Disclaimer
Although the author has made every effort to ensure that the information in this book was
correct at press time, the author do not assume and hereby disclaim any liability to any
part for any loss, damage, or disruption caused by errors or omissions, whether such errors
or omissions result from negligence, accident or any other cause.
Introduction
I want to thank you and congratulate you for downloading the book, “Python’s
Companion”.
This book contains proven steps and strategies to help beginners learn Python
Programming quickly and easily. It is designed to be a practical, step-by-step tutorial of
essential Python programming concepts for self-learners from beginner to intermediate
level.
It uses a straightforward approach that focuses on imparting the important ideas without
the heavy programming jargon. Python, after all, is a language with simple and easy-to-
learn syntax.
The book features various Python programs as examples as well as a concise explanation
of the different aspects of Python Programming. By the time you finish the book, you will
be equipped with the necessary skills to create useful and practical codes on your own.
IMPORTANT
Although we have made this book as easy as possible to use, you might find yourself stuck
at some point. When programming, you might, for example, get the “Error” message and
not know what to do. The last Chapter focuses on helping you solve these issues. Do not
hesitate to use it and NEVER give up!
If you happened to like my book please leave me a quick review on Amazon. I personally
read every single comment on the site. Your feedback is very important to me as it will
help improve the book and ensure your satisfaction.
Thanks again for downloading this book. I hope you enjoy it!
An Overview of Python
Python was developed by Guido van Rossum at the National Research Institute in the
Netherlands in the late 80s. Its first version was officially released in 1991. He derived its
core syntax from the ABC language, borrowed heavily from C, and borrowed partly from
other languages such as C++, Modula-3, Unix shell, SmallTalk, and Algol-68.
Python is a high-level, object-oriented, interactive, interpreted, and general-purpose
programming language.
A high level scripting language, Python codes are designed to be highly readable. Its
programs are written in nearly regular English and are neatly indented. It uses English
keywords, concise codes, and simple syntax.
It is a multi-paradigm programming language that supports structured, functional, aspect-
oriented, and object-oriented programming methods.
Python is an object-oriented programming language. It emphasizes the use of objects over
functions in contrast with languages that are procedure-oriented. It supports user-defined
classes, inheritance, multiple inheritance, and methods binding at runtime.
Python is interactive. You can write your program directly on the Python prompt and
generate immediate feedback. You can use the prompt to test bits of codes.
Python is both a compiled and interpreted language. Python is an interpreted language
because it has to convert codes into machine-readable byte codes before it can run them. It
is also a compiled language because behind the scenes, Python is implemented with a
combination of an interpreter and bytecode compiler. It performs the compilation
implicitly as it loads the modules. In addition, some standard processes require the
availability of the compiler at runtime.
Python is a powerful and flexible language. You can use it to automate and simplify
complicated tasks at work or at home. You can develop large web applications, GUIs, and
interesting games with it.
One of the main reasons for Python’s popularity is its extensive standard library which
contains more than a hundred modules. Users can access these modules easily with a
simple import statement. The most commonly used ones include network programming,
internet protocols such as HTTP, SMTP, and FTP, mathematical functions, random
functions, regular expression matching, operating systems, threads, networking
programming, GUI toolkit, HTML parsing, XML processing, and email handling.
Although it borrows heavily from C, Python differs in two major areas with C: the use of
indentation to structure blocks of codes and the use of dynamic typing.
In C, statements are grouped with the use of curly braces and a trailing semicolon. In
Python, statements are organized into a block with the use of indentation.
In C, variables are declared and assigned a specific type before they can be used in a
program. In Python, variables are just names that point to objects stored in memory. They
need not be declared before they are assigned. They can be reassigned and they can
change types anywhere in the program.
Other features that contribute to its popularity are its support for garbage collection and
easy integration with other languages such as C, C++, Java, CORBA, ActiveX, and COM.
Because of its readability and the use of plain English in most of its construction, Python
is an easy-to-learn language for many people. While some background in programming is
desirable, you don’t need it to learn Python. The language is so easy to learn that many
experts recommend Python to students and beginners who are learning to program for the
first time. Python is, in fact, for those who are new to programming who want to make
powerful and useful programs within a short span of time.
This book is organized as a step-by-step material to learning Python. Each step is designed
to build the required skills to progress to the more advanced topics in its study.
Step 1: Installing Python
https://www.python.org/downloads/
On the landing page, you will be asked to select the version you want to download. There
are TWO HIGHLIGHTED VERSIONS:
If you’re looking for an older release, scroll further down the page to find links to other versions.
PLEASE NOTE
This book uses version 3.5.2 of Python.
https://www.python.org/downloads/mac-osx/
Starting Python
IDLE is the integrated environment that you can use to write and run your programs in.
Both IDLE and command line interface is installed when you install Python.
Figure 1. Once you install Python into your computer both IDLE and command line
interface are installed.
You may also go to the folder containing the shortcut or the installed files and click on the
Python command line.
If you’re using GNU/Linux, UNIX, and Mac OS systems
You have to run the Terminal Tool and enter the Python command to start your session.
Step 2: Working with IDLE
IDLE, an integrated development environment (IDE), was created for use with Python. It
is bundled with and installed alongside the Python interpreter. IDLE offers a simple
graphical user interface with helpful features that make program development more
convenient and intuitive.
IDLE is an efficient, powerful, and flexible platform for exploring, testing, writing, and
implementing your programs in Python.
In the script mode, the interpreter runs scripts or codes saved with a .py file extension. The
script mode is also called the normal mode.
Python Shell
multiple-window text editor
auto-completion
smart indent
syntax highlighting
integrated debugger
Figure 4. Python Shell’s main menu includes: File, Edit, Shell, Debug, Options, Window
and Help.
Just to get a feel of the Python Shell and the IDLE environment, use the print() function
to instruct the interpreter to output “Hello, World!” on your monitor.
print(“Hello, World!”)
PLEASE NOTE
A prompt is a text or a symbol used to represent the system’s readiness to perform the
next command. The symbols “>>>>” means the computer is waiting for a new input.
As you press ENTER, Python reads, interprets, and outputs Hello, World! onscreen:
Now, do away with the print() statement and just type “Hello, World!” on the >>> prompt.
Watch how Python returns the string:
>>>“Hello, World!”
‘Hello, World!’
>>>
The Python Shell isn’t just a place for trying out your codes. It is a place for solving
mathematical expressions as well. Python supports basic arithmetic operators and you can
invoke them right at the >>> prompt. Just type the expression and press ENTER. Try it
out:
PLEASE NOTE
The sentences on the right with the “#”(#12 times 12, #82 divided by 4 and #3 raised to
the 3rd power), are not part of the expression. They are ways for me to better explain
Python’s expressions.
Clicking on the “New File” option (see figure 5) opens a text editor that you can use to
type, modify, save, and run your program. Your program’s output is displayed on the
Python Shell. Python’s built-in text editor is a basic one with many useful features and a
menu that almost mimics that of the Python Shell. It offers the following menu options:
Figure 6. Once you select “New File”, the menu option offers; File, Edit, Format, Options,
Window and Help.
Take note that the above menu options lack the Shell and Debug options found in
Python Shell. It has, however, the Format and Run options which are not found in the
Python Shell.
The Run menu offers options for checking and running your module. The output is
displayed on the Python Shell.
The other options, namely File, Edit, Options, Windows, and Help, offer practically the
same features that you can find on Python Shell.
Now that you’re more or less familiar with Python’s working environment, it’s time to
create your first program with IDLE. You can use another text editor, but for simplicity,
you can use Python Shell’s built-in file editor. This is where you’ll be typing your first
program. When you’re done, you can save the file in a specific directory on your hard disk
or in another storage device.
Python’s file editor is a typical text editor with basic editing and formatting options.
For this purpose, you can type the universal program “Hello, World!”
>>>print(“Hello, World!”)
>>>
Saving the File
Saving the file prepares it for further processing by Python. It also allows you to work on
your application on a piece meal basis. You can store the file for future use or editing once
it’s saved on your storage device. To save the file:
The default installation folder for saving a program is Python’s installation folder. You can
change this to your preferred file destination folder. Saving your file is important because
you can’t possibly run your code without saving it. Python programs automatically get a
.py extension in IDLE. For instance, if you save your file in Python Shell’s text editor, you
can name your program as: MyFirstProgram and Python will save it as
MyFirstProgram.py.
To run your program, click on the Run menu in the text editor. You’ll have these options:
Python Shell
Check Module
Run Module
To run your application, choose Run Module. If there are no errors, the Python Shell will
display something like this:
If there are errors, Python will display the error message on the Python Shell.
Exiting Python
To exit from IDLE’s Python Shell, you can type exit() or quit() and press enter or simply
type ctrl-d.
If you’ve chosen to access the command line in the Power Shell instead of IDLE, you can
type either exit() or quit() and press enter.
Programs and other data are saved in files for future access and use. Files are stored in
different directories and should be accessed accordingly. Python handles files and
directories with its os module. The os module contains many useful methods that will
help users create, change, or remove directories.
os.mkdir(“newdir”)
For example, if you want to create a new directory “trial”, you can use the following code:
>>>import os
PLEASE NOTE
Don’t worry if you do not understand this part yet. If you are completely new to
programming you can skip this part for now and move to Step 5. The code “import” is
used to import a module. We will later discuss how to import a module in Step 18.
>>>os.mkdir(“trial”)
>>>
os.chdir(“newdir”)
For example, if you’re current directory is Python/sciapp and you want to change to
another directory, Python/mathapp, here is how you will use os.chdir():
>>>import os
Change a directory to “/Python/mathapp”:
>>>os.chdir(“/Python/mathapp”)
>>>
Example:
>>>import os
>>>os.getcwd()
>>>
Before you can remove a directory, all contents should first be removed.
os.rmdir(‘dirname’)
Take note that the full name of the directory should be provided. If not, the interpreter will
search for the directory in the current working directory.
>>>import os
>>>os.rmdir( “/pyprog/mathapp” )
>>>
Step4: Python Basic Syntax
In order for the Python interpreter to process and execute your instructions properly, you
must write your code in the format that it can understand. In programming, syntax refers
to the set of rules that define the correct form, combination, and sequence of words and
symbols.
PLEASE NOTE
An interpreter is a program that reads and executes codes. Python is a great example of an
interpreter.
and or not
assert yield except
break continue pass
class def del
finally global nonlocal
if elif else
import lambda from
in is try
True False None
while for return
with raise as
PLEASE NOTE
All the keywords except True, False and None are in lowercase and they must be
written as it is.
Keyword are case sensitive.
Python’s Identifiers
An identifier is a name given to a variable, class, function, string, list, dictionary,
module, and other objects. In python, it helps differentiating one entity from another.
PLEASE NOTE
These entities (variable, class, function, string, list, dictionary, modules and objects) will
be later explained in this book.
Variables: Step 5
Class: Step 21
Five rules for writing identifiers
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z)
or digits (0 to 9) or an underscore (_). Here are some examples:
C
c
my_variable,
my_var9
UPPERCASE
lowercase
UPPERCASE_WITH_UNDERSCORES
lowercase_with_underscores
CamelCase or CapWords
mixedCase
For example:
1lowercase is invalide but lowercase1 is accepted.
Avoid using the letters “O” (uppercase), “l” (lowercase letter l), or “I” (uppercase letter I)
as a single letter identifier as they may cause unnecessary confusion with the numbers 0
(zero) and 1 (one) in some fonts.
An identifier may consist of several words but for better readability, use a single
underscore to separate each unit.
Examples:
my_secret_variable
my_great_function
A Class Identifier
A class identifier may be a CamelCase name, that is, a name consisting of two or more
words which all start in capital letters and are joined together without underscores or
spaces.
Examples:
MyFamousCollection
TheFabulousList
You cannot use keywords as identifier. However, you may use a trailing underscore to
distinguish the name from a keyword.
Example:
class_
The following naming conventions are specific to each object in Python. Read them and
use them as reference as you go through each lesson.
Naming Classes
Apply the UpperCaseCamelCase convention when naming a class. In general, built-in
classes are usually written in lowercase. Exception classes normally end in “Error”.
Naming Functions
A function name should consist of letters in lowercase. When using multiple words as
function name, they should be separated by underscores to enhance readability.
Naming Arguments
You should always use the word “self” as the first argument in an instance method and
“cls” as the first argument in a class method.
Naming Constants
Constants are written in all uppercase letters with underscores to separate multiple-word
names.
Examples:
TOTAL
MAX_OVERFLOW
Examples:
‘Joshua’
“occupation”
”‘age:”’
Statements
Statements are expressions that you write within a program which are, in turn, read and
executed by the Python interpreter. Python supports statements such as if statement, for
statement, while statement, break statement, and assignment statements.
Multi-line statements
Statements may sometimes be too long to fit in a single line and are thus written across
several lines. To implicitly tell Python that a multiple line expression is a single statement,
you can enclose it in braces{}, brackets[], or parentheses ().
Example #1:
Example #2:
The above structure illustrates the implicit way to let Python know that it should expect a
multiple-line statement. To explicitly indicate continuation, you can use a backslash (\) at
the end of each line:
Indentation
Python programs are structured through white spaces or indentation. Hence, if you have
been using Java, C, or C++ for a while, you’ll never see the familiar curly braces {}
around block codes. White spaces make Python programs look more organized and
readable. In Python, a block starts from the same distance to the right and ends on the first
unindented line. Starting a nested block is as easy as indenting further to the right.
By convention, programmers use four white spaces instead of tabs to indent a block of
code. While this level of indentation is not strictly imposed in Python, consistency of
indentation within the block code is required if you want your program to run as expected.
def tool_rental_fees (days):
fees = 10 * days
if days >= 7:
fees -= 10
elif days >= 3:
fees -= 5
return fees
Comments
Comments are notes written within programs to describe a step, process, or to just
basically include important information. Comments provide documentation to your work
and are useful during review or program revisit. It will make work a lot easier for you and
other programmers to evaluate the program months or years down the line. A comment is
introduced by a hash (#) symbol which tells the interpreter to ignore the line and proceed
to the next statement.
For long comments that span over several lines, you can wrap the connected lines together
with a hash (#) symbol at the beginning of each line:
Alternatively, you can use triple quotes at the start and end of a multiple-line comment.
“““This is an alternative
way of writing
multi-line comments”””
Docstring
A documentation string or docstring is used for documenting what a class or function
does. You will find a docstring summary at the top of a block of code that defines a class,
method, function, or module. Docstrings are typically phrases that start with a capital
letter and end with a period. They may span over several lines and are enclosed within
triple double quotes (”””). A docstring starts with a one-line summary which is written like
an imperative statement.
Examples:
def triple_value(num):
“““Function to get thrice the value of a number.”””
return 3*num
class Documentation(object):
”””
Step 5: Variables and Python Data Types
Variables
A variable is a reserved memory location that can be used to store values. This
means that when you create a variable you reserve some space in the memory.
Whenever you create a variable, you are allocating space in a computer’s memory, a
storage that can hold values. Variables are given distinct names to identify their memory
locations. These names are then used as a reference to instruct the computer to access,
edit, save, or retrieve stored data.
Variable creation and management is a lot more flexible and straightforward in Python
than in most other languages. You can easily create or declare a variable by using a
syntactically appropriate name and assigning a value to it using the assignment operator
(=). You need not even inform Python that you want a variable to contain a specific type
of data. Python automatically identifies the data type based on the values you assign to the
variable.
employee = “Jonathan Brown”
average_score = “80.5”
counter = “18”
comment = “That input is incorrect.”
The left operands (in grey) are the names of the variables while the right operands (in
blue) refer to the value assigned to the variable. The use of the assignment operator tells
Python that a variable is assigned to store a particular value. Hence, in the assignment
statement “average score = 80.50”, you are basically telling Python that the variable
‘average score’ is set to ‘80.50’. Python, in this case, knows that you are using the variable
‘average score’ to store a floating point number and there’s absolutely no need to declare
that this variable is going to hold a float.
Memory Location
To check the memory location of the above variables, you’ll use the id() operator.
But first, open you IDLE and type the variables and their values showed above.
>>>id(employee)
>>>id(score)
>>>id(counter)
>>>id(comment)
Once you type your assigments and press ENTER, Python will give you the memory
location:
Figure 8. Below each assignment, in blue, you can see the memory location.
x, y, z = a, b, c
IMPORTANT DEFINITIONS
Integer : These are positive or negative whole numbers (they don’t include any decimal
points). This will be discussed later in Step 6.
Float : These are real numbers and are written with a decimal point dividing the integer
and fractional parts. This will be discussed later in Step 6.
>>>name,rank,rating=“Johnston”,89.5,26
>>>
Now, use the print function to see the values stored in the above variables:
>>>print(name)
>>>print(rating)
>>>print(rank)
In the above example, the variable ‘name’ holds the string “Johnston”, while the variables
‘rating’ and ‘rank’ hold the integer 26 and the float 89.5 respectively.
Python allows the assignment of a common value to several variables in a single statement
with the syntax:
x = y = z = “apple”
The statement assigns the string “apple” to variables x, y, and z at the same time.
To check if the variables x, y, and z actually pertain to one and the same memory location,
use the id() operator:
>>>id(x)
>>> id(y)
>>>id(z)
Figure 9. In this example you can see that the 3 variables pertain to the same memory
location 63519840.
Just as easily as you have created and assigned values to a variable, you can change the
value and corresponding data type stored in it in a simple reassignment process.
To illustrate, create a variable named ‘counter’ and assign the value of 50, an integer.
>>>counter = 50
To increase the value stored in the variable by 30, enter this statement on the Python
prompt:
>>>counter += 30
To see how Python interprets your statement, use the print function to see the value stored
in the variable ‘counter’:
>>>print(counter)
80
Figure 10. Once you have typed your statements, you should get 80 as a result.
The above example showed that you can easily replace the value stored in a variable with
a single statement. The following example will demonstrate that you can also reassign a
variable to store a value with a different data type with a simple reassignment statement.
Assuming you now want the variable ‘counter’ to hold the string “upper limit”, just type
the regular assignment statement you have learned earlier:
>>>counter = “upper limit”
Now, use the print function to see how it has affected the value stored in the variable
‘counter’:
>>>print(counter)
upper limit
Data Types
Programming involves a lot of data processing work. Data types allow programming
languages to organize different kinds of data. Python has several native data types:
Every value in Python is an object with a data type. Hence, you’ll find data types like
function, module, method, file, class, and compiled code.
Boolean Data Type
There are two built-in Boolean data types: True or False. These values are used in
conditional expressions, comparisons, and in structures that require representation for
truth or falsity.
To show how Boolean data types work, create three variables that will hold Boolean
values resulting from the assigned expressions.
Use the print function to see the values stored in each variable:
>>>print(bool_a, bool_b, bool_c)
You should now get : True False False. (see figure 12 below)
Figure 12.
Step 6: Number Data Types
There are 3 numeric data types in Python 3: integers, floating point numbers, and
complex numbers. Python can tell if the number is an integer or a float by the presence or
absence of a decimal point. It recognizes a complex number by its standard form a + bJ.
Hence, it’s not necessary to declare a number as a specific type.
Integers (int)
Integers are whole numbers with no fractional parts and decimal point. They can be
positive, negative, or zero. Integers can have unlimited size in Python 3 and are only
limited by the available memory on your computer. Python supports normal integers as
well as octal, hexadecimal, and binary literals:
Normal integers
Examples:
44
4500
-32
0
96784502850283491
Examples:
>>> ol = 0O40
>>>print(ol)
32
>>>
Enter 0O40 on the Python prompt to get the same integer equivalent:
>>>0O40
32
>>>
Example:
>>>hl = 0XA0F
>>>print(hl)
2575
>>>
>>> 0XA0F
2575
>>>
Example:
>>> bl = 0b101010
>>> print(bl)
42
>>>
>>>0b101010
42
>>>
Converting Integers to their String Equivalent
With the functions oct(), hex(), and bin(), You can easily convert an integer to its string
equivalent as needed.
To illustrate, convert the integer 45 to its octal, hexadecimal, and binary literal using the
appropriate built-in functions:
>>> oct(45)
‘0o55’
>>>
Figure 13. In this example, we have converted the integer 45 into it’s octal literal
equivalent O055.
integer to hexadecimal literal
>>>hex(45)
‘0x2d’
>>>
Figure 14.In this example, we have converted the integer 45 into it’s hexadecimal literal
equivalent Ox2d.
integer to binary literal
>>>bin(45)
‘0b101101’
>>>
Figure 15. In this example, we have converted the integer 45 into it’s binary literal
equivalent Ob101101.
Examples:
0.50,
42.50
10500.40
2.5
Alternatively, floats may be expressed in scientific notation using the letter “e” to indicate
the 10th power.
>>> 3.5e5
350000.0
>>>
>>> 1.2e4
12000.0
>>>
PLEASE NOTE
The letter “E” or “E notation” is used to express very large and very small results in
scientific notation. Because exponents like 1023 cannot always be conveniently displayed,
the letter E or e is used to represent 10 to the power of. So in the example above 3.5e5
means 3.5 x 105).
Complex Numbers
Complex numbers are pairs of real and imaginary numbers. It takes the form ‘a + bJ’ or
‘a + bj’ where the left operand is a real number while the right operand is a float (b) and
an imaginary number (J). The upper or lower case letter Jj refers to the square root of -1,
an imaginary number.
Real Number(a) Float (b) and an Imaginary Number (J).
a + bJ
a + bj
Example:
>>> abc = 2 + 4j
>>> xyz = 1 - 2j
>>> abcxyz = abc + xyz
>>>print(abcxyz)
(3+2j)
>>>
PLEASE NOTE
A real number is a value that represents a quantity along a line. The real numbers include
all the rational numbers, such as the integer −3 and the fraction 2/3, and all the irrational
numbers, such as √2.
An imaginary number is a complex number that can be written as a real
number multiplied by the imaginary unit i.
Type int(x)
>>>int(97.50)
97
>>>
To convert an integer to a floating-point number
Type float(x)
>>>float(567)
567.0
>>>
To convert an integer to a complex number
Type complex(x)
>>>complex(34)
(34+0j)
>>>
To convert a float to a complex number
Type complex(x)
>>>complex(34.5)
(34.5+0j)
>>>
To convert a numeric expression (x,y) to a complex number with a real
number and imaginary number
Type complex(x,y)
>>>complex(4,7)
(4+7j)
>>>
Python has many built-in operators that programmers can use to manipulate and utilize
numeric data type.
Numbers and Arithmetic Operators
Python’s arithmetic operators allow programmers to create useful applications and
automate daily tasks. Python supports 7 arithmetic operators:
Addition +
Subtraction -
Multiplication *
Division /
Exponent **
Modulos %
Floor Division //
Addition (+)
The addition operator adds the operands on either side of the operator:
>>>20 + 14
34
>>>45.8 + 50.3
96.1
>>>2 + 3.5
5.5
>>> (2 + 3j) + (3 - 4j)
(5-1j)
Subtraction (-)
The subtraction operator subtracts the value of the right operand from the value of the left
operand:
>>>50 - 7
43
>>>75.4 - 2.50
72.9
>>> 6 - 3.4
2.6
>>> (5 + 2j) - (4 - 6j)
(1+8j)
>>>
Multiplication (*)
The multiplication operator multiplies the operands on either side of the operator:
>>>4 * 3
12
>>> 8.4 * 2.5
21.0
>>> 8 * 2.5
20.0
>>>
Division ( /)
The division operator divides the value of the left operand with the value of the right
operand:
>>> 32/8
4.0
>>> 4.5 / 1.5
3.0
>>> 27.5 / 3.2
8.59375
>>>
Take note that the division operator always returns a float by default regardless of the
data type of the operands. If you want your quotient to be in integer format, you can type
int() and enclose the mathematical expression.
For example:
>>> int(32/8)
4
>>> int(4.5/1.5)
3
>>> int(27.5/3.2)
8
>>>
You can apply the same principle to the other arithmetic operations if you want Python to
return a data type other than the default numeric type. For instance, if you need the
expression to output an integer after entering an integer*float expression which results to a
float, you can coerce Python to return an integer with int(). On the other hand, if you want
Python to return a float, you can use float() and place the expression inside the
parenthesis.
Exponent (**)
The exponent operator raises the first operand to the power indicated by the right operand:
>>> 3 ** 4
81
>>>4.5 ** 3
91.125
>>>
Modulos (%)
The modulos operator (%) returns the remainder after dividing the left operand with the
right operand.
>>> 32%7
4
>>> 16.5%4.5
3.0
>>> 4%2.5
1.5
>>>
Comparison operators evaluate the expression and return either True or False to describe
the relation of the left and right operands.
is less than <
is greater than >
is less than or equal to <=
is greater than or equal to >=
is equal to ==
is not equal to !=
Examples:
>>> 15 == 3*2*2
False
>>>4*2<=5*3+2
True
>>> 15 != 3*5
False
>>> (8*4)> 24
True
>>> 10 < (2*12)
True
>>>25 >= (60*2)
False
>>>
Assignment Operators
Assignment operators are used to assign values to variables.
= Operator
The = operator assigns the value of the right operand to the left operand.
Examples:
>>>x = 2 * 4
>>>y = 2
>>>xy = x + y
>>>a, b, c = 10, 30.5, 15
>>>a = b = c = 100
add and +=
The add and (+=) operator adds the value of the left and right operands then assigns the
sum to the left operand. It takes the format x+=a and its equivalent to the expression x =
x+a.
Examples:
>>> x = 12
>>>y = 5
>>> y+=12
>>>print(y)
17
>>>
>>> a = 7
>>> b = 0
>>> b += a
>>>print(b)
7
>>>
>>> b = 0
>>> b += 5
>>>print(b)
5
>>>
subtract and -=
The subtract and (-=) operator first subtracts the value of the right number from the left,
and then assigns the difference to the left number. It is expressed as x -= a and its
equivalent expression is x = x-a.
Examples:
>>>a = 15
>>>b = 13
>>>a -= b
>>>print(a)
2
>>> counter = 10
>>> counter -= 5
>>>print(counter)
5
>>> counter = 0
>>> counter -= 10
>>>print(counter)
-10
multiply and *=
The multiply and (*=) operator takes the product of the left and right operands and
assigns the value to the left operand. It is expressed as x*=a which is equivalent to x =
x*a.
Examples:
>>> x = 15
>>> y = 3
>>> x *= y
>>>print(x)
45
>>> multiplier = 3
>>> multiplier *= 5
>>>print(multiplier)
15
divide and /=
The divide and (/=) operator first divides the value of the left operand with the right then
assigns the result to the left operand. It is expressed with x /= a which is equivalent to the
expression x = x/a.
Examples:
>>> a = 15
>>> xyz = 45
>>> xyz /= a
>>>print(xyz)
3.0
>>> amount = 12
>>> amount /= 5
>>>print(amount)
2.4
modulos and %=
The modulos and (%=) operator initially divides the left operand with the right and then
assigns the remainder to the left operand. It is expressed as x %= a which is equivalent to
the expression x = x % a.
Examples:
>>> x = 12
>>> y = 5
>>> x %= y
>>>print(x)
2
>>> rem = 30
>>> rem %= 12
>>>print(rem)
6
The floor division and (//=) operator first performs a floor division on the left operand then
assigns the result to the left operand. It is expressed as x//=a which is equivalent to the
expression x = x//a.
Examples:
>>> a = 30
>>> b = 14
>>>a //= b
>>>print(a)
2
>>> floor = 15
>>>floor //= 4
>>>print(floor)
3
Bill Calculator
Now that you’re familiar with variables and arithmetic operators, you’re ready to create a
simple program that will help you automate the task of computing for your restaurant
bill. Assuming your total bill covers the basic meal cost, sales tax, and tip, you will need
the following information to start working on your program.
basic meal cost ?
sales tax rate 7% of basic meal cost
tip 20% of the sum of the basic meal cost and sales tax
First, you’ll have to set up the variables to store the required data.
meal = 45
sales_tax = 7/100
tip = 20/100
Since the tip is based on the combined amount of the basic meal cost and sales tax, you’ll
have to pass the total to a variable by creating a new variable or simply reassigning meal
to hold the new value. Assuming you have decided to simply reassign meal, you can use
the ‘add and’ operator to compute for the total value of the basic meal cost and sales tax.
Now that the variable meal contains the combined value of the meal and sales tax, you’re
ready to compute for the tip. You can create a new variable, bill, to store the total bill
amount.
meal = 45
sales_tax = 7/ 100
tip = 20 / 100
meal += meal * sales_tax
bill = meal + meal * tip
REMEMBER
As explained in Step 2, in order to create a program you must; open IDLE -> click File ->
New File -> copy the code for your bill calculator specified above -> go to File -> Save As
-> save the program as calculator.py or any other name you want -> click Run -> click on
Run Module.
To get the total bill amount, just type the word bill on the command prompt:
>>> bill
57.78
>>>
Figure 16. Type the word bill to get the total bill amount.
>>>abs(-4)
4
max()
Returns the largest in the given arguments. The syntax is:
max(x, y, z)
>>>print (“Maximum (50, 100, 150, 200) : “, max(50, 100, 150, 200))
Maximum (50, 100, 150, 200) : 200
>>>
min()
Returns the smallest argument. The syntax is:
min( x, y, z )
round(x[,n])
>>>round(104.987543, 2)
104.99
>>>round(99.01934567, 5)
99.01935
>>>
Math Methods
The following math methods are accessible after importing the math module.
PLEASE NOTE
Modules and how to import them will be explained later in Step 18.
To import math:
>>>import math
Math.ceil(x)
Returns the smallest integer which is not less than the given number.
Examples:
>>>import math
>>> math.ceil(98.75)
99
>>> math.ceil(154.01)
155
>>> math.ceil(math.pi)
4
>>>
Math.floor(x)
Returns the largest integer which is not greater than the given number.
Examples:
>>>import math
>>> math.floor(98.01)
98
>>> math.floor(13.99)
13
>>> math.floor(math.pi)
3
>>>
Math.fabs()
Returns the absolute value of a given number.
The fabs() method works similarly as the function abs() with some differences:
fabs() works only on integers and floats while abs() works on integer, floats, and
complex numbers
fabs() returns a float while abs() returns an integer
fabs() is imported from the math module while abs() is a built-in function
Examples:
>>>import math
>>> math.fabs(-12)
12.0
>>> math.fabs(15.0)
15.0
>>>
Math.pow()
Returns the value of xy.
Examples:
>>>import math
>>>math.pow(5, 2)
25.0
>>> math.pow(2, 3)
8.0
>>> math.pow(3, 0)
1.0
>>>
Math.sqrt()
Returns the square root of a number which is larger than zero.
>>>import math
>>> math.sqrt(16)
4.0
>>> math.sqrt(25.0)
5.0
>>>
Math.log()
Returns natural logarithm of numbers greater than zero.
>>>import math
>>> math.log(100.12)
4.6063694665635735
>>> math.log(math.pi)
1.1447298858494002
>>>
Step 7: Strings
To create a string, you must enclose it in either single or double quotes and assign it to a
variable. For example:
When you enclose a string which contains a single quote or an apostrophe inside single
quotes, you will have to escape the single quote or apostrophe by placing a backslash (\)
before it.
When you use the print function to print string_single, your output should be:
>>>print(string_single)
I don’t see a single quote.
>>>
Similarly, you will have to escape a double quote with a backslash (\) when the string is
enclosed in double quotes.
Hence, to create the string = “He said: “You have been nominated as honorary president of
the Mouse Clickers Club.””:
>>>string_two = “He said: "You have been nominated as honorary president of the Mouse
Clickers Club. "”
>>>
>>>print(string_two)
He said: “You have been nominated as honorary president of the Mouse Clickers Club. “
>>>
>>>print(string_wow)
This is how you can escape a backlash .
>>>
String Indexing
The initial character in a string takes zero as its index number and the
succeeding characters take 1, 2, 3… and so on as index numbers.
To access the string backwards, the last character takes -1 as its index.
To illustrate indexing in strings, define a variable named “string_var” and assign the string
“Python String” with the statement:
Index # 0 1 2 3 4 5 6 7 8 9 10 11 12
String P y t h o n S t r i n g
Index # -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Example #1:
To access the first character on the variable string_var (the first character of Python
String is “P”), enter the variable name “string_var” and enclose the integer zero (0) inside
the index operator or square brackets [].
>>> string_var[0]
‘P’
>>>
Figure 16. In this example, the first character of the string “Python String” is “P”. Since
the first character takes zero as it’s index number, Python gives you the letter “P” as an
answer.
Example #2:
To access the character on index 8, simply enclose 8 inside the square brackets:
>>> string_var[8]
‘t’
>>>
Figure 17. Since “t” takes 8 as it’s index number, Python gives you the letter “t” as an
answer.
Example #3:
>>> string_var[6]
‘ ‘
>>>
Figure 18. Since an empty space takes 6 as it’s index number, Python gives you ‘ ‘ (a
space) as an answer.
Example # 4:
To access the last character of the string, you can use negative indexing in which the last
character takes the -1 index.
>>>string_var[-1]
‘g’
>>>
A string is an ordered list, so you can expect that the penultimate letter takes the -2 index
and so on.
>>> string_var[-5]
‘t’
>>>
The Len() Function
There is a more sophisticated way of accessing the last character and it will prove more
useful when you’re writing more complicated programs: the len() function.
The len() function is used to determine the size of a string, that is, the number of
characters in a string.
For example, to get the size of the variable ‘string_var’, you’ll use the syntax:
>>>len(string_var)
13
>>>
Figure 19. By using the len() function, Python is able to calculate the number of characters
in your string “Python String”. Do not forget that Python calculates a space as a character.
Thus you get 13 characters.
Since the last character in the string takes an index which is one less than the size of the
string, you can access the last character by subtracting 1 from the output of the len()
function.
>>> string_var[len(string_var)-1]
‘g’
>>>
an IndexError.
Slicing Strings
You can access a range of characters in a string or create substrings using the range slice
[:] operator. To do this interactively on a random string, simply type the string within
single or double quotes and indicate two indices within square brackets. A colon is used to
separate the two indices. The slice operator will give you a string starting with S[A] and
ending with S[B-1].
Examples #1:
Index # 0 1 2 3 4 5 6 7 8 9 10 11 12
String S t r i n g S l i c e r
Index # -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Figure 20. In this example, we want to create a substring using the range of characters
from “r” to “e”.
Therefore, the command says that we are looking for a substring which includes the
characters from “r” to “e” in the “String Slicer” string. Therefore, the answer is “ring
Slice”.
Example #2:
>>>“Programmer”[3:8]
‘gramm’
>>>
Index # 0 1 2 3 4 5 6 7 8 9
String P r o g r a m m e r
Index # -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
You can also slice a string stored in a variable by performing the slicing notation on the
variable using the following statements:
Example #3:
Index # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
String P y t h o n S t a t e m e n t
Index # -16 -15 -14 -12 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Example # 4:
When slicing or creating a substring, you can drop the first number if the starting character
of the substring is the same as the initial character of the original string.
For example:
Index # 0 1 2 3 4 5 6 7
String a p p e n d i x
Index # -8 -7 -6 -5 -4 -3 -2 -1
In this example;
The starting character is “a”, as is the first letter in “appendix”.
The starting character of the substring is also “a”. Therefore, we can drop the first
number. In fact, instead of writing test_var[0:6] you can simply write test_var[:6].
Similarly, if your substring ends on the last character of the string, you can drop the
second index to tell Python that your substring ends on the final character of the original
string.
Likewise, you can concatenate strings stored in two or more variables. For example:
When you run the program (when you press enter), the output will be:
Take note that since a string is immutable, the acts of slicing and concatenating a string do
not affect the value stored in the variable.
For example, assign the string “concatenate” to the variable same_string and slice it to
return the characters from index 4 to 6:
>>>print(same_string)
concatenate
>>>
Notice how the slicing did not affect the original string at all.
Repeating a String
To repeat a string or its concatenation, you’ll use the operator *and a number. This
instructs Python to repeat the string a certain number of times.
For example, if you want to repeat the string *<>* five times, you can type the string on
the command prompt and specify the number of times it should be repeated with *5.
>>>“*<>*” *5
>>>‘*<>**<>**<>**<>**<>*’
You can store the above string in a variable and apply the * operator on the variable to
achieve the same result:
>>>sign_string = “*<>*”
>>>sign_string * 5
‘*<>**<>**<>**<>**<>*’
>>>
To illustrate, define a new variable ‘smart_var’ and use it to store the string “Europe”.
>>>smart_var = “Europe”
EUROPE
>>>print(smart_var.lower())
europe
The use of the upper() and lower() functions does not change the string stored at
smart_var. You can prove this by entering the command:
>>>print (smart_var)
Europe
Using the str() function
You may sometimes need to print non-string characters as string characters. For
example,a program may require you to print a string along with integers or other number
types. Python’s str() functionallows the non-string character to be converted to string
characters.
To illustrate, you can create a variable to store the integer 246.The variable can then be
used as parameter for the str() function.
>>>my_number = 246
>>>str(my_number)
‘246’
>>>
To print the string “My employee number is 246”, you can type the following:
>>>my_number = 246
>>> print(“My employee number is ” + str(my_number))
My employee number is 246
>>>
Python String Methods
There are several Python methods that can be used with string to support various
operations:
The replace() method
The replace() method replaces a substring within an existing string with a new substring.
Since you can’t actually change the string on account of its immutable nature, replacing
values necessitates the creation of a new string.
source_string.replace(old_substring, new_substring, [ count])
Old_substring: The existing substring in the source string you want to replace.
Count: This count is an optional parameter. This specifies the maximum number of
replacements. If not provided, the replace Python method will replace all occurrences.
Also, the replacements start from the left if the count parameter is specified.
For example:
Let say you want to replace all occurrences of the substring ‘flower’, with the substring
‘bug’:
Now let say you want to replace only the first occurrence of the substring, you can supply
a third argument, 1:
>>> a = “garden”
>>> b = “a lovely garden”
>>> a.upper()
‘GARDEN’
>>> b.upper()
‘A LOVELY GARDEN’
>>>
Lower()
>>> x = “HAPPY”
>>> y = “A HAPPY PLACE”
>>> x.lower()
‘happy’
>>> y.lower()
‘a happy place’
>>>
Swapcase()
The swapcase() method returns a view where the lowercase letters are in uppercase and
viceversa.
>>> a = ‘Garden’
>>> b = ‘A Lovely Garden’
>>> a.swapcase()
‘gARDEN’
>>> b.swapcase()
‘a lOVELY gARDEN’
>>>
Title()
The title() method returns a view where the first character of the string is capitalized
and the rest are in lowercase.
>>> x = “HAPPY”
>>> y = “A HAPPY PLACE”
>>> x.title()
‘Happy’
>>> y.title()
‘A Happy Place’
>>>
Count() method
For example:
>>> s = “It is not what you think it is but it is good enough for this purpose.”
>>> s.count(‘is’)
4
>>> s.count(‘t’)
8
>>> s.count(‘it’)
2
>>> s.count(‘not’)
1
>>>
As you can see in this example, the occurrence “is” is found 4 times in this string.
The find() method is used to search for a given character or a sequence of characters
in a string.
Example #1:
Index # 0 1 2 3 4 5 6 7
String A s t r i n g
Index # -8 -7 -6 -5 -4 -3 -2 -1
On the above example, the find() method returned ‘2’ which is the index of the first
character of the string ‘string’.
Example #2:
On the following example, find() returns ‘5’, the index of the first occurrence of the string
‘i’.
Example #3:
There are several i’s in the string and if you’re looking for the next ‘i’, you’ll have to
supply a second argument which should correspond with the index immediately following
index ‘5’ above. This tells the interpreter to start searching from the given index going
to the right. Hence:
Example #4:
The search found the second occurrence of letter ‘i’ at index 9. Besides specifying an
argument for the starting range, you can also provide an argument to indicate the end to
the search operation. You can do it backwards by applying negative indexing. For
example, if you want to find the third occurrence of the letter ‘i’, you can give the index
‘10’ as a second argument and provide an end to the search range with a third argument,
-10.
Isalpha()
The method isalpha() returns True if all characters of a non-empty string are
alphabeticand there is at least one character and False if otherwise.
>>> s = (“programs”)
>>> s.isalpha()
True
>>> print(s.isalpha())
True
>>> b = (“programming 1 and 2”)
>>> b.isalpha()
False
>>>
As you can see the first 2 strings had only alphabetic characters (only letters) whereas the
3rd string had both alphabetic and numeric (letters and numbers) characters.
Isalnum()
The method isalnum() returns True if ALL the characters of a non-empty string are
alphanumeric and False if otherwise
Example #1:
>>> b = “Programmer2”
>>> b.isalnum()
True
>>>
Example #2:
>>> a = “Programmer 1”
>>> a.isalnum()
False
>>>
As you can see, in the first example all characters are alphanumeric (characters which
include both numbers and letters). However, the second example includes letters, numbers
and a space between “programmer” and “1”. This is why Python returns False.
Isidentifier()
The isidentifier() method tests for the validity of a given string as an identifier and returns
True if valid or False if otherwise.
REMEMBER
As explained in Step 4, a Python identifier is a name used to identify a variable, function,
class, module or other object. An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores and digits (0 to 9).
Example #1:
>>> a = “program”
>>> a.isidentifier()
True
>>>
Example #2:
>>> b = “2program”
>>> b.isidentifier()
False
>>>
Example #3:
>>> c = “program_one”
>>> c.isidentifier()
True
>>>
Example # 4:
str.join(sequence)
p**r**o**g**r**a**m**m**e**r
REMEMBER
Read Step 2 to know how to run a program.
The characters in red are not part of the coding, they are simply comments. To read more
about comments go to Step 4.
Lstrip() method
The lstrip method returns a copy of a string from which all leading characters or white
spaces on the LEFT side of the string have been removed.
str.lstrip([chars])
The parameter allows you to instruct Python what character(s) should be trimmed.
Example # 1:
Take note that this does not affect or trim the original string:
>>>str
‘ this is string with too many whitespaces’
>>>
Example # 2:
If there is a leading whitespace and character that you want to remove at the same time,
Python removes the leading whitespace even if you only specify the character as a
parameter.
For example:
Rstrip() method
The rstrip() method returns a string copy of a string in which all trailing characters on the
RIGHT side of the string have been removed. By default, it strips the whitespaces at the
end of a string, but you can supply the character you want to be trimmed as a parameter.
str.rstrip([chars])
Example #1:
As you can see, Python has removed the whitespace at the end of the string. That is
because we have not provided an argument and Python striped the whitespace at the end
of the string by default.
Example #2:
Here, we have remove “g” from the end of the string. This is because I have provided the
letter “g” as the argument.
Strip([chars])
The strip() method does both lstrip() and rstrip() on a string and returns a copy of a string
in which both leading and trailing characters have been removed.
Example #1:
Example #2:
>>> y = “****I’m better off without these symbols.*****”
>>> y.strip(‘*’)
“I’m better off without these symbols.”
>>>
Rfind() method
Searches for the occurrence of a given substring
The rfind() method returns the index of a given substring’s last occurrence in the string
and returns -1 if the substring is not found. It allows a start and end index arguments to
limit the search range.
str.rfind(str, beg=0 end=len(string))
Example #1:
>>> str1 = “Programming is a skill that can be learned by anyone.”
>>>str2 = “skill”
>>> str1.rfind(str2)
17
>>>
Python tells you that the substring “skill” is found on the17th index number.
Example #2:
Example #3:
Index() method
Checks the occurrence of a given substring, returns index of the first
occurrence.
The index() method checks the occurrence of a given substring in a string and returns the
index of the first occurrence. It raises a ValueError if the substring is not found.
str.index(str2, beg=0 end=len(string))
Examples:
In this example, you’re going to instruct Python to search for the substring ‘exam’ without
range parameters. The substring occurs twice in the string but the interpreter returns only
its first occurrence:
Example #1:
Assuming you want to find the index of the next occurrence, then you’ll have to provide
a second parameter to specify the starting index of the search. In this situation, since the
initial occurrence of ‘exam’ is on index 15, you’ll have to start the search at index 16.
Example #2:
Example #3:
Example #4:
This method returns the index of a substring’s last occurrence in a given string or raises a
ValueError if the substring is not found.
str.rindex(str, beg=0 end=len(string))
Examples:
>>> str1.rfind(str2)
39
>>>
To tell Python to search the string for its second occurrence backwards, provide the
index immediately before the first occurrence as the end parameter for rfind():
Finally, to find the 3rd occurrence of the substring ‘ing’, supply 24 as the ending index:
You will get the same output if you use the find() method instead:
Zfill() method
Returns a string with leading zeroes within a specified width.
The zfill() method returns a string filled with leading zeros in the given width.
str.zfill(width)
Examples #1:
Example #2:
The method returns a right-justified string based on the given width. It allows optional
fill characters with space as default and returns the original string if the width is less than
its length. Padding is done using the specified fillchar (default is a space)
str.rjust(width[, fillchar])
Example #1:
In this example, the original string is 49 index position long. Here, we do not specify the
fillchar, therefore space is used as default.The Rjust method adds the amount of spaces
needed to get the string 70 index position long (it added 21 spaces).
Example #2:
In this example, the original string was 49 index position long. The Rjust method added
the amount of “*” needed to getthe string 70 index position long (it added 21 “*”).
Example #3:
Example #4:
However, if you specify a width that is less than the length of the string, Python simply
returns the original string:
The ljust() returns a left-justified string based on the given width. It allows optional
padding characters with space as default and returns the original string if the specified
width is less than the actual width of the string.
The syntax is:
str.ljust(width[, fillchar])
Example #1:
Example #2:
Example #3:
Python simply returns the original string if the specified width is less than the actual
length of the string:
The center() method returns a center-justified string based on a specified width. It allows
optional padding characters with space as the default filler.
str.center(width[, fillchar])
Example #1:
Example #2:
Example #3:
If you specify a width which is less than the actual length of the string, Python merely
returns the original string:
Endswith() method
Checks if the string ends in a given suffix.
The endswith() method returns True if the string’s ending matches the given suffix or
returns False if otherwise. The method allows the optional limitation of matching range
with restricting start and end indices.
str.endswith(suffix[, start[, end]])
suffix: This could be a string or could also be a tuple of suffixes to look for.
start: The slice begins from here.
end: The slice ends here.
Example #1:
Example #3:
Startswith() method
Checks if the string ends in a given suffix.
The startswith() method returns True if the string’s prefix matches the given prefix or
returns False if otherwise. The method allows the optional limitation of matching range
with restricting start and end indices.
str.startswith(suffix[, start[, end]])
suffix: This could be a string or could also be a tuple of suffixes to look for.
start: The slice begins from here.
end: The slice ends here.
Example #1:
Example #2:
Example #3:
You can use a ‘for loop’ to iterate through a string. For example, to count the number of
occurrence of the letter ‘o’ in a given string, you can create a simple loop:
count = 0
for letter in‘Python Programming’:
if(letter == ‘o’):
count += 1
print(count, “letters found”)
When you run the program, you should get this output:
2 letters found
>>>
IMPORTANT
In Step 16, we will study loops more extensively. A loop is a control structure that allows
the repetitive execution of a statement or group of statements. Loops facilitate complicated
execution paths.
Step 8: Output Formatting
Python offers many built-in functions that can be used interactively at the prompt. The
print() function is one of the functions that you will use in common, everyday
programming life. There are several formatting options that you can use with print() to
produce more readable and interesting output than values separated by space.
An output may be directed to the screen or file. You now know that you can use either
expression statements or the print() function to display output on the screen. Another way
to write values to a file is with the write() method which will be discussed later in the
book.
The following expressions demonstrate the standard usage of the print() function:
Example 1:
Example 2:
>>> x = 100
>>>print(‘The value of a is’, x )
The value of a is 100
>>>
Example 3:
>>> x = 3 * 2
>>> y = 4 * 4
>>> xy = x + y
>>>print(xy)
22
>>>
This section will show the different ways you can use the format() method to control your
output.
The first example uses curly braces {} as place holders for the values supplied as
arguments in the str.format expression.
Example #1:
By default, values are displayed in the order in which they are positioned as arguments in
the format() expression. If this is your preferred arrangement, you can tell Python to
output the default order by referencing to the values with empty curly braces in the print
parameter.
Example #2:
However, if you want the values to appear in an order that is different from their
positional arrangement, you will have to specify their index inside the curly braces.
Indexing starts from zero. Hence, the first value has index o, the second one has index 1,
and so on.
Example #1:
Index # 0 1 2
Value 50 55 100
Example #2:
Python 3.5 still supports string formatting using the sprint() style used in C programming.
Hence, you can still use the following formatting structure:
Example #3:
The first value was formatted to print an integer with a space of 8 digits (%8d) so the
output shows 4 leading spaces to match the actual 4 digits usage of the given value, 2546.
The second value was formatted to print a float with 8 digits and 2 decimal places. Since
the value given only took up 3 digits, 5 leading spaces were added to the output. In
addition, the 4 decimal places were rounded off to two.
The above print statement uses the string modulo% operator. You can translate the same
statement into Python 3’s string format method by using curly braces and positional
arguments. Here’s how your code will look like when you use the format() method
instead of the string modulo % operator.
Take note that this time, you have to supply the index of the value inside the curly braces
along with the numeric format.
You can produce the same output by using keyword parameters instead of the index:
The string format method can also be used with formatting options such as zero-padding
and data justification. Here are the options supported by Python 3:
‘<’
Left justifies the value within the specified space.
Example #1:
In the above example, you provided 35 spaces for the first value and instructed Python to
print a left-justified value within the given space.
Example #2:
Example #3:
‘>’
Right-justifies the value within the given space.
Example #1:
Example #2:
‘^’
Center-justifies the value within the given space.
Example #1:
Example #2:
‘0’
Enables padding of leading zero(s) for numbers when placed before the
width field.
The number of leading zeros to be added to the numeric value will be based on the number
of digits allocated for the numeric field and the number of digits taken up by the value
given.
Example #1:
Example #2:
‘=’
Forces sign placement before zero-padding.
Example:
Python supports sequence data types that allow operations such as indexing, slicing,
multiplying, adding, removing, and membership checking. List is one of the most
commonly-used sequences and it is a most flexible type. Basically, a list can contain any
type (string, float, integer, etc.)and number of items. It can hold one data type or a
combination of several data types. It can even hold a list as an item. A list is mutable.
Hence you can add, delete, or modify its elements.
Creating a list is as easy as defining a variable to hold an ordered series of items separated
by a comma. This time, you will use a square bracket to enclose the items.
my_list = []
You can build a list by assigning items to it using the following syntax:
Just like strings, you can access items on a list with the index operator []. The first item
has an index of zero (0). Remember to always use an integer when indexing to avoid
TypeError. Attempting to access a list element that is beyond the index range will result to
an IndexError.
Example #1:
Index # 0 1 2 3 4
String Biology English Chemistry Sociology Algebra
Example #2:
Index # 0 1 2 3 4 5 6
String B I O L O G Y
Example #3:
Example:
>>> quick_list = [“s”, “h”, “o”, “r”, “t”, “c”, “u”, “t”]
>>> quick_list[-1]
‘t’
>>> quick_list[-3]
‘c’
>>> quick_list[-7]
‘h’
String s h o r t c u t
Index # -8 -7 -6 -5 -4 -3 -2 -1
Slcing Lists
The slicing operator, the colon (:), is used to access a range of elements on lists.
REMEMBER
As explained in Step 7, the syntax for slicing a string is S[A:B-1]
S: The string you wish to use
A: The starting character of the substring you want to create
B: The ending character of the substring you want to create
Example #1:
>>> hw_list = [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
>>> hw_list[0:5]
[‘H’, ‘e’, ‘l’, ‘l’, ‘o’]
>>>
Example 2:
>>> hw_list = [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
>>> hw_list[5:]
[‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
>>>
Example #3:
>>> hw_list = [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
>>> hw_list[3:6]
[‘l’, ‘o’, ‘W’]
>>>
Example #4:
>>> hw_list = [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
>>> hw_list[:-4]
[‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’]
>>>
Example #5:
>>> hw_list = [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
>>> hw_list[:]
[‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
>>>
Adding Elements to a List
Lists are mutable and you can easily add an element or a range of elements on a list with
the append() or extend() method.
The append() method is used to add a single item while the extend() method is used to
append two or more items. Both methods are used to add items at the end of the original
list.
Append() metod
list.appendix(obj)
list.extend(seq)
Example:
For example, assuming that someone made an encoding mistake and came up with the
following list of even numbers:
To rectify the mistake in the values entered, you can change the first item on the list with:
>>> even[0] = 2
>>> even
[2, 3, 5, 7, 9, 12]
Changing the values individually will take time. You can instead specify an index range to
change several values at once:
>>> even
[2, 4, 6, 8, 10, 12]
>>>
Concatenating and Repeating Lists
It is possible to combine two lists in Python with the + operator. In addition, you can use
the *operator to repeat a list a certain number of times.
Combine two lists in Python with the + operator
Example #1:
Example #2:
Example #1:
Example #2:
list.insert(index, obj)
index: This is the Index where the object obj need to be inserted.
obj: This is the Object to be inserted into the given list.
You want to insert number 3 right after number 2 and it will take index 2. Hence, you will
have to enter this expression:
>>> numbers.insert(2,3)
>>> numbers
[1, 2, 3, 4, 8, 9, 10]
>>>
If you want the numbers list to contain a sequential list of numbers from 1 to 9, you can
insert a range of items into the empty slice of the list.
To complete the numbers list, you will have to squeeze in the numbers 5, 6, and 7.
>>>numbers[4:3] = (5, 6, 7)
The above expression makes use of the slicing operator where the first number is the
intended index(4) of the first item to be inserted and the second number is the numbers of
items (3) you want to insert.
>>>numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>
Removing or Deleting Items from a List
To remove an item from a list, you can use either the remove() or the pop() method. The
remove() method removes the specified item while the pop() method removes an item at
the specified index. To empty a list, you can use the clear() method.
The remove() method
my_list.remove(obj)
Assuming you want the list numbers to contain only integer values, you can use remove()
to remove the floats, 6.5 and 7.5, one by one.
>>>numbers.remove(6.5)
>>>numbers.remove(7.5)
>>> numbers
[1, 3, 5, 7, 9]
>>>
The pop() method
The pop() method is used to remove the item associated with the given index. If the index
is not given, it removes and returns the last element on the list.
list_name.pop(index)
To see how the pop() method works, create list called my_list:
You can easily see that there’s an odd item on my_list, the color “yellow” and it is located
on index 2. You can use the pop() method to remove this specific item:
>>> my_list.pop(2)
‘yellow’
>>>
>>> my_list
[‘apples’, ‘oranges’, ‘peach’, ‘pear’]
>>>
>>> my_list.pop()
‘pear’
>>>
The pop() method just removed and returned the last item on the list. Here’s the updated
my_list:
>>>my_list
[‘apples’, ‘oranges’, ‘peach’]
>>>
The clear() method
You may also prefer to just empty your list. You can do this with the clear() method.
Here’s the syntax:
list_name.clear()
You can also use the keyword del to delete one or more items or even the entire list.
REMEMBER
To see the list of keywords used in Python you can go back to Step 4.
Example:
>>> my_list = [“L”, “I”, “A”, “B”, “I”, “L”, “I”, “T”, “Y”]
>>>del my_list[0] #delete the first item
>>> my_list
[‘I’, ‘A’, ‘B’, ‘I’, ‘L’, ‘I’, ‘T’, ‘Y’]
>>>
del list_name[:]
Example:
>>> my_list = [“L”, “I”, “A”, “B”, “I”, “L”, “I”, “T”, “Y”]
>>>del my_list[1:6] #delete multiple items from index 1 to 6
>>> my_list
[‘L’, ‘I’, ‘T’, ‘Y’]
>>>
Yet another way to let Python know that you want to delete a range of items is by
assigning an empty list to the slice of items you want to delete.
>>> my_list
[1, 2, 3, 4, 5, 6, 7, 8]
>>>
You can delete the entire items on the list by replacing the entire range of items with an
empty space:
The sort() method is used to sort items of similar data type within the list. It sorts the items
in an ascending order.
list.sort()
Example #1:
>>> list_1.sort()
>>>print(list_1)
[0, 1, 3, 4, 6.5, 7, 9.5, 15]
>>>
Example #2:
The items in list_1 and list_2 are now arranged in ascending order. To arrange the items in
the reverse or descending order, you can use Python’s reverse method.
list.reverse()
>>>list_1.reverse()
>>>print(list_1)
[0, 15, 6.5, 3, 9.5, 4, 7, 1]
>>>list_2.reverse()
>>>print(list_2)
[‘yellow’, ‘white’, ‘red’, ‘purple’, ‘orange’, ‘green’, ‘blue’]
>>>
Take note that the sort() method is only applicable to lists containing items of similar
types. Python will flash a TypeError:unorderable types if you try to sort a mixed list of
strings and integers.
Using the count() Method on Lists
The count() method
The count() method counts of how many times an object occurs in a list.
list.count(obj)
Examples:
Membership operators can be used to test if an object is stored on a list. There are two
types of membership operators: “in” and “not in”. Python returns either True or False after
evaluating the expression.
Using the “in” and “not in” operators
>>> my_letters = [“a”, “e”, “x”, “z”, “b”, “d”, “h”, “f”]
>>> “a” in my_letters
True
>>>“v” in my_letters
False
>>> “v” not in my_letters
True
>>> “f” not in my_letters
False
>>>
Python’s built-in functions such as min(), max(), len(), and sorted() can be used with list to
obtain needed value and execute various tasks.
The following are built-in functions that are most commonly applied to lists:
Len()
Returns the number of items on a list.
Example:
Example:
Example:
Example:
Example:
PLEASE NOTE
We will later discuss tuple, set and dictionary in Step 10, 11 and 12.
To convert a string to a list
Example #1:
>>>list(“Programmer”)
[‘P’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘m’, ‘e’, ‘r’]
>>>
Example #2:
>>>string_new = (“Programmer”)
>>>list(string_new)
[‘P’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘m’, ‘e’, ‘r’]
>>>
To convert a dictionary to a list
Example #1:
Example #1:
Example #2:
List Comprehension
List comprehension is a concise way of creating a new list from an existing list. It consists
of an expression and a ‘for statement’ enclosed in square brackets. To illustrate, here is an
example of creating a list where each item is an increasing power of 3.
>>>pow3 = []
>>>for y in range(15):
pow3.append(3 ** x)
A list comprehension may have more ‘for’ or ‘if’ statements. An if statement can be used
to filter out elements for a new list.
Example #1:
Example #2:
Example #3:
A tuple is a sequence type that contains an ordered collection of objects. A tuple, unlike a
list, is immutable; you won’t be able to change its elements once it is created. A tuple can
hold items of different types and can have as many elements as you want subject to
availability of memory.
Besides being immutable, you can tell a tuple apart from a list by the use of parentheses
instead of square brackets. The use of parentheses, however, is optional. You can create a
tuple without them. A tuple can store items of different types as well as contain any
number of objects.
You can create a tuple with only one item but since this will look like a string, you’ll
have to place a comma after the item to tell Python that it is a tuple.
my_tuple5 = (“program”,)
my_tuple = ()
numbers = 5, 3, 4, 0, 9
>>> my_tuple = (‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘m’, ‘e’, ‘r’)
>>>
>>> my_tuple[0]
‘p’
>>>
>>> my_tuple = (‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘m’, ‘e’, ‘r’)
>>> my_tuple[-1]
‘r’
>>>my_tuple[-7]
‘g’
>>>
Slicing a Tuple
If you want to access several items at the same time, you will have to use the slicing
operator, the colon (:). By now, you must be very familiar with how slicing works.
To see how you can slice a range of items from a tuple, create new_tuple:
>>>new_tuple = (‘i’, ‘m’, ‘m’, ‘u’, ‘t’, ‘a’, ‘b’, ‘l’, ‘e’)
>>>
>>> new_tuple[4:7]
(‘t’, ‘a’, ‘b’)
>>>
4 is the index of the first item and 7 is the index of the first item to be excluded.
>>> new_tuple[2:]
(‘m’, ‘u’, ‘t’, ‘a’, ‘b’, ‘l’, ‘e’)
>>>
To access tuple items from the beginning to the 3rd index:
>>> new_tuple[:4]
(‘i’, ‘m’, ‘m’, ‘u’)
>>>
>>> my_tuple = (‘a’, 5, 3.5, [‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’])
>>>
Replacing a Tuple
To replace the item on index 2 of the list which is on index 3 of my_tuple:
>>>my_tuple[3][2] = ‘x’
>>>
While you may not replace or modify other data types, you can reassign a tuple to an
entirely different set of values or elements.
Reassigning a Tuple
To reassign a tuple, you can just list a different set of elements and assign it to the tuple.
To reassign new_tuple:
del tuple_name
>>>del my_tuple
Tuple Membership Test
To test if a tuple contains a specific item, you can use the membership operators ‘in’ and
‘not in’
>>> our_tuple = (‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘m’, ‘e’, ‘r’)
>>>‘g’in our_tuple
True
>>>‘l’in our_tuple
False
>>>‘e’not in our_tuple
False
>>>‘x’not in‘our_tuple’
True
>>>
mytuple.count(a)
Example:
>>> new_tuple = (“p”, “r”, “o”, “g”, “r”, “a”, “m”, “m”, “e”, “r”)
>>> new_tuple.count(‘m’)
2
>>> new_tuple.count(‘r’)
3
>>> new_tuple.count(‘x’)
0
>>>
Index(x)
Returns the index of the first element which is equal to the given element.
mytuple.index(a)
Example:
>>> new_tuple = (“p”, “r”, “o”, “g”, “r”, “a”, “m”, “m”, “e”, “r”)
>>> new_tuple.index(‘m’)
6
>>> new_tuple.index(‘r’)
1
>>> new_tuple.index(‘g’)
3
>>>
Built-in Functions with Tuples
Several built-in functions are often used with tuple to carry out specific tasks. Here are the
functions that you can use with a tuple:
Len()
Returns the number of elements on a tuple.
When a tuple holds items of purely string data type, max() evaluates the items
alphabetically and returns the last item.
Using max() on tuples with mixed data types (string and numbers) will raise a TypeError
due to the use of unorderable types.
Min()
Returns the smallest element on a tuple.
When used on a tuple that contains purely string data type min() evaluates the items
alphabetically and returns the first item.
The order of elements inside the my_tuple, however, remains the same:
>>> my_tuple
(‘dog’, ‘bird’, ‘ant’, ‘cat’, ‘elephant’)
>>>
Sum()
Returns the total of all items on a tuple.
Example #1:
>>>tuple(“Programmer”)
(‘P’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘m’, ‘e’, ‘r’)
>>>
Example #2:
Example #1:
Example #2:
Example #1:
Example #2:
I love apple
I love peach
I love pineapple
I love banana
I love orange
Except for the symbols used to enclose their elements and the fact that one is mutable and
the other is not, tuples and lists are similar in many respects. You will likely use a tuple to
hold elements which are of different data types while you will prefer a list when working
on elements of similar data types.
There are good reasons to choose tuple over a list to handle your data.
The immutable nature of tuples results in faster iteration which can help improve a
program’s performance.
Immutable tuple elements can be used as dictionary keys, something that is not possible
with a list.
Implementing unchangeable data as a tuple will ensure that it will stay write-protected.
Step 11: Sets
A set is an unordered group of unique elements. Although a set itself is mutable, its
elements must be immutable. Sets are used to carry out math operations involving sets
such as intersection, union, or symmetric difference.
Creating a Set
You can create a set by enclosing all elements in curly braces {} or by using set(), one of
Python’s built-in functions. A set can hold items of different data types such as float, tuple,
string, or integer. It cannot, however, hold a mutable element such as a dictionary, list, or
set. Sets can hold any number of items. A comma is used to separate items from each
other.
>>>set([5,4,3, 1 ])
{1, 3, 4, 5}
>>>
A set’s elements cannot have a duplicate. When you create a set, Python evaluates if there
are duplicates and drops the duplicate item.
Example #1:
>>> my_set = {‘apple’, ‘peach’, ‘grape’, ‘apple’, ‘strawberry’, ‘grape’}
>>>my_set
{‘peach’, ‘grape’, ‘apple’, ‘strawberry’}
>>>
Example #2:
>>>{1, 3, 5, 9, 1, 4, 3}
{1, 3, 4, 5, 9}
>>>
To create an empty set, you will have to use the set() function without an argument. You
cannot use empty curly braces as this is the syntax for creating an empty dictionary.
Example #1:
Example #2:
Example #3:
The remove() and discard() methods can be used to remove a specific item from a set.
The only difference between the two methods is their response to a non-existent argument.
The use of the remove() method raises an error when the item given as argument does not
exist. With discard(), the set simply remains unchanged.
Example #1:
Example #2:
Here is how Python responds when you use discard() with an item which is not foundon
the set:
The elements on the set were unchanged and no error was raised.
On the other hand, remove() will raise a Key Error if the item given as an argument is
non-existent:
The pop() method is likewise used to remove and return an item on a set. Since the set is
unordered, you cannot possibly control which item will be popped. Selection is arbitrary.
Finally, you can use the clear() method to remove all elements on a set.
You can use sets to perform various set operations. To do this, you will use different
Python operators or methods.
Set Union
A union of two sets refers to a set that contains all elements from the given sets. You can
use the | operator or the union() method to perform the operation. The result is a
combination of all elements which are returned in an ascending order.
Or
The intersection of two sets refers to the set of common elements between them. It is
performed with either the & operator or the intersection() method. Both return a set with
elements that are arranged in ascending order:
>>> x = {1, 3, 5, 7, 2, 4, 6}
>>> y = {2, 4, 5, 7, 2, 0, 9}
>>> x & y
{2, 4, 5, 7}
>>>
>>> x = {1, 3, 5, 7, 2, 4, 6}
>>> y = {2, 4, 5, 7, 2, 0, 9}
>>> x.intersection(y)
{2, 4, 5, 7}
>>> y.intersection(x)
{2, 4, 5, 7}
>>>
Set Difference
Set difference refers to a set of elements that are found in one set but not in the other set.
For instance, the difference of X and Y (X – Y) is a set of elements that can be found in X
but not in Y. Conversely, the difference of Y and X (Y – X) is a set of elements that are
found in Y but not in X. The set difference operation is performed with either the –
operator or the difference() method.
>>> x = {1, 2, 3, 5, 7, 9}
>>> y = {2, 8, 9, 5, 2, 1}
>>> x - y
{3, 7}
>>> y - x
{8}
>>>
>>> x = {1, 2, 3, 5, 7, 9}
>>> y = {2, 8, 9, 5, 2, 1}
>>> x.difference(y)
{3, 7}
>>> y.difference(x)
{8}
>>>
Set Symmetric Difference
The symmetric difference between two sets refers to the set of elements that are not
common in both sets. It is performed with either the ^ operator or the
symmetric_difference() method.
>>> a = {1, 3, 5, 4, 6, 8}
>>> b = {5, 2, 6, 1, 8, 10}
>>> a.symmetric_difference(b)
{2, 3, 4, 10}
>>> b.symmetric_difference(a)
{2, 3, 4, 10}
>>>
Set Membership Test
The membership test operators(the “in” and “not in” operators) can be used to test the
existence or non-existence of an item on a set.
For example:
>>>my_set = {1,2,3,4,5}
>>>max(my_set)
5
>>>
Using sorted() does not affect the actual order of the elements on the set:
>>> my_set
{‘violet’, ‘green’, ‘yellow’, ‘red’, ‘blue’}
>>>
Sum()
Returns the total of all items on a set.
You can iterate through every element on a set with a ‘for loop’.
A frozenset takes the characteristics of a set but has immutable elements. Once assigned,
you can no longer change its elements. A frozenset relates to a set as a tuple relates to a
list. Frozensets, unlike sets, are hashable and can thus be used as dictionary keys. Their
immutable nature does not allow the use of Python methods that add or remove items
within the frozenset.
A dictionary is used as a container for storing, managing, and retrieving data in key-value
format found in phone books, menus, or directories. Python provides a number of
operators that can be used to perform different tasks with a dictionary.
d = {}
Here we have accessed the data for they keys Name and Ranking.
In this example;
Name:Mark
Age:24
Ranking:5th
Average:89.5
dict_name[key] = b
For example, using the same dictionary above, you can add a new key-value pair, status:
regular:
>>> my_dict
{‘Name’: ‘Mark’, ‘status’: ‘regular’, ‘Ranking’: ‘5th’, ‘Age’: 24, ‘Average’: 89.5}
>>>
To modify a value stored in a dictionary key, you can assign a new value to the key using
the assignment operator. For example, you can change the value of the Ranking from 5th
to 3rd with:
>>>my_dict.pop(‘river’)
‘Danube’
>>>
For example, when you use dict.popitem() on my_dict, you’ll have no control over the
value it will remove:
>>> my_dict
{‘ocean’: ‘Pacific Ocean’, ‘river’: ‘Danube’, ‘Sea’: ‘Baltic Sea’}
>>>
>>> my_dict.clear()
>>>
>>> my_dict
{}
>>>
To delete the my_dict dictionary, you will use the del keyword:
>>>del my_dict
>>>
>>> my_dict
Traceback (most recent call last):
File “<pyshell#11>”, line 1, in <module>
my_dict
NameError: name ‘my_dict’ is not defined
>>>
The update(other) method updates a dictionary with a set of key-value pairs from another
dictionary. It merges the key value pairs of one dictionary into another and allows the
values of the other dictionary to overwrite the values of the current dictionary in situations
where a common key() exists.
For example:
The key:value pairs of dict_2 have now been merged with dict_1:
>>> dict_1
{‘Age’: 27, ‘Position’: ‘Supervisor’, ‘First Name’: ‘Chuck’, ‘Last Name’: ‘Davidson’,
‘Branch’: ‘New York’}
>>>
Take note that there is one common key between dict_1 and dict_2, the Branch. Hence, the
value of dict_2, New York, replaced the original value on dict_1, Chicago.
Since only the dict_1 dictionary was updated, the key-value pairs of dict_2 remains the
same:
>>> dict_2
{‘Position’: ‘Supervisor’, ‘Branch’: ‘New York’, ‘Last Name’: ‘Davidson’}
>>>
Item() method
Returns list of a dictionary’s key-value pairs.
dict.items()
dict.values()
dict.keys()
dict.setdefault(key, default=None)
The copy() method performs a shallow copy of a dictionary where every key-value pair is
duplicated. The method allows users to modify the dictionary copy without altering the
original file.
To illustrate, here is a series of statements showing how the copy method is used to
produce a shallow copy of the original dictionary.
A dictionary copy is a new file which is independent of the original dictionary from which
it was generated. Hence, any changes you make to the new dictionary will have no effect
at all on the original dictionary.
>>>my_dict2[“oranges”] = 50
>>>my_dict2[“apples”] = 5
>>>
>>>print(my_dict1)
>>>print(my_dict2)
>>>
Your screen will display these details:
The fromkeys() method takes a sequence of items and uses them as keys to create a new
dictionary. It allows a second argument through which you can provide a value that will be
attached to the keys on the new dictionary.
>>>print(new_dict)
{‘keyboard’: 10, ‘speaker’: 10, ‘monitor’: 10, ‘CPU’: 10, ‘mouse’: 10}
>>>
Dictionary Membership Test
You can use the membership operators ‘in’ and ‘not in’ to check whether a specific key
exists or not on the dictionary. Take note that this test is only for dictionary keys, not
values.
Examples:
for n in numbers:
print(numbers[n])
2
10
8
6
4
Using Built-in Functions with Dictionary
Python has several built-in functions that can be used with dictionary to perform various
tasks.
Lens()
Returns the number of items on a dictionary.
Example #1:
Example #2:
Operators are special symbols that indicate the implementation of a specific process. They
are used to evaluate, manipulate, assign, or perform mathematical or logical operations on
different data types. Python supports different types of operators:
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Identity Operators
Membership Operators
Bitwise Operators
Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations on numeric data
types:
Adds the value of operands on either side of the operator .
+ Addition
Example: 2 + 8 returns 10
Subtracts the right operand from the left operand.
- Subtraction
Example: 10 – 2 returns 2
Multiplies the value of the left and right operands.
* Multiplication
Example: 3 * 4 returns 12
Divides the left operand with the value of the right operand.
/ Division
Example: 20 / 5 returns 4
Performs exponential calculation.
** Exponent
Example: 2 ** 3 (two raised to the power of 3) returns 8
Returns the remainder after dividing the left operand with the value of
the right operand.
%
Modulos
Example: 13 % 3 returns 1
Divides the left operand with the right operand and returns a quotient
stripped of decimal numbers.
Floor
//
Division
Example: 13 // 3 returns 4
Assignment Operators
Assignment operators are used to assign values to variables.
Operators Function
Assigns the value of the right operand to the left operand.
=
Examples: a = “xyz” x = 130 y = [2, 3, 5, 7, 8]
Adds the left and right operands and assigns the value to the left operand,
works like x = x + a
+= add and
Examples: x += 8, adder += 4
Subtracts the right operand from the left operand and assigns the difference
to the left operand, works like x = x -8
-= subtract
and
Examples: x -= 4, counter -= 6
multiplies the left and right operands and assigns the product to the left
operand, works like x = x * 2
*= multiply
and
Examples: x *= 4, product *= 5
Divides the left operand with the value of the right operand and assigns the
result to the left operand, works like x = x / 4
/= divide
and
Examples: x /= 4, counter /= 2
Performs exponential operation on the left operand and assigns the value to
the left operand, works like x = x**2
**=
exponent
Examples: x **= 3, double **= 2
Performs floor division on the left operand and assigns the value to the left
operand, works like x = x//2
//= floor
division and
Examples: x //= 3, amount //= 2
Operators Meaning
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to
Logical Operators
There are three types of logical operators in Python:
or
and
not
x or If the first argument (x) is true, it returns True. If x is false, it evaluates the second
y argument, y, and returns the result.
x and
If x is true, it evaluates y. If y is false, it returns False. If x is false, it returns False.
y
not
It returns True if x is false and False if x is true.
x
Examples:
>>>(12>9) or (2<8)
True
>>> (12 > 28) or (5 < 7)
True
>>> (8>2) and (6>15)
False
>>> (6 ==2* 3) and ( 10 < 5 **3)
True
>>>not (3 * 5 > 4)
False
>>>not (5> 2**4)
True
>>>
Identity Operators
Identity operators are used to verify if two objects are stored in the same memory location.
Python has two identity operators:
Operators Description
Returns True if the variables on the left and right side of the
is
operator refer to the same object; returns False if otherwise.
Returns False if the variables on the left and right side of the
is not
operator refer to the same object; returns True if otherwise.
To illustrate how identity operators work, type the following expressions on the text editor
then save and run the program:
>>>x = 10
>>>y = 10
>>>a = “Programs”
>>>b = “Programs”
>>>x1 = [4, 6, 8]
>>>y1 = [4, 6, 8]
>>>z1 = [4, 5, 8]
>>>print(x is y)
>>>print(a is not b)
>>>print(x1 is y1)
>>>print(x1 is not y1)
>>>print(x1 is z1)
>>>
True
False
False
True
False
Variables x and y hold integers of the same value. They are, therefore, both identical and
equal. Hence, the ‘is’ id operator returned True.
Variables a and b contains the same string and data type and are identical. Hence, the ‘is
not’ operator returned False.
The variables x1 and y1 refer to a list. Although they have the same value, they are not
identical because the lists are mutable and are stored in different memory locations.
Hence, the use of the id operator ‘is’ returned False. Conversely, the use of the ‘is not’
operator on x1 and y1 returned True. Using the ‘is’ operator on variables x1 and z1 would
naturally result to False because not only are they mutable data types; they actually hold
different items.
Membership Operators
Python’s membership operators are used to test for the occurrence or non-occurrence of a
variable or value in a sequence which can be a string, tuple, list, or a dictionary. In the
case of a dictionary, you can only test for the occurrence of a key but not its value. There
are two types of membership operators in Python:
Operators Description
Returns True if the specified variable or value is found on a given sequence;
in
returns False if otherwise
Returns True if the specified variable or value is not found on a given
not in
sequence; returns False if otherwise.
To illustrate, type the following on the text editor and run the code:
True
False
True
True
False
False
There is a ‘p’ in my_string, so the interpreter returned True. In fact, there are two p’s. In
the second print statement, the interpreter returned false because there is no ‘membership’
substring in my_string. What you have is ‘Membership’. Remember that Python is a case-
sensitive language. There is a ‘color’ key in my_dict so Python returned True. There is a
key named ‘animal’ so it returned False when the ‘is not’ operator was used. On the last
print statement, ‘elephant’ is a value, not a key on the my_dict dictionary. Hence, the
interpreter returned False.
Bitwise Operators
In computers, a series of zeros and ones called bits represent numbers. Bitwise operators
work on operands like they are strings of binary digits. They are used to directly
manipulate bits.
Understanding the Base 2 Number System
In normal life, counting is done in base 1o. This means that for every number, each place
can contain one of ten values from zero to nine and that you carry over to the next place
when it goes higher than nine. In binary, counting is done in base two where a number
place can hold either zero or one. Like the counting pattern in base 1o, you carry over to
the next place every time the count goes over one.
For example, the numbers 0 and 1 are represented similarly in base 10 and base 2. In base
2, however, you have to carry over and add 1 to the next number place when the count
exceeds 1. Hence, in base2, number 2 is represented as ‘10’ and 3 is ‘11’. When you go on
to 4, you have to carry over to the next number place. Hence, 4 is represented as ‘1o0’ in
base 2.
In base 10, a decimal place denotes a power of ten. In base 2, each place represents a bit or
a power of two. The 1’s bit (rightmost bit) denotes ‘two to the zero power’ while the 2’s
bit (next bit) denotes ‘two to the first power’. The succeeding bits are 4, 8, 16, and so on.
In Python, numbers are written in binary format with the prefix 0b. To print an integer in
its binary format, you can use the bin() function which takes integer as argument and
returns it as a string. Once you use the bin() on a number, you can no longer work on it as
a number.
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< Bitwise left shift
>> Bitwise right shift
Examples:
>>> x = 12
>>>y = 5
>>> x & y
4
>>>bin(4)
‘0b100’
>>>
Take note that whether you use the integer or the binary format (with 0b prefix) in values
that you assign to the variables x and y, Python will return an integer when you use the
bitwise operators on the variables.
| Bitwise OR
>>> x = 12
>>>y = 5
>>>x | y
13
>>>bin(13)
‘0b1101’
>>>
^ Bitwise XOR
>>> x = 12
>>>y = 5
>>> x ^ y
9
>>>bin(9)
‘0b1001’
>>>
~ Bitwise NOT
>>> x = 12
>>>y = 5
>>> ~ x
-13
>>>bin(-13)
‘-0b1101’
>>> ~ y
-6
>>>bin(-6)
‘-0b110’
>>>
<< Bitwise left shift
>>> x = 12
>>>y = 5
>>> x << 2
48
>>>bin(48)
‘0b110000’
>>> y << 2
20
>>>bin(20)
‘0b10100’
>>>
>> Bitwise right shift
>>> x = 12
>>>y = 5
>>> x >> 2
3
>>>bin(3)
‘0b11’
>>>y >> 2
1
>>>bin(1)
‘0b1’
>>>
Precedence of Operators
Operator precedence impacts how Python evaluates expressions. For example, in
evaluating the expression x = 20 – 5 * 3, the value of 5 instead of 45 will be stored to the
variable x. This is because the multiplication operation 5 * 3 has precedence over the
subtraction operation 20 - 5. In the following table, operators are arranged in the order of
precedence from the highest to the lowest:
Description Operators
Exponentiation **
Complement, unary plus, and minus ~ + -
Multiplication, division, modulo, and floor division * / % //
addition and subtraction + -
Right and left bitwise shift >>, <<
Bitwise ‘AND’ &
Regular `OR’ and Bitwise exclusive ‘OR’ | ^
Comparison operators >, <, >=, <=
Equality operators == , !=
Assignment operators =, +=, -=, *-, /=, %= //= **=
Identity Operators is, is not
Membership operators in, not in
Logical operators OR, AND, NOT
Step 14: Built-in Functions
Python comes with several built-in functions that you can readily use to create useful
programs. You have learned some of them in earlier lessons. In this section, you will learn
the most commonly used functions.
abs() all() ascii() any()
bin() bool() bytes() bytearray()
callable() chr() compile() classmethod()
complex() delattr() dir() dict()
divmod() enumerate() exec() eval()
filter() format() float() frozenset()
global() getattr() hasattr() hash()
hex() help() __import__() id()
input() int() issubclass() isinstance()
iter() list() len() locals()
max() map() min() memoryview()
next() object() open() oct()
ord() print() pow() property()
repr() range() round() reversed()
set() slice() setattr() sorted()
str() sum() staticmethod() super()
type() tuple() vars() zip()
The range expression generates an iterator which progresses a set of integers from a given
or default starting value to an ending value.
To illustrate how this function works, type range(10) on the command line:
>>>range(10)
range(0, 10)
>>>
Since both the start and progression values were omitted, the list of numbers starts at the
default value of zero and the step is set to the default value of 1.
To see the list of numbers on the given range, you will use the expression list(range(n)).
>>>list (range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
Notice that the range displayed ended in an integer (9) which is one less than the ending
argument (10) of the range expression.
>>>range(2, 34, 2)
range(2, 34, 2)
>>>
Take note that the list generated ended at an integer (32) which is two (the step argument)
less than the ending argument (34).
Other examples:
The input() function has an optional parameter, a prompt string. Once the function is
called, the prompt string is displayed onscreen as the program awaits user’s input. Python
returns the user’s response as a string.
To illustrate, here is a program snippet that collects keyboard input for first name, last
name, and occupation:
When you run the program, the first prompt string will be displayed onscreen as:
At this point, the program is waiting for the user’s response and does nothing until a
keyboard input is received. Type ‘Kurt’. The program will return the response
immediately after the prompt string:
After displaying ‘Kurt’, the user’s response, the program now proceeds to display the next
prompt string:
Immediately after returning‘Johnson’, the program will execute the next line, a print
statement. It will then display the next prompt string.
After returning ‘student’, the program will process the next line, another print statement:
After the program’s execution, this is what you will see on your monitor:
When writing your own program, make sure that you provide white spaces in appropriate
places. This is important for better readability. You wouldn’t want the user’s input to
crowd the prompt string so you have to provide a space before the closing quotation mark.
For instance, if you fail to allocate white spaces in the above example, the whole
interaction will look like this:
Please enter your first name:Kurt
Please enter your last name:Johnson
Good day,KurtJohnson!
What is your occupation?student
So you are a/anstudent,Kurt.Great!
Likewise, it will introduce you to an if…else code block, one of the conditional structures
supported by Python.
An if…else block first evaluates the expression given in the ‘if’ statement. If the test
condition is True, the statement(s) in the ‘if’ body is executed. If False, the statement(s) in
the ‘else’ block is executed.
This program makes use of a dictionary to store key:value pairs of usernames and
password. It uses the input() function to obtain the username then applies the membership
test to check if the response matches with one of the keys in the dictionary. If yes, then the
program uses the get() method to retrieve the value stored in the given key and stores the
value in the variable pword. It then prompts the user to enter a password and stores the
response in the variable password. Next, the program tests if pword is equal to pword and
prints a ‘Thank you!’ string if equal. If not, it prints a string that asks the user to try again.
The ‘else’ statement at the end of the program is executed if the given username does not
match any of the keys in the dictionary.
usernames = {‘Adrian’:‘123456’, ‘John’:‘GVEST’, ‘Richard’:‘REJ321’, ‘Caleb’:‘875’}
user = input(“Please enter your username: “)
if user in usernames:
pword = usernames.get(user)
password = input(“Please enter your password: “)
if password == pword:
print(‘Thank you!’)
else:
print(‘You entered an incorrect password. Please try again.’)
else:
print(‘You are not a registered user.’)
If you run the program, you may see the following results:
members = [“Marc”, “Jane”, “Joshua”, “Kian”, “May”, “Jessica”]
name = input(“Please enter your name: “)
print(“Thanks for joining the Student Organization, ” + name + “!”)
members.append(name)
total = len(members)
totalstr = str(total)
print(“There are now ” + totalstr + ” members: “)
print(members)
A program that sorts on ascending basis words from a string entered by a user:
Run the program and enter a sentence after the string prompt.
After evaluating the string entered, Python displays each word in the sentence as a list of
words:
Python
has
many
methods.
string
useful
>>>
The print() Function
For the interpreter to recognize the print function, you have to enclose the print parameters
inside parentheses.
Examples:
Python can print multiple values within the parentheses. The values must be separated by
a comma.
>>>a = “employee”
>>>b = “age”
>>>c = 25
>>>print(“requirements : “, a, b, c)
abs()
The abs() function returns the absolute value of integers or floats. The value returned is
always a positive number.
Examples:
>>>abs(-18)
18
>>> abs(30)
30
>>>abs(-88.5)
88.5
>>>
The abs() function returns the magnitude when the arguments used are complex numbers.
>>>abs(2 + 2j)
2.8284271247461903
>>>abs(1 - 3j)
3.1622776601683795
>>>
max()
The max() function returns the largest value among two or more numeric type data given
as arguments.
Examples:
min()
The min() function returns the least value among two or more numeric data types given as
arguments.
Examples:
>>>min(10, -60, 5, 0)
-60
>>>min(4, 0, 65, 1)
0
>>>
type()
The type() function returns the data type of the given argument.
Examples:
Decision making structures are necessary in situations when you want your program to
perform an action or a calculation only when a certain condition is met. Decision making
constructs begin with a Boolean expression, an expression that returns either True or
False. The response will be used as a basis for determining how the program flows.
Python supports the following conditional statements:
if statements
if else statements
elif statements
else
nested if…elif…else statements
if statements
An if statement stars with a Boolean expression followed by a statement or a group of
statements that tells what action should be done if the test expression is True. An if
statement uses the following syntax:
if expression:
statement(s)
Python evaluates the ‘if’ expression and executes the body of the program only if the
evaluation is True. You must take note of the indentation of the statements on the body of
the if expression. The first unindented line indicates the end of an if block.
To illustrate, here’s a program that collects keyboard input and uses the response as the
basis for succeeding actions.
This program asks the user to enter a vowel and prints a string if the input meets the
condition.
vowels = [‘A’, ‘E’, ‘I’, ‘O’, ‘U’, ‘a’, ‘e’,‘i’, ‘o’, ‘u’]
letter = input(“Enter a vowel: “)
if letter in vowels:
print(“Thank you, you may use this computer.”)
print(“You may only enter one of the vowels to proceed.”)
Here’s the output when you enter a vowel in response to the prompt:
Enter a vowel: o
Thank you, you may use this computer.
You may only enter one of the vowels to proceed.
>>>
Assuming you enter the consonant H, here’s what the output would be:
Enter a vowel: H
You may only enter one of the vowels to proceed.
if…else statements
An if…else statement block first evaluates the ‘if expression’. If the test condition is True,
Python executes the statements in the body of the ‘if statement’. Otherwise, if the
condition is False, Python executes the statements in the else block.
if test expression:
statement(s)
else:
statement(s)
This program checks if a food order is on stock and prints appropriate string
stock = [hamburger’, ‘pizza’, ‘hotdog’, ‘barbeque’]
order = input(“Please enter your order: “)
if order in stock:
print(“Thank you. Your order will be served in 5 minutes.”)
else:
print(“Sorry, we don’t serve ” + order + ” at the moment.”
If you run the program and enter pizza at the prompt, here’s what it does:
Run the program again. This time, enter something that’s not on stock, ‘ice cream’.
if…elif…else statements
An elif (else if) statement can be used when there is a need to check or evaluate multiple
expressions. An if…elif…else structure first checks if the ‘if statement’ is True.
If true, then Python executes the statements in the if block. If False, it tests the condition
in the elif block. If the elif statement is evaluated as True, Python executes the statements
in the elif block. Otherwise, control passes to the else block. An if block can have as many
elif blocks as needed but it can only have one else block.
if expression:
if block
elif expression:
elif block
else:
else block
This program checks if a food order is in the list of foods that can be served in 5
Minutes. If not, it checks if the food order is in the list of foods that can be served in 15
minutes. If the food is not found in either list of foods, program prints an appropriate
statement.
stock1 = [‘hamburger’, ‘pizza’, ‘hotdog’, ‘barbeque’]
stock2 = [‘Fried Chicken’, ‘French Fries’, ‘Chips’, ‘Apple Pie’]
order = input(“Please enter your order: “)
if order in stock1:
print(“Thank you. Your order will be served in 5 minutes.”)
elif order in stock2:
print(“Are you willing to wait? Your order will be served in 15 minutes.”)
else:
print(“Sorry, we don’t serve ” + order + ” at the moment.”)
If you run the program and enter ‘hamburger’, here’s what the program does:
Run the program again and enter ‘Fried Chicken’, an item in the list stock2:
If you run the program again and enter a food item that’s not on either list, Mango Pie,
here’s what the output would be:
if test_expression1:
if test_expression1-a:
statement_block1-a
elif test_expression1-b:
statement_block1-b
else
statement_block1-c
elif test_expression2:
statement_block2
else:
statement_block3
This program asks for the user’s age and prints appropriate string based on the response.
num = int(input(“Enter your age: “))
if num >= 20:
if num >= 60:
print(“Please register with the Seniors Club.”)
elif num >= 36:
print(“You belong to the MiddleAgers Club.”)
else:
print(“Please register with the Young Adults Club.”)
elif num > 12:
print(“You belong to the Youth Club.”)
else:
print (“Sorry, you are too young to be a member.”)
A loop is a control structure that allows the repetitive execution of a statement or group of
statements. Loops facilitate complicated execution paths.
for val in sequence:
statement(s)
In the for statement, the variable ‘val’stores the value of each item on the sequence with
every iteration. The loop goes on until all elements are exhausted.
Examples:
For Loop with string:
< p >
< r >
< o >
< g >
< r >
< a >
< m >
< m >
< i >
< n >
< g >
>>>
For Loop with list
weather = [‘sunny’, ‘windy’, ‘rainy’, ‘stormy’, ‘snowy’]
for item in weather:
print(“It’s a”, item, “day!”)
print(“Dress appropriately!”)
color = (‘red’, ‘blue’, ‘pink’, ‘green’, ‘yellow’)
for x in color:
print(“I’m wearing a”, x, “shirt!”)
print(“Multi-colored shirts are cool!”)
Here is a loop that evaluates whether a number is even or odd. It prints the number and
state if it is an even or odd number.
numbers = [10, 99, 3, 28, 41, 40, 5, 9, 66]
for n in numbers:
if n % 2 == 0:
print(n, “is an even number.”)
else:
print(n, “is an odd number.”)
10 is an even number.
99 is an odd number.
3 is an odd number.
28 is an even number.
41 is an odd number.
40 is an even number.
5 is an odd number.
9 is an odd number.
66 is an even number.
>>>
x = 15
total = 0
for number in range(1, x+1):
total += number
print(“Sum of 1 and numbers from 1 to %d: %d” % (x, total))
When you run the program, you will have this output:
The ‘while loop” is used when you need to repeatedly execute a statement or group of
statements while the test condition is True. When the test condition is no longer true,
program control passes to the line after the loop.
while condition
statement(s)
Here is a program that adds number up to num where num is entered by the user. The total
= 1+2+3+4… up to the supplied number.
Example:
number = int(input(“Enter a number: “))
#initialize total and counter
total = 0
c = 1
while c <= number:
total = total + c
c += 1
#print the total
print(“The total is: “, total)
Enter a number: 5
The total is: 15
>>>
Break Statement
A break statement ends the present loop and instructs Python to execute the first statement
next to the loop. In nested loops, a break statement terminates the innermost loop and
instructs the interpreter to execute the line that follows the terminated block. A break
statement is commonly used to prevent the execution of the ‘else statement’. It is used to
end the current iteration or the entire loop regardless of the test condition or when external
conditions require immediate exit from the loop.
break
animals = [‘lion’, ‘tiger’, ‘monkey’, ‘bear’, ‘sloth’, ‘elephant’]
for name in animals:
if name == ‘sloth’:
break
print(‘Cool animal:’, name)
print(“Amazing animals!”)
Continue Statement
The continue statement skips remaining statement(s) in the present iteration and directs
the program to the next iteration.
continue
The break statement in the previous example may be replaced with the continue statement:
animals = [‘lion’, ‘tiger’, ‘monkey’, ‘bear’, ‘sloth’, ‘elephant’]
for name in animals:
if name == ‘sloth’:
continue
print(‘Cool animal:’, name)
print(“Amazing animals!”)
Pass Statement
A pass is a null operation in Python. The interpreter reads and executes the pass statement
but returns nothing. A pass statement is commonly used as a place holder whenever
Python’s syntax requires a line that you can’t provide at the moment. It is used to mark
codes that will eventually be written.
pass
Examples:
Looping Techniques
The ‘for loop’ and the ‘while loop’ can be combined with loop control statements to create
various loop forms.
Infinite loops (while loop)
The infinite loop is formed with the while statement. You’ll get an infinite loop when the
specified test condition is always True. Following is an example of an infinite loop. The
program imports the math module and uses the square root method on the given number.
To leave the loop, you will have to press Ctrl-c.
IMPORTANT
We will discuss importing math modules in Step 18.
import math
while True:
num = int(input(“Enter a number: “))
print(“The square root of” ,num, “is”, math.sqrt(num))
Enter a number: 9
The square root of 9 is 3.0
Enter a number: 4
The square root of 4 is 2.0
Enter a number: 8
The square root of 8 is 2.8284271247461903
Enter a number: 49
The square root of 49 is 7.0
Enter a number:
>>>
Because the condition will always be True, the while loop will continue to execute and ask
the user to enter a number.
Loops with top condition (while loop)
A while loop with a condition placed at the top is a standard while loop with no break
statements. The loop ends when the condition becomes False. Here is a program that
illustrates this form of while loop:
x = int(input(“Enter a number: “))
#initialize total and counter
total = 0
count = 1
while count <= x:
total = total + count
count = count + 1 # updates counter
# prints the total
print(“The total is”,total)
Enter a number: 4
The total is 10
>>>
Enter a number: 7
The total is 28
>>>
Loops with middle condition
This loop is usually implemented with an infinite loop and a conditional break in between
the loop’s body.
This program takes input from user until the desired input is entered.
letters = “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz”
# infinite loop
while True:
l = input(“Enter a letter: “)
# condition in the middle
if l in letters:
break
print(“That is not a letter. Please try again!”)
print(“Perfect!”)
Run the program and try entering a number. The program will run infinitely if you insist
on entering a number.
Enter a letter: 5
That is not a letter. Please try again!
Enter a letter: 3
That is not a letter. Please try again!
>>>
Enter a letter and the break statement will be executed. Program flow will continue to the
next line, a print statement.
Enter a letter: a
Perfect!
>>>
Loops with condition at the end
In this looping technique, the loop’s body is run at least once. It can be run with an infinite
loop and a conditional break at the bottom.
This program chooses a random number until the user opts to exit, it imports the random
module and uses the randint() method.
import random
while True:
input(“Press enter to draw a number “)
# get a number between 1 to 20
number = random.randint(1,20)
print(“You got”,number)
choice = input(“Do you want to play again?(y/n) “)
if choice == ‘n’:
break
When you run the program, the loop goes on infinitely until you press ‘n’ which leads to a
break statement that ends the loop.
A function is a block of organized and related statements that is used to perform a specific
task. It is a structuring element that allows a code to be used repeatedly in different parts
of a program. Using functions enhances program readability and comprehensibility.
Functions help make programming more efficient by minimizing repetitions and breaking
down long and complex programs into smaller and manageable segments.
def function_name(parameters):
“““docstring”””
function body
>>>def greet(name):
“““Greets the person
passed as argument”””
print(“Hello, ” + name + “. Good day!”)
>>>
It’s a good practice to name your function according to the work they perform.
2. function name
A function is identified by a unique name that is given to it in the function header
statement. Function-naming follows the rules set for writing identifiers.
3. parameters
Parameters (argument) are optional and are used to pass values to functions. They are
written inside parentheses.
4. colon (:)
A colon marks the end of function headers.
5. docstring
A documentation string or docstring is an optional component that is commonly used to
describe what the function does. It is written on the line next to the function header. A
docstring can span up to several lines and are enclosed in triple quotes. You can access the
docstring with: function_name.__doc__.
For example, this function has a two-line docstring enclosed in triple quotes:
>>>def greet(name):
“““Greets the person
passed as argument”””
print(“Hello, ” + name + “. Good day!”)
>>>
To access the docstring, print the __doc__ attribute of the function ‘greet’.
>>> print(greet.__doc__)
Greets the person
passed as argument
>>>
Likewise, you can access the string through the >>> prompt:
>>> greet.__doc__
‘Greets the person\n passed as argument’
>>>
6. statement(s)
A function’s body consists of one or more valid statements. Multiple statements use the
same indentation to form a block.
7. return statement
A return statement is used to return a value from a function. If a return statement is not
given inside a function, the function will return the object ‘None’.
return [expression_list]
>>>def greet(name):
“““Greets the person
passed as argument”””
print(“Hello, ” + name + “. Good day!”)
>>>print(greet(“John”))
Hello, John. Good day!
None
>>>
def absolute_value(number):
“““Returns the absolute value of
a number entered by user”””
if number >= 0:
return number
else:
return -number
print(absolute_value(12))
print(absolute_value(-100))
print(absolute_value(-50))
When you run the program, the function will return the absolute value of the given
integers:
12
100
50
>>>
Here is a function with a parameter and return, a function that evaluates if a given number
is an even number. It is a function which returns the number if even, otherwise, function
returns a string and None.
def even_numbers(number):
if number % 2 == 0:
return number
else:
print(“Sorry,that’s not an even number.”)
print(even_numbers(22))
22
print(even_numbers(13))
Sorry, that’s not an even number.
None
print(even_numbers(14))
14
def people_id(name):
“““This function greets the person named as parameter.”””
print (“Hi, ” + name + “, Welcome and enjoy your stay! Good day!”)
print(people_id(‘Sean’))
print(people_id(‘Kirsten’))
print(people_id(‘Dax’))
def member_check(x):
if x.lower() == “y”:
return(“Thanks for your loyalty!”)
elif y.lower() == (“n”):
return(“Please complete membership forms.”)
else:
return(“Please check your response.”)
print(member_check(“y”))
print(member_check(“n”))
print(member_check(“x”))
Calling a Function
Once it is defined, you can call a function in different ways. You can call it through the
>>> prompt, through another function, or through a program.
The simplest way to call a function is through the >>> prompt. You can do this by typing
the function name and providing the parameters.
>>>def stringprinter(str):
print(str)
return;
At the prompt, call the stringprinter function and supply the arguments:
For example:
def class_sum(num):
return num * 3
def school_sum(m):
return class_sum(m) + 3
print(school_sum(5))
print(school_sum(8))
print(school_sum(15))
Output:
17
27
47
>>>
Mark = {
“Name”: “Mark Spark”,
“Quizzes”: [89.0, 95.0, 78.0, 90.0],
“Homework”: [89.0, 60.0, 98.0],
“Recitation”: [89.0,90.0, 88.0],
“Tests”: [85.0, 92.0]
}
Selen = {
“Name”: “Selen Jobs”,
“Quizzes”: [98.0, 100.0, 95.0, 100.0],
“Homework”: [85.0, 84.0, 90.0],
“Recitation”: [87.0, 89.0, 90.0],
“Tests”: [90.0, 97.0]
}
Shane = {
“Name”: “Shane Taylor”,
“Quizzes”: [75.0, 87.0, 95.0, 84.0],
“Homework”: [92.0, 74.0, 99.0],
“Recitation”: [80.0, 83.0, 84.0],
“Tests”: [98.0, 100.0]
}
def average(numbers):
total=sum(numbers)
result=total/len(numbers)
return result
def get_average(student):
Quizzes = average(student[“Quizzes”])
Homework = average(student[“Homework”])
Recitation = average(student[“Recitation”])
Tests = average(student[“Tests”])
print(student[“Name”])
return .2*Quizzes + .1*Homework + .3*Recitation + .4*Tests
print(get_average(Mark))
print(get_average(Selen))
print(get_average(Shane))
Mark Spark
87.93333333333334
Selen Jobs
92.28333333333333
Shane Taylor
90.18333333333334
>>>
Anonymous Functions
While you would normally define a function with the def keyword and a name,
anonymous functions are defined with the lambda keyword and without a name. An
anonymous function is variably called a lambda function.
lambda arguments: expression
A lambda function can take as many arguments as you want but it can only have one
expression. That single expression is evaluated then returned. You can use a lambda
function anywhere a function object is needed.
Here is an example of a program that uses the lambda function that squares the value of
input:
squared = lambda x: x ** 2
print(squared(10))
In the above sample program, lambda x: x ** 2 is the lambda function where x is the
argument and x ** 2 is the expression that the interpreter evaluates and returns. The
identifier ‘squared’ holds the function object returned by the expression.
The statement which assigns the lambda expression to ‘squared’ is almost like defining a
function named squared with the following statements:
def squared(x):
return x ** 2
Lambda functions are commonly used when a nameless function is required on a short-
term basis. In Python, lambda functions are generally used as arguments to other
functions. It is used with built-in functions such as map() and filter().
Python’s map() function takes in a list and another function. The function argument is
called with all elements in the list and returns a new list containing elements returned from
each element in the original list.
Here is an example showing how the map() function is used with the lambda function to
get the squared value of every integer in the list.
num_list = [1, 3, 5, 7, 9, 11, 8, 6, 4, 2]
squared_list = list(map(lambda x: x ** 2 , num_list))
print(squared_list)
Python’s filter() function takes in a list and another function as parameters. The function
argument is called with all elements in the list and returns a new list containing elements
returned from each element in the original list that evaluates to True.
Here is an example of the usage of the filter() function in a program that filters out odd
number from a specified list:
num_list = [12, 4, 1, 8, 9, 6, 11, 5, 2, 20]
odd_list = list(filter(lambda x: (x % 2 != 0) , num_list))
print(odd_list)
[1, 9, 11, 5]
>>>
Recursive Functions
Recursion is a programming construct where the function calls itself at least once in its
body. The value returned is usually the return value of the function call. A recursive
function is a function that calls itself.
While recursion is often associated with infinity, a recursive function has to terminate in
order to be used. A recursive function can be brought to an end by downsizing the solution
with every recursive call as it moves gradually to a base case. The base case is the
condition where a problem can finally be solved without recursion. Recursion can result to
an infinite loop if the base case is not reached in the function calls.
The use of recursive function is illustrated in the computation of the factorial of a number.
A number’s factorial refers to the product of all integers from 1 to the given integer. For
example, to find the factorial of 5 (written as 5!): 1*2*3*4*5 = 120. The problem is
solved by multiplying the value returned from the previous multiplication operation with
the current integer until it reaches 5.
def factorial(num):
if num == 1:
return 1
else:
return num * factorial(num-1)
Run the program and use the print function to find the factorial for the numbers 5 and 7:
>>>print(factorial(5))
120
>>>print(factorial(7))
5040
>>>
Any file that contains proper Python code and has the .py extension can be called a Python
module. Modules contain statements and definitions. They usually contain arbitrary
objects such as classes, functions, files, attributes, and common Python statements like
those that initialize the module. These objects can be accessed by importing them.
Modules help break down large programs into manageable files. They also promote code
reusability. You can, in fact, gather the most frequently used functions, save them in one
module, and import them in your other programs.
Modules are known by their main filename, that is, without the .py extension. For
example, create a module and save it as multiplier.py.
For example, if you want to reuse the multiplier module, you can use the following
statements:
>>>import multiplier
>>> multiplier.multiply (5, 3)
15
>>>
Python’s Math Module
Importing the math module allows Python users to access attributes and mathematical
functions and constants such as sin() and cosine() functions, pi, and square root. One you
import the math module, you can simply place math and a dot before the attribute or
function.
>>>import math
>>>
The above statement is an example of a generic import where you only import the module
without specifying a function. The statement gives you access to math module’s entire
definition.
To import specific math definitions, attributes, or functions, you will just simply type them
after math and a dot. For example:
>>>math.pi
3.141592653589793
>>> math.sqrt(100)
10.0
>>> math.gcd(16, 8)
8
>>> math.fabs(-12)
14.0
>>>
If you just need a specific function, for instance, square root, it will be tiring to repeatedly
type math.sqrt() every time you want to obtain the square root of a number. To avoid this,
you can do a function import with this syntax:
>>> from module import function
>>> from math import sqrt
From here, you only need to type sqrt() and the number:
>>>import multiplier
>>>dir (multiplier)
[‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’,
‘__package__’, ‘__spec__’, ‘multiply’]
>>>
The math module contains many useful functions. To print the entire content of the math
module, you can use the following code:
import math
everything = dir(math)
print (everything)
This is what you would see on your screen after running the code:
For instance, if you want to read Python’s help documentation for the math function sqrt,
you can use the following statements:
>>>import math
>>>help(math.sqrt)
sqrt(…)
sqrt(x)
>>>
The Random Module
By importing the random module, you will have access to several functions that are
commonly used in games.
Usage of Random Module
The random module is commonly used when you want a program to produce a random
number on a specified range. It is used when the program requires the user to pick a
random element from a list, roll a dice, pick a card, flip a coin, and similar games.
Random Functions
Random provides the following useful functions:
1. Randint
The randint() function is used to generate a random integer and accepts two parameters.
The first one is the lowest number and the second one is the highest number. For example,
to generate any integer from 1 to 6:
>>>import random
>>>print (random.randint(1, 6))
>>>import random
>>>print(random.randint(0, 100))
96
>>>
2. Choice
random.choice( [‘cat’, ‘dog’, ‘parrot’] ).
This function is most commonly used to pick a random item from a list.
import random
my_list = [2, 3, 4, 5, 6, 7, 8, 9, 10, “Ace”, “Jack”, “Queen”, “King”]
random.choice(my_list)
print(random.choice(my_list))
print(random.choice(my_list))
print(random.choice(my_list))
Run the program and y0u might get the following random output:
4
Queen
2
>>>
3. Shuffle
The shuffle() function sorts the elements on a list so that they will be arranged in random
order.
random.shuffle(list)
Here’s an example:
from random import shuffle
a = [[x] for x in range(15)]
shuffle(a)
>>>print(a)
[[14], [5], [10], [7], [11], [13], [0], [2], [9], [1], [6], [12], [3], [4], [8]]
>>>
Since numbers are shuffled on a random basis, you will most probably get a different
result every time you use the print statement.
import random
my_list = [‘P’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘m’, ‘e’, ‘r’]
random.shuffle(my_list)
print(my_list)
[‘r’, ‘e’, ‘g’, ‘a’, ‘m’, ‘m’, ‘P’, ‘r’, ‘r’, ‘o’]
>>>
4. Randrange
The randrange() function generates a random element from a specified range.
random.randrange(start, stop[, step])
Here is an example:
import random
for x in range(5):
print(random.randrange(0, 50, 2))
12
42
48
28
0
>>>
Universal Imports
Instead of importing specific object(s), it’s possible to import everything from a module
by using an asterisk * in the import statement. This is called universal import.
For example:
While it may seem convenient to just import everything instead of explicitly importing a
certain function, universal import is not recommended except when using the Python Shell
interactively. One reason is the possibility of running several functions with exactly the
same name. If you import with an asterisk *, you might risk running functions with
obscure origin because you won’t know which module they came from.
Importing Several Modules at Once
You can import several modules in one import statement by separating module names with
commas. For example:
When importing a module, you can change the name of the namespace with:
import module as module2
For example:
Most programs require date and time data to operate. Python has time and calendar
modules that can be used to track times and dates in programs.
To access functions in the time module, you have to import the module with:
import time
Many time functions return a time value as a tuple of 9 integers. The functions strptime(),
and gmtime() also provide attribute names for each field.
>>>import time
>>>print(time.localtime())
The above time tuple represents the struct_time structure which has the following
attributes:
Index Attributes Fields Values
0 tm_year 4-digit year 2016
1 tm_mon month 1 to 12
2 tm_mday day 1 to 31
3 tm_hour=23 hour 0 to 23
4 tm_min=51 minute 0 to 59
5 tm_sec second 0 to 61
6 tm_wday day of the week 0 to 6 (0 is Monday)
7 tm_yday day of the year 1 to 366
8 tm_isdst Daylight savings 0, 1, -1
Formatted Time
You can format time in many different ways with the print function. There are also several
ways to get readable time format in Python. A simple way to get time is with the asctime()
function. Here’s an example:
>>>import time
>>> time_now = time.asctime( time.localtime())
>>> print (“Current date and time is:”, time_now)
import calendar
For example, to get the calendar for the month of July, 2016, you can use the following
statements:
>>>import calendar
>>>July_cal = calendar.month(2016, 7)
>>>print (“Calendar for the month of:”)
>>>print (July_cal)
time.altzone
time.asctime
time.clock
time.ctime
time.gmtime
time.localtime
time.mktime
time.sleep
time.strftime(fmt[, tuppletime])
time.strptime(string[, format = “%a %b %d %H:%M:%S %Y”])
time.time
time.tzset
Br default, calendar has Monday as the first day of the week. You can change this by
calling the calendar.setfirstweekday() function.
The calendar module offers the following functions:
The calendar.calendar() function returns a multiline string of calendar for a given year.
calendar.firstweekday( )
The function returns the setting for the first weekday of the week. The default starting day
is Monday which is equivalent to o.
>>>import calendar
>>>calendar.firstweekday()
0
>>>
calendar.isleap(year)
This function evaluates if the given year is a leap year. If yes, it returns True. If not, it
returns False.
>>>import calendar
>>> calendar.isleap(2016)
True
>>> calendar.isleap(2014)
False
>>>
calendar.leapdays(y1, y2)
This function returns the sum of leap days within a given range.
>>>import calendar
>>> calendar.leapdays(2010, 2016)
1
>>>
calendar.month(year, month, w=2, l=1)
This function returns a multiline string of calendar for a given month of the year. The
value of w indicates the width (in characters) of the dates while l specifies the allotted
lines for each week.
>>>import calendar
>>>calendar.month(2016, 7, w=2, l=1)
>>>‘ July 2016\nMo Tu We Th Fr Sa Su\n 1 2 3\n 4 5 6 7 8 9 10\n11 12 13
14 15 16 17\n18 19 20 21 22 23 24\n25 26 27 28 29 30 31\n’
>>>
Use the print function to get a calendar for the month in a more user-friendly format.
>>>import calendar
>>>calendar.monthcalendar(2016, 7)
[[0, 0, 0, 0, 1, 2, 3], [4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22,
23, 24], [25, 26, 27, 28, 29, 30, 31]]
>>>
calendar.monthrange(year, month)
This function returns two integers. The first integer denotes the weekday code (o to 6) for
the first day of the month in a given year. The second indicates the number of days in the
specified month (1 to 31).
>>>import calendar
>>>calendar.monthrange(2016, 7)
(4, 31)
>>>
calendar.prmonth(year, month, w=2, l=1)
It returns a calendar for the month like what you’ll see if you use print
(calendar.month(year,month,w,l)).
calendar.setfirstweekday(weekday)
Sets the first day of the week using a weekday code that represents the days from Monday
(0 ) to Sunday (6).
>>>import calendar
>>> calendar.weekday(2016,6,30)
3
>>>
Datetime
Python has another method, datetime(), that you can use to retrieve current system date
and time. Before you can use it, you’ll have to import the module datetime.now().
In order to convert the date and time information into a more readable format, you can
import ‘strftime’ from Python’s standard library with these statements:
‘2016-07-08 02:35:02’
Step 20: Namespaces
A name or identifier is a way of identifying and accessing objects. For instance, when you
enter an assignment statement like x = 5, 5 is the object stored in memory while x is the
name that we use to refer to the object. You can get the memory address of some objects
by using id(), a built-in function.
For example:
>>> x = 5
>>>id(x)
1518352208
>>> id(5)
1518352208
>>>
The above results with the id() functions tells you that x and 5 refer to the same object.
Here are other expressions that can tell how Python responds to reassignments:
>>> x =5
>>>id(x)
1518352208
>>>
Here, x gets reassigned and holds the value of 5 + 7. It is now in another memory location:
>>> x = 5 + 7
>>> id(x)
1518352320
>>>
Finally, 5 is assigned to ‘y’. Take note that using id() on both the name and object returns
the same memory location of the object 5, that is, at 1518352208. This makes Python
programming efficient since you won’t have to create duplicate copies of the object.
>>>y = 5
>>> id(5)
1518352208
>>> id(y)
1518352208
>>>
Since a function is also an object, you can use a name to refer to it. You will then use the
function’s name to call it.
For example:
def greetings():
print(“Good Morning!”)
x = greetings
>>> x()
Good Morning!
>>>
Now that you have a better idea about names and what you can use them for, you’re ready
to learn the concept of namespaces. A namespace is basically a collection of names. It is a
mapping of every name that has been defined to corresponding objects. For instance,
Python aut0matically creates a namespace that has all the built-in names when you start
the interpreter. Hence, built-in functions are always available. Each Python module creates
a global namespace for itself. A module can have several classes and functions. A local
namespace is created every time a function is called.
Scope
Although namespaces have distinct names, it is not always possible to access all of them
from just about anywhere in the program. There is such a thing as scope, a program
component that allows users to access a namespace directly without a prefix. There are at
least 3 nested scopes:
Every time a reference is made inside a function, the interpreter searches for the name in
the following hierarchy: 1. local namespace 2. global namespace and 3. built-in
namespace.
def main_function():
x = 50
def sub_func():
y = 15
z = 5
In the above code, the variable x is within the local namespace of main_function(). The
variable y is in the local namespace of sub_function, a nested function. The variable z, on
the other hand, is in the global namespace.
Inside the main_function, x is a local variable, y is nonlocal, while z is global. When in the
main_function, you can read and assign new values to x, a local variable but you can only
read the variable y from sub_function. If you try to reassign y to a new value, that will be
stored in the local namespace you’re in, the main_function, and will be an entirely
different variable from the variable y in the sub_function.
The same thing happens if you try to reassign z, the global variable, inside the
main_function. If you want all references and assignments to go to the global variable,
you have to declare it as global with the expression ‘global z’.
To illustrate, here is a program that uses and accesses the variable z in three different
namespaces:
def main_function():
z = 10
def sub_function():
z = 20
print(‘z =’,z)
sub_function()
print(‘z =’,z)
z = 33
main_function()
print(‘z =’,z)
z = 20
z = 10
z = 33
>>>
Here’s a program where all references and assignments go to the global variable z:
def main_function():
global z
z = 10
def sub_function():
global z
z = 20
print(‘z =’,z)
sub_function()
print(‘z =’,z)
z = 33
main_function()
print(‘z =’,z)
The output will show the value assigned to z as a global variable in the nested function:
z = 20
z = 20
z = 20
>>>
Step 21: Classes and Object-Oriented
Programming
An object can refer to anything that could be named such as functions, integers, strings,
floats, classes, methods, and files. It is a collection of data and the methods that utilize
data. Objects are flexible structures that can be used in different ways. They can be
assigned to variables, dictionaries, lists, tuples, or sets. They can be passed as arguments.
A class is a data type just like a list, string, dictionary, float, or an integer. When you create
an object out of the class data type, the object is called an instance of a class.
In Python, everything is an object — and that includes classes and types. Both classes and
types belong to the data type ‘type’. The data value that you store inside an object is
called an attribute while the functions associated with it are called methods. A class is a
way of creating, organizing, and managing objects with like attributes and methods.
Designing an object requires planning and decision-making on what the objects will
represent and how you can group things together.
Defining a Class
To define a class, you will use the keyword class followed by a class identifier and a
colon. If the new class is a child class, you’ll have to enclose a parent class inside the
parentheses. A class name starts in uppercase by convention. The class definition is
usually followed by a docstring which provides a short description of the class.
class Members:
I created a new class.
pass
This is an example of a definition of a class that takes an object:
ClassName.__doc__.
When you use the keyword ‘class’ to define a class, this tells Python to create a new class
object with the same name. Defining a class creates a namespace that contains the
definition of all the attributes of the class, including special attributes that start with
double underscores. This object can then be used to access the attributes of the class and to
create or instantiate new objects of the class.
class MyClass:
“This is a new class.”
b = 12
def greet (self):
print (‘Good morning!’)
>>> MyClass.b
12
>>> MyClass.greet
<function MyClass.greet at 0x02CA5D20>
>>> MyClass.__doc__
‘This is a new class.’
>>>
Creating an Object
The class object can be used to create instances of the new class. Creating an object is no
different from making a function call at the >>> prompt. For example, the following
statement creates an instance object called obj:
>>>obj = MyClass()
To access the attributes of an object, you can use the object name as prefix before the dot.
An object’s attribute is either method or data. An object’s method refers to the
corresponding functions of the class. A function object defines a method for objects
created from a class. For example, create a class named NewClass:
class NewClass:
“This is a new class.”
x = 5
def func (self):
print(“I’m a function object.”)
>>> NewClass.func
<function NewClass.func at 0x02BB5D20>
>>>
>>>obj = NewClass()
NewClass.func, a class attribute, is a function object because it defines a method for all
object created from NewClass. Hence, obj.func is a method object.
>>> obj.func
<bound method NewClass.func of <__main__.NewClass object at 0x02BB1C10>>
>>>
You probably notice the parameter ‘self’ in function definition inside classes. Yet, when
the method obj.func was called without an argument, Python went on with the process and
did not raise an error. That is because the object itself is passed as the first argument. In
Python, when an object calls its method, the object automatically becomes the first
argument. By convention, it is called ‘self’. You can use any name but for uniformity, it is
best to stick with the convention. If you need to place more arguments, you have to place
‘self’ as the first argument.
Examples:
class Achievers:
def __init__(self) :
For example:
class Employees:
“Common base for all employees.”
counter = 0
def __init__(self, name, position, salary) :
self.name = name
self.position = position
self.salary = salary
The class definition code block states that whenever an instance of the Employees class is
created, each employee will have a copy of the variables initialized using the __init__
method.
You can instantiate members of the class Employees with these statements:
Following is a longer code that illustrates class definition and the use of the datetime
module:
import datetime
class Member:
def __init__(self, firstname, surname, birthdate, country, email, telephone):
self.firstname = firstname
self.surname = surname
self.birthdate = birthdate
self.country = country
self.email = email
self.telephone = telephone
def age(self):
now = datetime.date.today()
age = now.year - self.birthdate.year
if now < datetime.date(now.year, self.birthdate.month, self.birthdate.day):
age -= 1
return age
member1 = Member(
“Jessica”,
“Law”,
datetime.date(1995, 6, 1), # year, month, day
“United States”,
“jane.law@yow.com”,
“811 432 0867”
)
member2 = Member(
“Martin”,
“Donz”,
datetime.date(1991, 8, 16), # year, month, day
“Canada”,
“martindonz@jobs.com”,
“580 324 7111”
)
print(member1.firstname)
print(member1.surname)
print(member1.birthdate)
print(member1.country)
print(member1.email)
print(member1.telephone)
print(member1.age())
print(member2.firstname)
print(member2.surname)
print(member2.birthdate)
print(member2.country)
print(member2.email)
print(member2.telephone)
print(member2.age())
Run the code and you’ll see the following output onscreen:
Jessica
Law
1995-06-01
United States
jane.law@yow.com
811 432 0867
21
Martin
Donz
1991-08-16
Canada
martindonz@jobs.com
580 324 7111
24
You will notice that two functions were defined inside the Member class body. These
functions are the object’s methods.
The first is a special method, __init__(). Whenever you call the class object, it creates a
new instance of the class and Python immediately executes the __init__() method on the
new object. The __init__ method is used to pass on to the new object and to set it up with
all the data and parameters that you have specified. The second method, the ‘age’ method,
calculates the member’s age with the use of current date and the birthdate.
Take note that the __init__ function creates attributes and sets them according to the
values passed in as parameters. Although it’s not compulsory, the attributes and
parameters are usually given the same name.
Adding an attribute
It is possible to add an attribute outside of the __init__ function.
To illustrate, here is a program that has two numbers as class attributes:
class NumberPairs:
def __init__(self, first = 0, second = 0):
self.first = first
self.second = second
def display_data(self):
print(“The first number is {0} and the second number is {1}.”.format(self.first,
self.second))
This one will create object ‘b’ with only one number, 6, as argument:
>>> b = NumberPairs(6)
>>> b.display_data()
The first number is 6 and the second number is 0.
>>>
Notice that it took the supplied argument as the first number and zero as the default
argument for the second number.
If you want to add a new attribute to the object ‘b’, you can easily do so with the syntax
‘obj.attr = value’.
>>>b.attr = 16
To display the values of the number pair and the new attribute:
>>> a.attr
Attempting to access the non-existent object a.attr will raise the AttributeError:
del obj.attribute
To delete pairs2:
>>>del pairs2.second
If you try to call the function display_data on pairs2, Python will throw an AttributeError:
>>> pairs2.display_data()
Traceback (most recent call last):
…
AttributeError: ‘NumberPairs’ object has no attribute ‘second’
The same thing happens when you delete the function display_data:
del object
Using the above example, you can delete object ‘a’ with:
>>>del a
>>>
While the above statements may sound so simple, what happens internally is more
complicated. When you create an instance object with c = NumberPairs(16, 7), the name c
binds with the object in memory. When you issue the command del c, the relationship is
broken and the name c is removed from its corresponding namespace. The object,
however, remains in memory. It is automatically destroyed later if it not referenced to by
another name. This process is commonly known as ‘garbage collection’.
To illustrate, this program shows how the value stored in the variable ‘condition’ changed
from ‘new’ to ‘used’ as the program is executed:
When you run the program, you will have the following output:
Inheritance
Inheritance is a programming structure that allows a new class to inherit the attributes of
an existing class. The new class is called the child class, subclass, or the derived class
while the class it inherits from is the parent class, superclass, or base class. Inheritance is
an important feature because it promotes code reusability and efficiency. If you have, for
example, an existing class that delivers what your program requires, you can create a
subclass that will take most of what the existing class does, enhance its functionality, or
perhaps partially override some class behavior to make it a perfect fit for your purpose.
To define a class that will inherit all functions and variables from a parent class, you will
use the syntax:
class ChildClass(ParentClass):
class Students(object):
“common base for all members”
def __init__(self, name, average, level):
self.name = name
self.average = average
self.level = level
stud1 = Students(“Michelle Kern”, 88.3, “Senior”)
stud2 = Students(“Jennifer Pauper”, 93.5, “Junior”)
stud3 = Students(“Dwight Jack”, 90.0, “Junior”)
print(stud1.name, stud1.average, stud1.level)
print(stud2.name, stud2.average, stud2.level)
print(stud3.name, stud3.average, stud3.level)
When you run the program, you’ll get the following output:
Assuming you want to create a new class, Graduates, which will inherit from the Students
class and use a new attribute, grad_year, here’s how your program might look:
class Graduates(Students):
“common base for Graduates members”
def __init__ (self, name, average, level, grad_year):
Students.__init__(self, name, average, level)
self.grad_year = grad_year
mem1 = Graduates(“Randy Doves”, 88.2, “graduate”, “2015”)
mem2 = Graduates(“Dani Konz”, 85.0, “graduate”, “2014”)
mem3 = Graduates(“Ashley Jones”, 89.5, “graduate”, “2016”)
print(mem1.name, mem1.average, mem1.level, mem1.grad_year)
print(mem2.name, mem2.average, mem2.level, mem2.grad_year)
print(mem3.name, mem3.average, mem3.level, mem3.grad_year)
When you run the program, you would have the output:
class MultiDerivedClassName (ParentClass1, ParentClass2,
ParentClass3, …):
pass
Multilevel Inheritance
A multi-level inheritance allows a new class to inherit from a derived class. In Python,
multilevel inheritance can go as deep as you want it to go. Following is the syntax for
multi-level inheritance:
class Base:
pass
class Derived_1(Base):
pass
class Derived_2(Derived_1):
pass
class Derived_3(Derived_2)
Step 22: Python Iterators
An iterator is any Python objectwhichcan be iterated onto return data on a per itembasis.
Python iterators can be found in many places. They are implemented in comprehensions,
‘for’ loops, and generators but are not readily seen in plain sight. Iterator objects must
performthemethods __iter__() and __next__().
In general, built-in Python containers like string, list, and tupleare iterable because they
can be used to produce an iterator. The function iter() is used to return an iterator by
calling the __iter_() method. The function next() is then used to iterate through each
element. The StopIteration exception is raised whenever the end is reached.
To illustrate:
>>>num_list = [5, 8, 2, 4]
>>>num_iter = iter(num_list)
>>>num_iter
<list_iterator object at 0x03300F30>
>>>next(num_iter)
5
>>>next(num_iter)
8
>>>next(num_iter)
2
>>>next(num_iter)
4
>>>
You can get similar results by using theexpression ‘obj.__next__()’. To illustrate, create a
new iterator, new_iter to iterate through the num_list:
>>>num_list = [5, 8, 2, 4]
>>> new_iter = iter(num_list)
>>>new_iter
<list_iterator object at 0x03A50FD0>
>>>
>>> new_iter.__next__()
5
>>> new_iter.__next__()
8
>>> new_iter.__next__()
2
>>>new_iter.__next__()
4
>>>
Iterating through containers need not always be as tedious. The use of the ‘for loop’, offers
a more sophisticated way to iterate automatically through an object.
For example:
5
8
2
4
The use of the ‘for loop’ in the above example makes iteration a simple task. Internally,
however, a ‘for loop’ is executed as an infinite loop with try and except statements. The
following example will illustrate how Python executes a ‘for loop’.
Internally, Python implements the above statement block as an infinite while loop:
while True:
try:
item = next(iterator_object)
except StopIteration:
break
Behind the scenes, the ‘for loop’ calls iter() on x_iterable to create an iteratorobject.In
addition, the next() function is used within the ‘while’ structure to return the succeeding
item. After exhausting all items, Python will raise a StopIteration exception which
indicates the end of the loop. The StopIteration is the only exception that can terminate the
loop. All other exceptions are ignored.
To build an iterator, you need to execute the iterator protocol, namely, the__iter__() and
__next__() methods.
The method __iter__() is used to return an iterator object. The __next__() method is then
called to return the next element in the series. Once the end is reached and in succeeding
calls for the next item, the method shouldprompt a StopIteration message.
>>>x = MultThree(6)
>>> n = iter(x)
>>>next(n)
1
>>>next(n)
3
>>>next(n)
9
>>>next(n)
27
>>>next(n)
81
>>>next(n)
243
>>>next(n)
729
>>>next(n)
Traceback (most recent call last):
File “<pyshell#9>”, line 1, in<module>
next(i)
File “C:/AppData/Local/Programs/Python/Python35-32/Mult_Three.py“, line 18, in
__next__
raise StopIteration
StopIteration
Step 23: Python Generators
Building your own iterator can be a tedious and lengthy process. You will have to
implement a class with the iterator protocol and raise StopIteration when you’ve come to
the end of the file. This counter intuitive steps can be avoided when you use generators.
def gen_function():
“““define generator function”””
x = 5
print(“This is the initial value.”)
# The gen_function has multiple yield expressions
yield x
x += 5
print(“This is the second value.”)
yield x
x += 5
print(“This is the final value.”)
yield x
>>>g = gen_function()
>>>next(g)
This is the initial value.
5
>>> next(g)
This is the second value.
10
>>>next(g)
This is the last value.
15
>>>
You will notice that unlike normal functions where local variables are destroyed as the
function returns, the local variables in a generator function are retained between calls. In
addition, you can only iterate over a generator object once. You will have to define a new
generator object if you want to restart the iteration process. That is, you’ll make another
assignment such as x = gen_function.
Step 24: Files
File is a named disk location which is used to store related data. You will usually want to
reuse your data in the future and to do so, you have to store them in memory through a
file. In Python, file management is done using a file object.
Attribute Returns:
file.name the name of the file
file.mode the access mode used to open the file
file.closed True if close, False if open
For example:
label = open(“names.txt”, “w”)
print (“Filename: “, label.name)
print (“Closed or Not : “, label.closed)
print (“Opening Mode : “, label.mode)
label.close()
Filename: names.txt
Closed or Not : False
Opening Mode : w
>>>
File Operations
There are 4 basic file-related operations in Python:
opening a file
reading from a file
writing to a file
closing a file
file object=open(filename [, access_mode][, buffering])
The filename is the string that represents the name of the file that you want to access.
The access mode is an optional parameter that allows you to indicate the mode in which
you want to access the file. Options include read, write, or append. You can also specify
whether you want the file to be opened in either binary or text mode. The text mode
supports working with strings while the binary mode returns bytes and allows access to
non-text files such as images or exe files. The default access modes are read mode and text
mode:
Buffering allows users to specify their preferred buffering. No buffering takes place when
the value is at zero. When the buffering value is one, line buffering is done as you access
files. When the value is greater than one, the buffering process is implemented according
to the given buffer size. A negative value tells Python to implement the system default.
r Read mode (default): opens a file for reading.
Write museode: overwrites an existing file or creates a new file if the file does not
w
exist.
r+ Read and write mode.
Read and write mode: overwrites an existing file or creates a new one if the file does
w+
not exist.
Append mode: adds data at the end of the file, creates a new file if the file does not
a
exist.
Read and append mode: adds data at the end of the file, creates a new file if the file
a+
does not exist.
x Opens file for exclusive creation, fails if the file already exists.
rb+ Read and write mode.
Read and write mode: overwrites an existing file or creates a new file if
wb+
the file does not exist.
Read and append mode: adds data at the end of the file or create a new
ab+
file if the file does not exist.
Examples:
>>>f = open(“access.txt”)
>>>f = open(“access.txt”,‘w’)
Writing to a File
If you want to modify or write something into a file, you have to open the file in append
mode, write mode, or in exclusive creation mode. You should exercise caution when
choosing the mode as specifying a wrong mode can easily cause your file and the data
stored to be erased or overwritten.
Closing a File
When you’re done with your work, it’s important to close your files properly to free up the
resources used and to avoid accidental deletion or modification. Closing your file properly
is a way of telling Python that you’re done with your editing or writing work and that it is
time to write data to your file.
fileobject = open(“trial.txt”,encoding = ‘utf-8’) # open trial.txt file
fileobject.close()
By opening the file “newfile.txt” in “w” (write) mode, you are telling Python to overwrite
any data stored in the file, if any. This also means that you’ll be starting over with an
empty file. The file was closed properly using the close() method.
To build your file, open the newfile.txt again using “w” mode:
>>>f = open(“newfile.txt”,“w”)
Use the write() method to write the following strings on the file:
Take note that the Python Shell returns a number every time you enter a statement with the
write() method. The number refers to the number of characters written to a file.
When you’re done writing to the file, don’t forget to close the file with the close() method:
f.close()
Reading a Python File
There are several ways to read a text file in Python. Here are the most common ones:
Create a variable, ‘lines’ that will store text lines from the readlines() method:
>>>lines = f.readlines()
>>> lines
[‘A file can hold important information.’]
>>>
>>>f.close()
>>>
You probably noticed that the write() method does not use line breaks and simply writes
whatever you type and enter. Hence, what you got in the above example is a paragraph. If
you want to write your strings on a line by line basis, you can try encoding a new line
character, “\n” at the end of each string. For example:
To illustrate both methods, you need to create a text file that will store data on a per line
basis using a new line character at the end of a string.
>>> f.close()
Line by Line Reading of Text Files with the ‘while’ loop
Here is a simple loop that you can use to read a Python file on a per line basis:
f = open(‘linefile.txt’, ‘)
line = f.readline()
Keep reading line one at a time until file is empty:
while line:
print line
line = f.readline()
f.close()
When you run the program, here’s what you should see on the Python Shell:
f = open(‘linefile.txt’)
for line in iter(f):
print line
f.close()
The ‘with statement’ can be used to read through the lines of a file. The ‘with structure’
allows you to open a file safely and let Python close it automatically without using the
file.close() method.
Example:
The following code creates newfile.txt in write mode, writes 4 lines of text, and closes the
file:
To read each line in the file using the ‘with pattern’, you can use the following statements:
line_num = 0
with open(‘newfile.txt’, ‘r’) as f_file:
for line in f_file:
line_num += 1
print(‘{:>3} {}’.format(line_num, line.rstrip()))
The ‘with pattern’ makes use of the ‘for loop’ to read the files line by line. This shows that
the file object is an iterator that can produce a line when you require a value. The ‘line’
variable holds the entire line content including carriage returns.
You can use the format() string method with the print() function if you want your program
to print out each line and the corresponding line number. You can even specify how the
line number should appear by using format specifiers. In the above code, the specifier
{:>3} tells Python to print the argument (line_num for line number) right-justified inside 3
spaces. The rstrip() method is used to remove trailing whitespaces as well as carriage
return characters.
If you run the program, here’s what the output would be:
f = open(‘linefile.txt’)
for x in iter(f):
print(x)
f.close()
Did you guess how easy it is to append data to a saved text file?
Renaming a File
Python’s os module offers some methods that can be used to perform various file
operations such as deleting and renaming files.
Before you can use the os module, you’ll need to import it with the syntax:
import os
os.rename(current_filename, new_filename)
Example:
import os
Deleting a File
To delete an existing file, you can use the remove() method which, like rename(), can be
called from the os module. The remove() method takes only one argument and has the
following syntax:
os.remove(file_name)
Example:
import os
# Delete file2.txt
os.remove(“file2.txt”)
Binary Files
Files are not limited to text. They may also contain images or binary files.
To open binary files, you will use the same syntax you use for opening text files except
that this time, you have to use the binary mode which is denoted by the letter ‘b’.
The file object of a file opened in binary mode possess most of the attributes of a file
object created from opening a text file. It has the mode and name attributes. Unlike a text
file, however, it has no encoding attribute. That’s because binary files, unlike text files,
require no conversion. What you save into it is exactly what you will get.With a binary
file, you will be reading bytes, in contrast to reading strings in a text file. Python will raise
an AttributeError if you try to use a non-existent encoding attribute.
>>> mypict.name
c:/doggie.jpg’
>>> mypict.mode
‘rb’
When you use the read() method in binary mode, any number you put in as a parameter
will refer to the amount of bytes that would be read.
To illustrate, this statement opens an image file beach.jpg in binary read mode and creates
a file object mypict:
The next statement uses the read() method on mypict and supplies 5 as argument.
>>> info
b’\xff\xd8\xff\xe0\x00’
The tell() method returns the number of bytes that has been read. Since you have specified
5 bytes to read, Python returns the same number of bytes.
>>> mypict.tell()
5
>>> mypict.seek(0)
0
To read the entire image file, use the read() method on mypict with no arguments:
You can enter info on the >>>prompt to view the contents of the entire file but that will
probably be a pageful of strange letter combinations. Instead, you can use len() to see the
total number of bytes read and stored in the variable info:
>>> len(info)
3893
File Methods
Python has several file methods that can be used to handle files. The most commonly used
methods are summarized below:
File.writer(str)
Writes stringo to a file
The syntax is:
fileobject.write(str)
Example:
fileobject.writelines(sequence)
Example:
sequence = [“The club now has 100 members.\n”, “I am the 100th member.”]
# Close file
fileobj.close()
Filename: my_file.txt
Line No 0 - I am a new member.
File.readline(size)
Reads an entire line from file
Thesyntax is:
fileobject.readline(size)
Size is an optional parameter that you can use if you want to specify the number of bytes
that should be read.
Example:
Assuming that you have created a text file named alphabet.txt and that you have
performed a write operation on the file to write several lines:
# Open a file.
fileobj = open(“alphabet.txt”, “r+”)
print (“Filename: “, fileobj.name)
lines = fileobj.readline()
print (“Read Line: %s” % (lines))
lines = fileobj.readline(14)
print (“Read Line: %s” % (lines))
lines = fileobj.readline()
print (“Read Line: %s” % (lines))
lines = fileobj.readline(18)
print (“Read Line: %s” % (lines))
# Close file
fileobj.close()
Filename: alphabet.txt
Read Line: There are 26 letters in the alphabet.
File.readlines()
Reads until end-of-file using readline()
fileobject.readlines(sizehint)
The readlines() method returns a list that contains the lines. By default, it reads until EOF
but it has an optional argument, sizehint, that can be used to instruct Python to read whole
lines approximating the given sizehint bytes. It returns an empty string when the EOF is
reached immediately.
Example:
A dictionary is mutable.
A tuple is immutable.
A string is immutable.
A list is mutable.
Strings, lists, and tuples are sequence types.
# Open myfile
fileobject = open(“myfile.txt”, “r+”)
print (“Filename: “, fileobject.name)
lines = fileobject.readlines(2)
print (“Read Line: %s” % (lines))
lines = fileobject.readlines()
print (“Read Line: %s” % (lines))
# Close file
fileobject.close()
Filename: myfile.txt
Read Line: [‘A dictionary is mutable.\n’]
Read Line: [‘A tuple is immutable.\n’, ‘A string is immutable.\n’, ‘A list is mutable\n’,
‘Strings, lists, and tuples are sequence types.\n’]
Here’s what happens when you tweak the code and use an argument on the first
readlines():
# Open myfile
fileobject = open(“myfile.txt”, “r+”)
print (“Filename: “, fileobject.name)
lines = fileobject.readlines()
print (“Read Line: %s” % (lines))
lines = fileobject.readlines(3)
print (“Read Line: %s” % (lines))
Filename: myfile.txt
Read Line: [‘A dictionary is mutable.\n’, ‘A tuple is immutable.\n’, ‘A string is
immutable.\n’, ‘A list is mutable\n’, ‘Strings, lists, and tuples are sequence types.\n’]
Read Line: []
The syntaxis:
fileobject.tell()
Example:
The alphabet.txt file described in the preceding example contains the following lines:
lines = fileobj.readline()
print(“Read Line: %s” % (lines))
pos = fileobj.tell()
print(“Current Position: ” ,pos)
# Close file
fileobj.close
Filename: alphabet.txt
Read Line: There are 26 letters in the alphabet.
Current Position: 39
File.seek()
Sets file’s current locatopm at offset
The syntaxis:
fileobject.seek(offset[, from])
offset
from
From is an optional parameter which has zero(0) as default. There are three possible
values for whence:
Take note that if you open a file for appending with either ‘a’ or ‘a+’, any seek() operation
is nullified on the next write operation. If you open a file for writing in append mode with
‘a’, the method is not operable. On the other hand, if you open a file in text mode with ‘t’,
the only valid offsets are those returned by tell().
Example:
This is line 1 of 5.
This is line 2 of 5.
This is line 3 of 5.
This is line 4 of 5.
This is line 5 of 5.
# Open a file
fileobj = open(“newfile.txt”, “r+”)
print (“Filename: “, fileobj.name)
lines = fileobj.readlines()
print (“Read Line: %s” % (lines))
# Close file
fileobj.close()
Filename: newfile.txt
Read Line: [‘This is line 1 of 5.\n’, ‘This is line 2 of 5.\n’, ‘This is line 3 of 5.\n’, ‘This is
line 4 of 5.\n’, ‘This is line 5 of 5.\n’]
Read Line: This is line 1 of 5.
File.read(n)
Reads size bytes from a file
fileobject.read(size)
Example:
A string is a sequence.
Strings and tuples are immutable.
A list is a mutable sequence.
Python offers many file methods.
The os module has useful methods for directories.
This program shows how the read() method is used to display piecemeal string:
# Open a file
fileobj = open(“myfile.txt”, “r+”)
print (“Filename: “, fileobj.name)
lines = fileobj.read(35)
print (“Read Line: %s” % (lines))
# Close file
fileobj.close()
Filename: myfile.txt
Read Line: A string is a sequence.
Strings and
File.truncate([size])
Resizes the file
The syntaxis:
fileObject.truncate( [ size ])
The truncate() method truncates the size of the file. It has an optional argument for size
which, if given, will be used as the basis for truncating the file. If size is not provided, the
default is the current position. The truncate() method will not work for files which are
opened in ‘read only’ mode.
Example:
This example makes use of the file linefile.txt which contains the following lines:
lines = fileobject.readline()
print (“Read Line: %s” % (lines))
fileobject.truncate()
lines = fileobject.readlines()
print (“Read Line: %s” % (lines))
# Close file
fileobject.close()
Filename: linefile.txt
Read Line: This is the first
Read Line: []
File.flush()
Flushed the internal buffer
fileobject.flush()
# Open a file
fileobject = open(“onefile.txt”, “wb”)
print (“Filename: “, fileobject.name)
# The method() returns none but can be called with the read operations
fileobject.flush()
# Close file
fileobject.close()
Filename: onefile.txt
File.close()
Closes an open file
The syntax is:
fileobject.close()
# Open a file
fileobject = open(“myfile.txt”, “wb”)
print (“Filename: “, fileobject.name)
# Close file
fileobject.close()
File.isatty()
Returns True it file if attached to a try to a tty or similar device and False
if otherwise.
fileobject.isatty()
Example:
# Open a file
fileobject = open(“myfile.txt”, “wb”)
print (“Filename: “, fileobject.name)
val = fileobject.isatty()
print (“Return value : “, val)
# Close file
fileobject.close()
Since the file is not attached to any tty or tty-like device, the output will be:
Filename: myfile.txt
Return value : False
File.fileno()
Returns integer file descriptor
The operating system keeps tab of all opened files by creating a unique entry to represent
each file. These entries are called file descriptors and are represented by integers.
fileobject.fileno()
Example:
# Open a file
fileobject = open(“myfile.txt”, “wb”)
print (“Filename: “, fileobject.name)
filenum = fileobject.fileno()
print (“File Descriptor: “, filenum)
# Close file
fileobject.close()
Errors are quite common in programming and they fall into two major types: syntax errors
and runtime errors.
Syntax Errors
Errors caused by non-compliance with the language structure or syntax are called syntax
or parsing errors.
misspelled keywords
incorrect indentation
omission of a required keyword or symbol
placement of keywords in wrong places
an empty block
Examples:
for n in num[4, 19, 25, 50, 26, 75] #print statement should have been indented
if x == 50: #because it is inside the if block
print(“Enter a password!”)
Runtime Errors
Errors that occur during runtime are called exceptions. If unsolved, a runtime error may
cause a program to crash or terminate unexpectedly. Common runtime errors include
IndexError (for index which is out of range), KeyError (when key is not found) or
ImportError (for missing import module). Python creates an exception object every time it
encounters an exception and displays a traceback to the error if it’s not managed.
Here are examples of exceptions:
Built-in Exceptions
Python has several built-in exceptions and they are raised whenever a runtime error
occurs:
One way of managing a Python exception is by using “try and except statements”. Critical
parts of the program that are likely to cause exceptions are placed within the ‘try’ clause
while the exception code is given inside the ‘except’ clause.
For example:
try:
num = int(input(“Please enter a number between 0 and 15: “))
print(“You entered %d.” % num)
except ValueError:
print(“That’s not a number! Please try again.”)
Python will try to execute all statements in the ‘try’ block. If a ValueError is encountered,
control immediately passes to the ‘except’ block. Any unprocessed statement in the ‘try’
block will be ignored. In this case, a ValueError exception was given to handle non-
numeric responses.
try…finally
A try statement can also include a “finally” clause. The “finally” clause is always executed
regardless of the actions done about the program error. It is also used to clean and release
external resources.
try:
num = int(input(“Please enter a number between 0 and 15: “))
print(“You entered %d.” % num)
except ValueError:
print(“That’s not a number! Please try again.”)
else:
print((“That will be your meal stub number.”)
finally:
print((“Great! Don’t forget to claim your meals.”)
Python Cheat Sheets
To help with your learning you can download and print this Cheat Sheet from our website.
We offer two different ways to download it;
You can open it through Microsoft Word, edit it as you wish and print it.
Or you can also download it as it is and print it.
Variable Assignment
string = “string”
integer = 1
list = [ item1, item2, item3, … ]
tuple = (item1, item2, item3, …)
dictionary = { key1 : value1, key2 : value2, key3 : value3 … }
mutli_line_string = “““ multi-line string”””
unicode_string = “unicode string”
class_instance = ClassName (init_args)
Python Operators
Arithmetic Operators
Addition x = a + b 5 + 10 → 15
Subtraction x = a – b 15 – 10 → 5
Multiplication x = a * b 5 * 10 → 50
Division x = a / b 15 / 3 → 5
Modulos x = a % b 11 % 3 → 2
Floor Divison x = a // b 11 // 3 → 3
Assignment Operators
Assigns the value of the right operand to c = a + b assigns value of a
= assignment
the left operand. + b into c
It adds right operand to the left operand c += a is equivalent to c = c
+= add and
and assign the result to left operand + a
It subtracts right operand from the left
subtract c -= a is equivalent to c = c -
-= operand and assign the result to left
and a
operand
It multiplies right operand with the left
multiply c *= a is equivalent to c = c
*= operand and assign the result to left
and * a
operand
It divides left operand with the right c /= a is equivalent to c = c /
/= divide and operand and assign the result to left ac /= a is equivalent to c = c
operand / a
Performs exponential (power) calculation
** exponent c **= a is equivalent to c = c
on operators and assign value to the left
= and ** a
operand
floor It performs floor division on operators and c //= a is equivalent to c = c
//=
division assign value to the left operand // a
Modulus It takes modulus using two operands and c %= a is equivalent to c = c
%= and
assign the result to left operand % a
Relational Operators
2 < 10 is less than
5 > 3 is greater than
4 <= 2+2 is less than or equal to
2 * 5 >= 2 * 3 is greater than or equal to
10 ==2 * 5 is equal to
18 != 2 * 6 is not equal to
Logical Operators
or (12 > 9) or (15 < 10)→ True (4 > 14) or (8 < 5) → False
and (10 > 2 ) and (15 > 5) → True (5 > 2 ) and (12 > 20) → False
not not (6 > 3 ** 5) → True not (6 < 4 ** 4) → False
Identity Operators
Verifies if the left and right operands refer to the same memory location:
is a = 8, b = 8 a is b → True
is not x = 5, y = 10 a is not b → True
Membership Operators
Bitwise Operators
Assuming x = 15 and y = 10
& Bitwise AND x & y → 10 bin(10) → ‘0b1010’
| Bitwise OR x | y → 15 bin(15) → ‘0b1111’
^ Bitwise XOR x ^ y → 5 bin(5) → ‘0b101’
~ Bitwise NOT ~ x → -16 bin(-16) → ‘-0b10000’
<< Bitwise left shift x << 2 → 60 bin(60) → ‘0b111100’
>> Bitwise right shift y >> 2 → 2 bin(2) → ‘0b10’
Strings
s = ‘new string’ Creates ‘new string’ in single quotes.
s = “new string” Creates “new string” in double quotes.
s = “““Hello, world””” Creates a string “““Hello,world””” in triple quotes.
y=x.replace(“old”,“new”,1) Replaces 1 st occurrence of “old” string with “new string”.
n = len(str) Stores the length (no. Of characters) of a string to n.
“abc” in str Checks if a given substring exists in a string .
“%s%s” % (“prog”,
→ ‘program’
“ram”)
print(“string”) → string
str.split(“delim”, limit) “a/t”.split(“/”) → [‘a’, ‘t’]
str.upper() Returns a view of a string in uppercase.
str.lower() Returns a view of a string in lower case.
Returns a view of a string where the first letter of every word
str.title()
is capitalized, the rest are in lowercase.
Sum the occurrence of a character or series of character in a
str.count(“a”)
string.
Searches for a character or series of characters, returns the
str.find(“abc”)
index number.
str.isalpha() Checks if a string is alphabetic.
str.isalnum() Checks if a string is alphanumeric.
str.isidentifier() Checks if a string is a valid identifier.
str1.join(seq) Concatenates a string with a sequence of string.
Returns the string without leading characters or
whitespaces.
str.lstrip()
Returns the string without trailing characters or
str.rstrip()
whitespaces.
Returns the string without leading and trailing characters or
str.strip()
whitespaces.
Checks the occurrence of a given substring and returns its
str1.index(str2, beg, end)
index.
Searches for the last occurrence of a given substring and
str1.rindex(str2, beg, end)
returns its index.
str.zfill(width) Returns a string with leading zeros within the given width.
Returns right-justified string within a given width, has
str.rjust(width[, fillchar])
optional fill character.
Returns left-justified string within a given width, takes
str.ljust(width[, fillchar])
optional fill character.
Returns center-justified string within a given width, takes
str.center(width[, fillchar])
optional fill character.
str.endswith(“suffix”) Checks whether a string ends in a given suffix.
str.startswith(“prefix”) Checks whether a string ends in a given prefix.
string1 + string2 “prog” + “ram” → ‘program’
Lists
L = [“a”, 1, “X”, 4.5,] list creation
L[0] access the first element
L[0:2] access the first two elements
L[-4:] access the last four elements
L[1:4] = [“e”, 10, “o”] replace elements on index 1 to 3 with given values
del L[3] remove list element on given index
len(L) returns the number of items on a list
max(L) returns the largest item on a list
min(L) returns the smallest item on a list
sum(L) returns the total value on list
list() converts an iterable to a list
L.append(a) adds a given value to list L
L.extend(L2) adds elements in L2 to L, same as L3 = L + L2
L.remove(a) a is a value you want to remove from list L
L.sort() sort a list containing elements of the same type
searches for a value and returns number of
L.count(“e”)
occurrence
L.reverse() sorts a list in the reverse (descending) order
L.pop() simple stack, removes the last element
L.index(a) index of first occurrence of a given value
a in L membership test: does L contain a? True or False
[x*3 for x in L if x>4] list comprehension
Tuple
x = 1, 2, 3, 4, 5
x = (1, 2, 3, 4, 5)
x = (1, 2, 4, “a”, “b”, “c”)
x = (“book”, (1, 3, 40), [8, 4, 7])
x = (“student”,)
x = ()
1, 2, 3, 4, 5 = x
x[3] # access element on index 3
x[4:7] # access element on indices 4 to 6
del x # delete tuple x
‘g’ in my_tuple # membership test, returns True or False
mytuple.count(a) returns the number of elements equal to given value
mytuple.index(a) returns index of the first element equal to given value
len(mytuple) returns the number of elements in a tuple
max(mytuple) returns the largest element in a tuple
min(mytuple) returns the smallest element in a tuple
sorted(mytuple) returns a view of a sorted tuple
sum(mytuple) returns the total of all items in a tuple
tuple() converts an iterable to a tuple
Dictionary
D = {‘key1’: 15, ‘key2’: ‘xyz’, ‘key3’: 78.50
creates a dictionary
}
D = dict(‘key1’=15, ‘key2’=‘xyz’,
creates a dictionary
‘key3’=78.50)
D = {} creates an empty dictionary
keys = (‘x’, ‘y’, ‘z’)
creates dict2 from a list of tuple key-value
dict2 = dict(pairs)
pairs
D = dict.fromkeys(keys) create new dictionary with no values
for k in D: print(k) iterates over dictionary keys
my_dict[‘Age’] accesses the value of the given key
my_dict.get(‘Name’) uses the get() method to access a value
my_dict[‘Age’] = 24 adds a new key and value to a dictionary
my_dict[‘Age’] = 20 modifies the value of a given key
my_dict.pop(‘Name’) removes the given key and its value
method that removes a random key-value
my_dict.popitem()
pair
removes all key-value pairs from
my_dict.clear()
dictionary
del my_dict deletes a dictionary
updates dict1 with key-value pairs from
dict1.update(dict2)
dict2
returns a list of a dictionary’s key-value
dict.items()
pairs
dict.values() returns a list of all dictionary values
dict.keys() returns a list of dictionary keys
dict.setdefault(‘a’, None) searches for a given value in dictionary
dict_2 = dict_1.copy() creates a copy of dict_1 dictionary
squares={x:x*3 for x in range(5)} dictionary comprehension
takes items in sequence and uses them as
newdict = dict.fromkeys(L, 3)
keys
3 in a_dict dictionary membership test
len(a_dict) returns the number of items in a dictionary
for x in dict.values(): print(x) prints values
for x, y in dict.items(): key-value tuples
list(dict.keys()) dictionary keys in list form
sorted(dict.keys()) sorted dictionary keys in list form
Sets
my_set = {2, 4, 6, 8, 10}
my_set = {‘x’, ‘y’, ‘z’, a’, ‘e’}
my_set = set()
my_set = {10.0, “Python”, (9, 7, 5), 5}
Set_a = {2, 4, 6} List_1 = [2, 5, 4, 1, 6] S = set(List_1) # set ([1,2,4,5,6])
set([5,4,3, 1 ]) creates set from a list
my_set.add(12) adds an element to a set
my_set.update([1, 3, 5])
my_set.discard (‘x’) removes an element from a set
my_set.remove (‘f’) removes an element from a set
my_set.pop() removes a random item and returns it
my_set.clear() removes all elements of a set
X | Y union: combines the elements of X and Y
X.union(Y) combines the elements of X and (
x & y intersection: combines common elements of X and Y
x.intersection(y) method that combines common elements of X and Y
x – y difference: set of elements found in x but not in y
x.difference(y) returns a set of elements found in x but not in y
x ^ y set of elements that are not common in x and y
b.symmetric_difference(a)
‘s’ in my_set set membership test
len(my_set) returns the number of elements on a set
max(my_set) returns the largest element on a set
min(my_set) returns the largest element on a set
sorted(my_set) returns a sorted view of a set
sum() returns the total of all items in a set
Loops
for num in range(4): # 4 numbers starting from zero: 0,1,2,3
for num in range(0, 10, 3): # start, end, progression: 0,3,6,9
for num in range(0, 9): # start, end: 0,1,2,3,4,5,6,7,8
for a, z in dict.letters(): # dict[key1] = 50 dict[key2] = 100
print(“dict[{}]={}”.format(a,z))
num_list = [2, 4, 6, 8]
for a, z in zip(List_1, List_2): # return tuple pairs
for index, value in enumerate(num_list): # index, value
for x in sorted(set(num_list)): # set sorted from num_list
for val in reversed(num_list): # reverse sort of num_list
Conditional Statements
if…else
if a > 90:
print(“Good job!”)
else:
print(“Please try again!”)
if…elif…else
if x > 20:
print(“Sorry, you have exceeded the limit.”)
elif x > 12:
print(“You have a chance to join the jackpot round.”)
else:
print(“You may roll the dice again.”)
Built-in Functions
range(n1, n2, step) creates a list with arithmetic progression
input() x = input(“Enter a number: “) takes user’s input
print(x) prints the given value
abs(n) returns absolute value of integers or floats
max(x) returns the largest value among two or more numeric data
min(x) returns the smallest value among two or more numeric data
type() returns the data type of given argument
User-Defined Functions
To define a function
def function(parameters): def adder(num):
“““docstring””” ”““Function that adds numbers”””
function body function body
Classes
To define a class:
class ClassName:
“““This is a new class.”””
b = “apple”
def greet(self):
print(‘Hello, World!’)
Files
f = open(“trial.txt”, “w”) # open options: r , r+, rb, rb+, w, wb
f.write(“I’m a string.\n”)
f.close()
L = open(“trial.txt”).readlines() # returns list of lines
for line in open(“trial.txt”): print(line, end=””)
File Operations
fileobj = open(“myfile”,
creates fileobj, opens myfile on write mode
“w”)
fileobj.write(“string”) writes ‘string’ to file
fileobj.writelines(“I am
writes a sequence of strings
me./n”)
reads an entire line, takes an optional argument for
fileobj.readline()
byte size
reads all lines until EOF, takes an optional sizehint
fileobj.readlines()
argument
fileobj.tell() returns the position of the file pointer
fileobj.seek(offset[from]) sets file pointer’s current position at offset
fileobj.read(n) reads size bytes from file
truncates the file, takes an optional agreement for
fileobj.truncate(size)
size
fileobj.flush() flushes the internal buffer
fileobj.close() closes an open file
fileobj.isatty() checks if file is attached to a tty device
fileobj.fileno() return an integer file descriptor
Date and Time
import time
formatted time:
time_now=time.asctime(time.localtime(time.time()))
→ Thu Jun 30 01:22:15 2016
from datetime import datetime
datetime.now()
from time import strftime
strftime(“%Y-%m-%d %H:%M:%S”) → ‘2016-07-08 02:35:02’
Python Modules
import module Imports a Python module.
import math Imports the math module.
math.sqrt(n) Math.sqrt(100) → 25
math.gcd(n1, n2) Math.gcd(12, 14) → 2
math.fabs(n) Math.fabs(-15) → 15.0
import random Imports Python’s random module.
random.randint(1, 12) returns a random integer from 1 to 12.
random.choice([‘a’, 1, 2])Returns a random value from a given list.
Rort and arranges items in a list in a random
random.shuffle(([1, 2, 3])
order
import time Imports Python’s time module.
time.localtime() Returns time in tuple format.
import calendar Imports Python’s calendar module.
calendar.month(2016, 7) Imports calendar for July 2016.
calendar.calendar(year, w=2, l=1, c=6)
Imports calendar for the year.
calendar.firstweekday( ) Sets first day of the week, default is Monday.
Help!
Oh no, you’re stuck! Chances are that someone else had the same problem you’re having
and has written about it online. Here are some great ressources you can use to find
answers to your questions.
Google
You can simply google the exact error message you are getting. For example:
>>> a.attr
Attempting to access the non-existent object a.attr will raise the AttributeError:
FAQ
Python.org offers many answers to many common general questions. To read about
Python Frequently Asked Questions <click here>.
If you are stuck and searching online isn’t proving helpful, then you might try asking
someone in an IRC channel. IRC is a chat system where people around the world
communicate live. You can create your own account by going to
www.webchat.freenode.net. To join the main Python channel, you must enter /join
#python in the input box.
Other Best Selling Books You Might Like!
Read this Step by Step book to easily understand Excel 2016 in no time! Click <here> to
see my book and click on it’s cover to see the first pages!
Read this Step by Step book to easily understand Windows 10 in no time! Click <here> to
see my book and click on it’s cover to see the first pages!
Conclusion
I hope that this book was able to help you to learn the fundamentals of Python
programming quickly and easily. By now, I know that you can make useful, practical
programs that will automate many of your daily tasks at work and at home.
The next step is to take up advanced Python programming courses that can help you create
more powerful programs.
If you happened to like my book please leave me a quick review on Amazon. I personally
read every single comment on the site. Your feedback is very important to me as it will
help improve the book and ensure your satisfaction.
Thank you!
Joe Thompson
Table of Contents
Introduction
An Overview of Python
Step 1: Installing Python
Installing Python in Windows
Which version should I use?
Installing Python in Mac
Running the Installation file
Starting Python
IDLE versus the command line interface (CLI)
IDLE
The Command Line Interface (CLI)
Different ways to access Python’s command line
If you’re using Windows
If you’re using GNU/Linux, UNIX, and Mac OS systems
Step 2: Working with IDLE
The Python Shell
The File Menu
The Edit menu
The Shell Menu
The Debug Menu
The Options Menu
The Window Menu
The Help Menu
Writing your First Python Program
Accessing Python’s File Editor
Typing your code
Saving the File
Running the Application
Exiting Python
Step 3: Python Files and Directories
The mkdir() Method
The chdir() Method
The getcwd() Method
The rmdir() Method
Step 4: Python Basic Syntax
Python Keywords (Python Reserve words)
Python’s Identifiers
Five rules for writing identifiers
A Class Identifier
Naming Global Variables
Naming Classes
Naming Instance Variables
Naming Modules and Packages
Naming Functions
Naming Arguments
Naming Constants
Using Quotation Marks
Statements
Multi-line statements
Indentation
Comments
Docstring
Step 5: Variables and Python Data Types
Variables
Memory Location
Multiple assignments in one statement
Assignment of a common value to several variables in a single statement
Data Types
Boolean Data Type
Step 6: Number Data Types
Integers (int)
Normal integers
Octal literal (base 8)
Hexadecimal literal (base 16)
Binary literal (base 2)
Converting Integers to their String Equivalent
integer to octal literal
integer to hexadecimal literal
integer to binary literal
Floating-Point Numbers (Floats)
Complex Numbers
Converting From One Numeric Type to Another
To convert a float to a plain integer
To convert an integer to a floating-point number
To convert an integer to a complex number
To convert a float to a complex number
To convert a numeric expression (x, y) to a complex number with a real number and
imaginary number
Numbers and Arithmetic Operators
Addition (+)
Subtraction (-)
Multiplication (*)
Division ( /)
Exponent (**)
Modulos (%)
Relational or Comparison Operators
Assignment Operators
= Operator
add and +=
subtract and -=
multiply and *=
divide and /=
modulos and %=
floor division and //=
Bill Calculator
Built-in Functions Commonly Used with Numbers
abs(x)
max()
min()
round()
Math Methods
Math.ceil(x)
Math.floor(x)
Math.fabs()
Math.pow()
Math.sqrt()
Math.log()
Step 7: Strings
Accessing Characters in a String
String Indexing
The Len() Function
Slicing Strings
Concatenating Strings
Repeating a String
Using the upper() and lower() functions on a string
Using the str() function
Python String Methods
The replace() method
Case Methods with String
Upper()
Lower()
Swapcase()
Title()
Count() method
The find() method
Isalpha()
Isalnum()
Isidentifier()
The join() method
Lstrip() method
Rstrip() method
Strip([chars])
Rfind() method
Index() method
Rindex() method
Zfill() method
Rjust() method
Ljust() method
Center() method
Endswith() method
Startswith() method
Iterating Through a String
Step 8: Output Formatting
The print() function
Using the str.format() method to format string objects
Other Formatting Options
‘<’
‘>’
‘^’
‘0’
‘=’
Step 9: Lists
Accessing Elements on a List
Indexing
Negative Indexing
Slcing Lists
Adding Elements to a List
Changing Elements of a List
Concatenating and Repeating Lists
Inserting Item(s)
Removing or Deleting Items from a List
Sorting Items on a List
Using the count() Method on Lists
Testing for Membership on a List
Using Built-in Functions with List
Len()
Max()
Min()
Sum()
Sorted()
List()
Enumerate()
List Comprehension
Step 10: Tuples
How to Create a Tuple
Accessing Tuple Elements
Indexing
Negative Indexing
Slicing a Tuple
Changing, Reassigning, and Deleting Tuples
Replacing a Tuple
Reassigning a Tuple
Deleting a Tuple
Tuple Membership Test
Python Tuple Methods
Count(x)
Index(x)
Built-in Functions with Tuples
Len()
Max()
Min()
Sorted()
Sum()
Tuple()
Enumerate()
Iterating through a Tuple
Tuples vs. Lists
Step 11: Sets
Creating a Set
Changing Elements on a Set
Removing Set Elements
Set Operations
Set Union
Set Intersection
Set Difference
Set Symmetric Difference
Set Membership Test
Using Built-in Functions with Set
Len()
Max()
Min()
Sorted()
Sum()
Enumerate()
Iterating Through Sets
Frozenset
Step 12: Dictionary
Accessing Elements on a Dictionary
Adding and Modifying Entries to a Dictionary
Removing or Deleting Elements from a Dictionary
The pop()method
The popitem() method
The clear() method
Other Python Dictionary Methods
Update(other)
Item() method
Values() method
Keys() method
Setdefault() method
Copy() method
The fromkeys() method
Dictionary Membership Test
Iterating Through a Dictionary
Using Built-in Functions with Dictionary
Lens()
Sorted()
Creating a Dictionary with the dict() function
Dictionary Comprehension
Step 13:Python Operators
Arithmetic Operators
Assignment Operators
Relational or Comparison Operators
Logical Operators
Identity Operators
Membership Operators
Bitwise Operators
Understanding the Base 2 Number System
Precedence of Operators
Step 14:Built-in Functions
The range() function
The input() Function
Password Verification Program
Using input() to add elements to a List
The print() Function
abs()
max()
min()
type()
Step 15: Conditional Statements
if statements
if…else statements
if…elif…else statements
nested if…elif…else statements
Step 16: Python Loops
The for Loop
For Loop with string:
For Loop with list
for loop with a tuple
Using for loop with the range() function
The While Loop
Break Statement
Continue Statement
Pass Statement
Looping Techniques
Infinite loops (while loop)
Loops with top condition (while loop)
Loops with middle condition
Loops with condition at the end
Step 17: User-Defined Functions
1. def keyword
2. function name
3. parameters
4. colon (:)
5. docstring
6. statement(s)
7. return statement
Calling a Function
Using functions to call another function
Program to Compute for Weighted Average
Anonymous Functions
Lambda functions with map()
Lambda functions with filter()
Recursive Functions
Scope and Lifetime of a Variable
Step 18: Python Modules
Importing a Module
Python’s Math Module
Displaying the Contents of a Module
Getting more information about a module and its function
The Random Module
Usage of Random Module
Random Functions
Universal Imports
Importing Several Modules at Once
Step 19: Date and Time
Formatted Time
Getting Monthly Calendar
The Time Module
The Calendar Module
calendar.firstweekday( )
calendar.isleap(year)
calendar.leapdays(y1, y2)
calendar.month(year, month, w=2, l=1)
calendar.monthcalendar(year, month)
calendar.monthrange(year, month)
calendar.prmonth(year, month, w=2, l=1)
calendar.setfirstweekday(weekday)
calendar.weekday(year, month, day)
Datetime
Step 20: Namespaces
Scope
Step 21: Classes and Object-Oriented Programming
Defining a Class
Creating an Object
The __init__() method
Instance Variables
Adding an attribute
Deleting Objects and Attributes
Modifying Variables within the Class
Inheritance
Multiple Inheritance
Multilevel Inheritance
Step 22: Python Iterators
Creating a Python Iterator
Step 23: Python Generators
Step 24: Files
The File Object Attributes
File Operations
The Open() function
Writing to a File
Closing a File
Opening, Writing to, and Closing a Text File
Reading a Python File
The readlines() method
Line by Line Reading of Text Files with the ‘while’ loop
Line by Line Reading of Text Files using an Iterator
The ‘with statement’
Appending Data to a File
Renaming a File
The rename() method
Deleting a File
Binary Files
File Methods
File.writer(str)
File.writelines(sequence)
File.readline(size)
File.readlines()
File Positions: file.tell() and file.seek
File.tell()
File.seek()
File.read(n)
File.truncate([size])
File.flush()
File.close()
File.isatty()
File.fileno()
Step 25: Handling Errors or Exceptions
Syntax Errors
Runtime Errors
Built-in Exceptions
Catching Exceptions
try and except
try…finally
Python Cheat Sheets
Variable Assignment
Accessing Variable Values
Python Operators
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Identity Operators
Membership Operators
Bitwise Operators
Strings
Lists
Tuple
Dictionary
Sets
Loops
Conditional Statements
if…else
if…elif…else
Built-in Functions
User-Defined Functions
Classes
Files
Text File Opening Modes
Binary File Opening Mode
File Operations
Date and Time
Python Modules
Help!
Google
FAQ
IRC (Internet Relay Chat)
Other Best Selling Books You Might Like!
Conclusion