Download as pdf or txt
Download as pdf or txt
You are on page 1of 117

Python

Programming
For Beginners
 
 Learn
Python in One Day
 
 
 
 
Elite Tech Academy

 
© Copyright 2017 by AmazingLifeForever
– 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 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 within this book is offered for general
informational
purposes solely, and is universal as so. The presentation of the
information
is without contract or any type of guarantee assurance. While we
try to keep
the information up-to-date and correct, there are no
representations or
warranties, express or implied, about the completeness,
accuracy, reliability,
suitability or availability with respect to the
information, products, services,
or related graphics contained in this book for
any purpose.
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 owned by the owners themselves, not affiliated with this document.
The author claims no responsibility to any person or entity
for any liability,
loss or damage caused or alleged to be caused directly or
indirectly as a
result of the use, application or interpretation of the
information presented
herein.

 
Introduction

I want to thank you and congratulate you for


buying the book, “Python
Programming for Beginners”.
This book contains the steps, strategies, and information
you need to learn
the essentials of Python programming in as little time as
possible. It seeks
to provide a solid foundation for people who are new to
programming and
are taking Python as their first language. It is an excellent
resource material
for programmers who are studying Python as an adjunct to
their computer
language portfolio.
Python is a powerful and versatile language that is easy to
learn and master.
It is a vastly popular language in the academic circles where
it is used in
data analytics, computing, and bioinformatics. It was used to
build popular
sites such as Google, Instagram, Pinterest, BitTorrent and
Dropbox. It is a
living and growing language that will continue to be relevant
in the coming
years.
This book explores the nature, capabilities, and features of
Python and
provides a step-by-step guide to help you use and manage its data
types,
functions, modules and methods, and apply its programming principles. It
teaches the core of Python programming and helps you create your own
programs
quickly and easily.
This book uses a straightforward and practical approach to
make the study
of programming an interesting and enjoyable experience for all
types of
learners and readers. It provides relevant and numerous examples that
you
can use as references when writing your own programs. It offers
programming
challenges that will help you assess your skills and help you
grow as a
programmer.    From the basics of installation to advanced
programming topics,
this book offers the ultimate experience in learning
Python programming for
students at different levels.
Thanks again for buying this book, I hope you enjoy it!
TABLE OF CONTENTS

 
CHAPTER 1 WHY YOU SHOULD LEARN PYTHON........................... 2
CHAPTER 2 INSTALLING PYTHON AND USING IDLE................... 4
CHAPTER 3 PYTHON SYNTAX................................................................
10
CHAPTER 4 VARIABLES AND DATA OPERATORS ...................... 16
CHAPTER 5 DATA TYPES ........................................................................
28
CHAPTER 6 FUNCTIONS AND MODULES ........................................ 76
PRACTICE SET
1........................................................................................... 94
CHAPTER 7 DECISION MAKING AND FLOW CONTROL ........... 96
PRACTICE SET 2 .......................................................................................
108
CHAPTER 8 FILE MANAGEMENT .....................................................
110
CHAPTER 9 REGULAR EXPRESSIONS .............................................
118
CHAPTER 10 SOLUTION TO PRACTICE SETS ............................. 120
CONCLUSION...............................................................................................
122
 
 
Your Free Python Cheat Sheet

Before we begin, I would like to express my heartfelt


gratitude. I know that
your time is limited. I also realize that there are many
other books and
courses about this topic.
You chose to read mine. That means a lot to me!
As a token of appreciation, I would like to give you
something. It won’t
cost you a dime. It’s a Python Cheat sheet that you could
use for your
reference.
Please  download   your  cheat sheet  at the below link  -
http://amazinglifeforever.com/Gift/pythoncheatsheet/
Chapter
1
Why You Should Learn Python
 

Python is a general purpose programming language that supports


multiple programming paradigms such as object-oriented, aspect-oriented,
structured, and functional programming.
Developed by Guido van Rossum in the late 1980s, Python’s syntax is
derived primarily from C and the ABC programming languages.
Python is one of the most popular programming languages for
beginners. A powerful and versatile language, it has been used to develop
various desktop and web applications.
It was used to build popular sites and platforms such as Google,
BitTorrent, Dropbox, Pinterest, Instagram, and Civilization IV. It is widely
used in the academic circles for data analysis, bioinformatics, and
computing.
Python is an interpreted language and it converts codes into
machine-
readable byte codes before it can run them.
It is a high level language that is easy to learn, master, and use.
In a
relatively shorter learning time, you will be able to create interesting
games,
GUIs, web applications, and productivity programs.
Python codes are short and simple which makes programming more
efficient. You can create Python programs in considerably less time than
what
you would normally use when using other programming languages.
Python has one of the most extensive libraries and is loaded with
built-in features that can help programmers automate tasks and develop
highly
useful applications.
Learning Python can give you a solid foundation for a programming
career. You can use it as a stepping stone to learn other object-oriented
programming languages and make yourself a versatile and all around
programmer.
Python programmers and developers are one of the most sought after
and highest-paid professionals in the world today. Python is used by
companies
like Google, Yahoo!, Disney, IBM, and Nokia. Mastering
Python will enhance your
career prospects.
Chapter
2
Installing Python and Using IDLE
How to Install Python
Python has been developed using an open source license and
it is free to use
and distribute both for personal and commercial use. You can
download its
installation files from the website
of its administrators, the Python Software
Foundation.

Installing Python in Windows


To install Python in Windows, you must download the specific
installation
package for your preferred version. Here’s the link:
https://www.python.org/downloads/
The link will present the two latest versions, Python 3.6.3
for Python 3 and
Python 2.7.14 for Python 2. If you prefer the older versions,
you can scroll
down the page to view the list and find the appropriate link.
After successfully downloading the package, run the
installation files by
clicking on its icon. You can opt to install using
default settings or
customize the installation to specify the location and
features. You can
choose to install for all users of the computer or for the
current user only by
clicking or unclicking the option. You can also choose to
add Python to
Path.

 
Installing Python in Mac
Mac users can download the
installation package from this link:
https://www.python.org/downloads/mac-osx/

Installing Python in Linux/UNIX


If you’re using Linux/UNIX as operating system, you can
download the
installation package from this link:
https://www.python.org/downloads/source/
Once the download is completed, you can install Python by
clicking on the
downloaded exe file. A standard installation package will
include IDLE,
pip, and documentation.

Starting Python
You can start Python using the command line terminal or
IDLE. The
command line environment allows basic interface for trying out lines
of
codes and running your program. IDLE, which means Integrated
Development
Learning Environment, is an IDE created exclusively for use
in Python.
There are different options for accessing IDLE or the
command line
depending on the operating system installed.
If you’re using Windows, you can start IDLE or the command
line by
clicking on the menu item or icon on the Start Menu. Likewise, you may
go
to the folder containing the installation files or a shortcut to the
installation
files and clicking on either IDLE or Python Interactive Shell.
To run Python using GNU/Linux UNIX, and Mac OS, you will
need to run
the Terminal Tool and enter Python to start your session.

Using IDLE
IDLE offers a
basic graphical user interface with several helpful features to
make writing
programs more efficient and intuitive. It is a flexible platform
for exploring
Python capabilities and testing, writing, debugging, and
implementing your
programs.
You can use
IDLE in either interactive or script mode. 
In interactive
mode, Python evaluates each expression or statement entered
while it simultaneously
runs previous statements stored in its active
memory. It provides immediate
feedback after reading the latest statement.
This mode is commonly used to test
code snippets. You can also use it to
learn Python syntax.
In the script
mode, the interpreter runs Python codes or scripts which are
saved with a .py
file extension.
IDLE offers the
following important features:  Python Shell, built-in
multiple-window text
editor, syntax highlighting, smart indent, auto-
completion, and an integrated
debugger.

The Python Shell


The Python Shell features a user-friendly drop down menu with
several
useful features. You can use it to access and run Python programs. You
can
work interactively with Python by entering an expression and pressing
enter. You can use its copy-paste options to work on previous commands
and make
the necessary modifications.
The Python
Shell shows the following main menu options:
File  Edit  Shell  Debug 
Options  Windows Help      

The
File Menu

The File menu offers options for creating a


new file, opening a saved
module or file, saving a new file, saving a copy,
saving a file using a
different filename, searching for and opening a class,
browsing sys.path,
closing current file, printing and saving the current
window, and exiting
Python Shell.
Clicking on ‘New File’ opens the built-in
text editor with an almost
identical main menu options. You can use this text
editor to type, edit, save,
open, and run your program or modules. The output
is displayed on the
Python Shell. The menu options are File, Edit, Format, Run,
Options,
Windows, and Help.
The Format menu provides options for
indenting/dedenting, commenting
out or uncommenting, tabifying/untabifying,
toggling tabs, setting tabs and
indent width, paragraph formatting, and
removing trailing whitespaces.
The Run menu has options for checking and
running modules.
The rest of the menu options in the text
editor are similar to those found in
the Python Shell.

The
Edit Menu

The Edit menu provides options that allow


users to undo, redo, copy, cut,
paste, search for and/or replace a word.

The
Shell Menu
The Shell menu has options for viewing the
most recent restart and for
restarting the Python Shell.
The
Debug Menu

The Debug menu is used to access the


debugger, the line where Python
raises an exception or error, the stack, and
the auto-stack viewer.
The
Options Menu

The Options menu allows you to set


preferences for font, tabs, indent width,
keys, highlighting, and other general
options in IDLE.

The
Window Menu

The Window menu has a submenu for adjusting


zoom height and moving
between open Python Shell and text editor windows.

The
Help Menu
The Help menu allows users to access
Python’s documentation and help
files.

Writing and Running Your First Python


Program
 

To write a program, you can use other text editors or


Python’s own text
editor. When you write a program using other text editors,
you will have to
save it with a .py extension. In IDLE, your program will
automatically be
saved with a .py extension.

Using
IDLE to Write Your Program

To access the built-in text editor on Python Shell:


Click on File
Choose New File
The text editor will appear on your screen.

Typing
your Program
You will use the editor to type your first program. You can
write a simple,
single line program on the text editor:
print(Hello,
World!)

Saving
the File

Saving your program or file


prepares it for processing by Python. You can’t
run the program without saving
the file. You can save it in the current
working directory or in a directory of
your choice.
To
save:
Click
on File
Choose
Save
Clicking
on the ‘Save’ option opens the ‘Save as’ dialogue which will allow
you to name
the file and specify the destination folder. Name the file as
‘Hello’ and save
it on the default directory. Take note that you did not have
to provide the extension.
Python automatically saves the file as Hello.py.
Running
the Program

To run the Hello.py program, click on the Run module option


in the Run
menu. If there are no errors, you will see the following on the
Python Shell:
 ======= RESTART: C: /Python/Hello.py =======
Hello, World!
Chapter
3

Python
Syntax
 

 
Programming syntax refers to the set of
rules and conventions that define
how programs should be written and how they
are interpreted. To write
valid Python programs, you have to familiarize yourself
with its syntax.

Keywords
Keywords are reserved words that Python
uses for built-in functions and
processes. You can’t use them to name
variables, functions, objects, classes,
modules, and other items. At present,
there are 33 Python keywords that
you should learn and never use as identifier
to avoid program errors or
exceptions:
True      False None   
class       for continue  
finally       return        lambda    
try is         from     
def      global  while
and        not        nonlocal    
del        with as        
elif       or         if        
yield except    break
import  pass assert   
raise     in         else
 

 
Identifiers
An identifier is a name given to objects
such as variables, modules, classes,
and functions. 
Here are the rules and conventions for
naming objects or entities:
·      
An identifier can be a
combination of uppercase, lowercase, an
underscore, or digits.
 
·      
An identifier should
not contain a special character or symbol such as $,
&, %, @, and #.
 
·      
It should not start
with a digit.
 
·      
You can use underscores
to join multiple-word identifiers.
 
·      
Keywords should never
be used as identifiers.
 
Valid
identifiers:        

myVariable, my_new_Car, students,


var_1, camelCaseName

Invalid
identifiers:    
9variable,
cash-register, func@#
 
Take note that Python is case sensitive.
Hence, Students and students are
distinct identifiers.

 
Quotation Marks
A pair of single (΄), double ("),
or triple (''') quotation marks indicate string
literals in Python.
Examples:
΄Andrei΄,
"age", '''occupation: ''', ΄Safety is a Priority΄

Python Statements
Statements are expressions written within a
program which are read,
ignored, or executed by the interpreter. Python
supports several types of
statements including if, for, while, break, and
assignment statements.

Multi-line statements
A multi-line statement spans several lines.
To tell Python implicitly that a
multiple-line statement is a single statement,
you can wrap the lines inside
parentheses (), curly braces {}, or square
brackets [].     
Example:
>>>
my_letters = {'a', 'b', 'c', 'd', 'e', 'f'
'g', 'h', 'i', 'j',
'k', 'l'
'm', 'n', 'o', 'p',
'q', 'r'
's', 't', 'u', 'v',
'w', 'x'
'y', 'z'}
 
You can explicitly indicate continuity by
using a backslash (\) at the end of
each line

 
Example:
>>>my_letters
= ["a", "b", "c", "d"\
                   
"e", "f", "g", "h"\
                              
"i", "j", "k", "l"\
                           "m",
"n", "o", "p"\
                    
"q, "r", "s", "t"]

Indentation
Python uses indentation or white spaces to
structure programs. The use of
white spaces makes Python programs more readable
and organized. A block
of code starts from the same distance going to the
right. A nested code is
marked by further indenting to the right. Consistency
in indentation is a
must if you want your program to run properly. The end of a
code block is
indicated by the first unindented line.
By convention, four white spaces are
preferred over tabs when indenting a
block of code.
Here is a program snippet that will
illustrate the use of white spaces:
 
num =
int(input('Number: '))
if num <= 5:
    print(' You
lose!')
elif 5 < num <
10:
    print(' Nice
Try!')
else:
    print('Try
Again!')

Comments
Comments are notes that programmers write
within programs to describe a
process, step, or provide any important
information. Comments enhance
program documentation and are useful during
reviews. A comment is
preceded by a hash (#) symbol which tells the interpreter
to ignore the line
and go on to the next statement on the code.
Example:
#This provides
commission data
Like a statement,
a comment can span over multiple lines. You can use a
hash (#) symbol at
the beginning of each line to wrap them together.
Example:
#This long comment
#spans over
#several lines
 
Another way to wrap multiple-line comment is by using
triple quotes (""")
to indicate the start and end of the
comment.
 
Example:
"""Using
triple quotes
is another way to
wrap
a multiple line
comment"""
 

Docstring
A docstring, short for documentation
string, is used to document what a
class or function does. It is placed at the
top of a code block that defines a
method, function, class, or module.
Docstrings are phrases that start with a
letter in uppercase and end with a
period. It is usually a one-line summary
which is written like an imperative
statement. Docstrings may also span
several lines. They are enclosed within
triple quotes (""").
Examples:
def
double_value(num):
   
"""Function to get twice the value of a
number."""
    return 2*num
Chapter
4

  Variables and Data Operators


 

Variables
In Python, a variable is a reserved memory location that can
be used to store
and access values. Whenever you create a variable, you are
allocating a
space in memory or reserving a storage that you can use to hold
values. A
variable is given a distinct name to identify its location. You can
use the
variable name to instruct the machine to perform different tasks such
as
saving, accessing, printing, editing, or retrieving data.
Variable creation and management is more flexible in Python
compared to
other languages. Declaring a variable is as straightforward as
assigning a
value to an identifier using the assignment operator (=). There is
no need to
declare the data type of the value to be assigned because the
interpreter
intuitively identifies the data type of the assigned value.
Here are examples of variable assignment statements:   
student = "Meryll
Storm"          #a string
grade = 90.75                       #a
float
age = 20                           #an
integer
comment =
"excellent"           #a string    
The left operands are the identifiers given to the variable
while the right
operands are the value assigned to the variable. The assignment
operator
tells Python that a variable is set to a given value. In the above
example, the
assignment statement “age = 20” means the variable ‘age’ is set to
20. The
value of 20 is an integer based on its form and there is no need to
declare
that it is an integer.
You can use the id() operator to obtain the memory location
of the
variables.
Syntax:  
id(variable name)
For
example, to get the memory location of the variable ‘student’, you will
type
the following on the Python Shell prompt >>>
 
>>> id(student)
 
Python will return
the memory location:
 
45352584
 
>>> id(grade)
42623648
 
>>> id(age)
1484937792
 
>>> id(comment)
45352744
 
 
Python
allows multiple assignments in a single statement where the values
are assigned
based on positional order.
 
Syntax:     a, b, c =
1, 2, 3
For example, enter the following multiple assignment
statement:
>>> name, number,
grade = "Goldburn", 16, 90.5 
 
To
see how Python handles the statement, use the print function to view the
values
stored in the variables name, number, and grade:
 
>>> print(name)
Goldburn
 
>>> print(number)
16
 
>>> print(grade)
90.5
 
Python allows the assignment of a single value to multiple
variables in one
assignment statement with the syntax:
 
a = b = c =
"leopard"
 
The above statement assigns the string ‘leopard’
simultaneously to variables
a, b, and c in a single statement. You can verify
if the three variables point
to one memory location by using the id() operator:
>>> id(a)
45301152
 
>>> id(b)
45301152
 
>>> id(c)
45301152
You can easily change the value and the corresponding data
type stored in a
variable with a simple reassignment statement.
For example, create a variable ‘counter’ by assigning an
integer value of
30:
counter = 30
If you want to increase the value stored in ‘counter’ by 20,
you can enter
the following statement with the ‘add and’ (+=) operator:
 
>>>counter += 20
 
To check how Python evaluates the above statement, you can
type ‘counter’
on the >>> prompt:
 
>>> counter
50
 
The above example demonstrates how easily you can reassign
the variable
to hold a different value. A variable is not limited to any data
type. You can
reassign another data type with an assignment statement. For
instance, to
reassign ‘counter’ to the string ‘calculator, simply enter the
statement:
 
 >>> counter =
"calculator"
 

 
To view the current value stored in ‘counter’, just type
counter in the >>>
prompt:
>>> counter
'calculator'

Data Operators
Operators are special symbols that signify the
implementation of a process.
They are used to assign, evaluate, manipulate, or
perform operations on
different data types.
Python supports several types of data operators:

Arithmetic Operators
 
Addition (+)  
 
The addition operator adds the operands on both sides
of the operator:
 
>>>5+
2
7
 
Subtraction  (-)
 
The subtraction operator deducts the right operand
from the left operand:
 
>>>15
– 5
10
 
 
Multiplication (*)
 
The multiplication operator multiples the values of
both operands:
 
>>>10
* 2
20
 
 
Division ( /)
 
The division operator divides the left operand with
the right operand:
 
>>>12
/ 4
3.0
 
 
Exponent (**)
 
The exponent operator raises the first operand to the
power indicated by the
second operand:
 
>>>
2**4
16
 
Modulos (%)
 
The modulos operator returns the remainder after
dividing the left operand
with the right operand:
 
>>>
35 % 9
8
Floor Division (//)
 
The floor division operator divides the left operand
with the right operand
and returns the quotient as a whole number without
decimal part.
 
>>>
42//3
14

Comparison or Relational Operators


Comparison operators evaluate a comparison expression and
return either
True or False.
Operator      Meaning
==         is equal to
!=          is not equal to
<            is less than
>            is greater than
<=         is less than or equal to
>=         is greater than or equal to
 
Examples:
>>> a
= 26
>>> b
= 24
>>> a
== b
False
 
>>>32
> -35
True

 
Logical Operators
There are three types of logical operators:
or 
and
not
 
Python evaluates logical expression using the
following rules:
 
x and
y  If x and y are both true, it returns True. If one is false, it returns
False.
 
x or
y        If either x or y is True, it returns True. If both are False, it
returns
False.
 
not y      It
returns True if y is false and False if y is true.
 
Examples:
>>>
(10 > 2) or (2 > 8)
True
 
>>>
(4 > 2) and (3 > 12)
False
 
>>>
(15 == 3 * 5) and (5 < 2 ** 3)
True
 
>>>
not (10 > 3 ** 5)
True
 
>>>
not (2 * 9 > 4)
False
Assignment Operators
Assignment operators are used to assign values to variables.

 
Assigns the value of the right operand to the left operand:
 
a = ‘apple’, c = [1, 2, 3, 4]
 
 
+=
add and  
 
Add the left and right operands and assigns the total to the
left operand:
 
x += 4
 
-= subtract and
 
Subtracts the right operand from the left operand and
assigns the value to
the left operand:
 
x -= 3
 
*= multiply and
 
Multiplies
both operands and assigns the value to the left operand:
 
x *= 4
 
/=
divide and
Divides the left operand with the right operand and assigns
the quotient to
the left operand:
x /= 2
 
 
**= exponent and
 
Performs exponential operation on the left operand and
assigns the result to
the left operand
 
x **= 2
 
 
//=
floor division and
 
Performs
floor division on the left operand and assigns the value to the left
operand
 
x //= 5

Membership Operators
Membership operators test for the occurrence or non-occurrence
of a value
in a sequence such as string, list, or tuple and of a key in a
dictionary.
 
in
 
The ‘in’ membership operator returns True if the given value
is found in a
sequence or if the specified key is in a dictionary. It returns
False if
otherwise.
 
not in
 
The ‘not in’ membership operator returns True if the
specified value is not
found in a sequence or if a given key does not exist in
a dictionary. It
returns False if otherwise.
Examples:

>>> my_string =
"Python is an interpreted language."
>>> 're' in my_string
True
 
>>> a_list = [24, 33,
14, 12, 'e', 'x', 23.5]
>>> 12 in a_list
True
 
>>> 14 not in a_list
False
 
>>> my_dict =
{'color':'yellow', 'size':'large', 'age':14}
>>> 'color' in my_dict
True
 
>>> 'size' not in
my_dict
False
 
 
Chapter 5

Data
Types
 

 
Programming
requires working with data. Python programs uses objects of
different data
types. These objects may be built-in, user-defined, or
imported from modules or
libraries.
 
Python supports the following basic data types:
 
Number
String
List
Tuple
Dictionary
Sets
 
Numbers
Python 3 supports three
numeric data types:
·      
integers
·      
floating point numbers or floats
·      
complex numbers
 
Integers (int)
Integers are whole numbers without a fractional part
or decimal point. It has
unlimited size and includes zero, positive, or
negative numbers. Python
supports normal integers, binary, octal, and
hexadecimal literals.
 
Normal integers  
Examples: 50, -100, 0, 87654312367809
 
Binary literal (base 2)
A binary literal is introduced by 0 (zero) followed by
an uppercase B or
lowercase b.
 
Examples:
>>>
0b0100
4
>>>
bin_num = 0b0100
>>>
print(bin_num)
4
 
 
Octal literal (base 8)
 
An octal literal is prefixed by o (zero) and uppercase
O or lowercase o:
 
Examples:
 
>>>
0O100
64
 
>>>
0o100
64
 
>>>
oct_num = 0O100
>>>
print(oct_num)
64
 
 
Hexadecimal literal (base 16)
 
A hexadecimal literal starts with 0 (zero) and an
uppercase X or lower case
x.
 
Examples:
 
>>>
0xa0f
2575
 
>>>
0XA0F
2575
 
>>>
hex_num = 0xa0f
>>>print(hex_num)
2575
 
 
Converting Integers to String
 
The built-in function oct(), bin(), and hex() are used to
convert an integer to
its string representation.
To illustrate, the following statements shows how to
convert the integer 30
to its octal, binary, and hexadecimal literals:
 
integer to octal literal:
 
>>>
oct(30)
'0o36'
 
 
integer to binary literal:
 
>>>
bin(30)
'0b11110'
 
 
integer to hexadecimal literal
 
>>>
hex(30)
'0x1e'
 
Floating-Point Number (Float)
 
A float is a real number with a decimal point and
fractional part.
 
Examples:     45.98, 98.5, 987456343.25
 
 
Complex Number
 
A complex number is a pair of a real and imaginary
number. It is written as
‘a+bj’ or ‘a+bJ’ where
a and b are floating point numbers and J or j is an
imaginary number. The
letter ‘J’ or ‘j’ symbolizes the square root of -1
which is an imaginary
number.
 

 
Example:
 
>>> x
= 6 + 7j
>>> y
= 3 - 4j
>>>
xy = x + y
>>>
print(xy)
(9+3j)
 
Converting One Numeric Type to Another
 
Python intuitively handles the conversion of mixed
number types to a
common one. Sometimes however, syntax may require their
explicit
conversion. You can compel Python to convert a number by using the
appropriate keyword.
 
For example, to convert an integer to a floating point
number: float(x)
 
Example:
 
>>>
float(20)
20.0
 
To convert an integer to a complex number: complex(x)
 
Example:
 
>>>
complex(20)
(20+0j)
 
To convert a numeric pair expression to a complex
number: complex(x, y)
 
Example:
 
>>>
complex(8,4)
(8+4j)
 
 
To convert a floating point number to an integer: int(x)
 
Example:
 
>>>int(26.75)
26
 
To convert a floating point number to a complex
number: complex(x)
 
>>>
complex(30.5)
(30.5+0j)
 
String
 
A string is an ordered series of Unicode characters
which may consist of
letters, numbers, special characters, or their
combination. It is defined
through an assignment statement where it is enclosed
in a pair of single or
double quotation marks.
 
A string is an immutable data type. Once assigned to a
variable, you will no
longer be able to modify it.
 
Here are examples of string assignment statements:
 
>>>
string_1 = 'programmer'
>>>
string_2 = "sequence data type"
>>>
employee = 'Robert Jones'
 
When you use a single quote within a string that is
enclosed in a single
quote, you must escape it with a backslash. Otherwise, the
interpreter will
return a syntax error.
 
For example:
 
>>>
remark = 'I can\'t approve the proposal.'
 
View the variable ‘remark’ with the print()
function:
 
>>>print(remark)
I can't
approve the proposal.
 
Take note that you can totally avoid the use of the
backslash by using
double quotes to enclose the string.
 
In the same manner, you will have to escape a double
quote with a string
when the entire string is enclosed in double quotes.
 
For example:
 
>>>
response = "He responded to the question: \"I'm interested in
your
investment offer.\""
 
To view the string stored in the variable response,
use the print function:
 
>>>
print(response)
He responded
to the question: "I'm interested in your investment
offer."
 
Accessing String Value
 
A string can be accessed with the index operator [].
The initial character or
substring takes zero index and the succeeding
characters are numbered
sequentially.
 
To illustrate, assign the string ‘Mathematics’ to the
variable ‘subject_101’:
 
subject_101 =
‘Mathematics’
 
 
To access the first character on subject_101:
 
>>>
subject_101[0]
'M'
 
To access the 5th character, enclose 4 on
square brackets:
 
>>> subject_101[4]
'e'
 
To access the last charter in a string, you can use
either the len() function or
negative indexing.
 
The len() function is used to find out how many
characters are in a string.
Following the indexing rule where index starts at
zero, the last character is
equal to the length of the string less 1.
 
syntax:  string[len(string)-1]
For example, to access the last character of the string
subject_101:
>>>
new_string[len(new_string)-1]
 
Negative indexing is a simpler way to access the last
character. In Python,
the last character has the index of -1, the penultimate
character -2, and so
on.
 
>>>
subject_101[-1]
's'
 
>>>
subject_101[-5]
'a'
 
Slicing Strings
 
You can make substrings from a given string using the
slicing operator [:].
The colon is used to separate the two indices. The
first number represents
the index of the first character on the substring while
the second number
stands for the first sequential character to be omitted from
the original
string.
 
For example, create a new string:
 
>>>
string_1 = 'economy'
To display a
substring ‘con’, write 1 as the starting index and 4 as the
ending index:
 
>>>
string_1[1:4]
'con'
 
You can drop the first index if you want to access a
substring that starts
from the first character of the string. Similarly, you
can drop the second
index if you want to end the substring on the last
character of the string.
 
Examples:
 
>>>
string_1[:4]
'econ'
 
>>>
string_1[3:]
'nomy'
 
A string is immutable and any substrings you create
will not affect the
string. For example, type string_1 at the command prompt to
view the
string stored in this variable:
 
>>>
print(string_1)
economy
 
Concatenating Strings
 
The + operator is used to combine several
strings into a single string.
 
For example:
>>>
string1 = 'Strings'
>>>
string2 = 'Tuples'
>>>
string1 + ' and ' + string2 + ' are immutable data types.'
'Strings and
Tuples are immutable data types.'
 

 
Repeating a String
 
A string or string concatenation may be repeated with
the use of the
multiplication operator * and a number to indicate the
number of times that
a string should be repeated.
 
For example, to repeat the string *()* two times:
 
>>>
'*()*'*2
'*()**()*'
 
The upper() and lower() Methods
 
The upper() and lower() functions are
used to display a string in uppercase
or lowercase.
 
For example, assign the string ‘Immutable’ to the
variable my_string:
 
>>>
my_string = 'Immutable'
 
To view the string in uppercase:
 
>>>
print(my_string.upper())
IMMUTABLE
 
To view the string in lowercase:
 
>>>
print(my_string.lower())
immutable
 

 
List
A list is a commonly used sequence data type in Python. It
is a flexible
container that can hold any type and number of data or a
combination of
different kinds of data. 
A list is mutable. Hence, you
can add, modify, or delete its elements.
To create a list, simply
define a variable that will hold an ordered sequence
of elements separated by a
comma. These elements are enclosed in a square
bracket.
To create an empty list, you
will use the syntax:
my_list
= []
 
To build a list, you can assign the items to a
variable with the syntax:
 
my_list =
[item1, item2, item3]
 
Here are examples of list creation statements:
 
color_list =
["yellow", blue", "green", "orange"]
int_list = [0,
3, 6, 9, 12, 15]        
mixed_list =
["guitar", 20, 6.5]        
nested_list =
["bass", 4, 6.5, [5, 10, 4, 8, 12.5, 2]]    
 
Accessing Elements on a
List
Python provides several ways
to access the items on a list:
·      
Indexing
The index operator [] can be used to access
list elements. As with strings,
the first item has an index of zero (0).
Accessing an item that is not found
within the index range of a list will
result to an IndexError.
 
Examples:
>>>animals
= ["rhinoceros", "leopard", "lion", "elephant"]
 
To access index 0, 2, 3, and
5:
>>>
animals[0]
'rhinoceros'
 
>>>
animals[2]
'lion'
 
>>>
animals[3]
'elephant'
 
>>>
animals[5]
Traceback
(most recent call last):
  File
"<pyshell#32>", line 1, in <module>
    animals[5]
IndexError:
list index out of range
 
If you need to access a nested list, you can use nested
indexing.
 
Example:
>>>
list_nested = ["basement", 10, [2, 4, 6, 8]]
 

 
To access the list elements:
 
>>>
list_nested[0]
'basement'
 
>>>
list_nested[1]
10
 
>>>
list_nested[2]
[2, 4, 6, 8]
 
>>>
list_nested[2][2]
6
 
>>>
list_nested[2][3]
8
 
·      
Negative Indexing
Python supports negative indexing for the list data
type. The last item on
the list has the -1 index, the penultimate item takes
the -2 index, and so on.
 
Example:
>>>
vowel_list = ['a', 'e', 'i', 'o', 'u']
 
To access the elements of the list using negative
indexing:
 
>>>
vowel_list[-1]
'u'
 
>>>
vowel_list[-2]
'o'
 
>>>
vowel_list[-4]
'e'
 
·      
Slicing Lists
You will use the slicing operator [:] to access
a range of items on a list.
 
Syntax: list[:]
 
Example:
>>>
list_a = [10, 'members', 'of', 'the', 'glee', 'club']
 
To access a range of items, you will provide the index
of the first item on
the left side of the colon and the index after the last
item to be included on
the list.
 
>>> list_a[1:3]  #to
access index 1 and 2
['members',
'of']
 
>>>
list_a[4:6]  #to access index 4 and 5
['glee',
'club']
>>>
list_a[3:5]  #to access index 3 and 4
['the',
'glee']
If the range you want to access starts with the first
element, you may omit
the left index:
 
>>>
list_a[:4]
[10,
'members', 'of', 'the']
 
If the range you want to access ends on the last item
of the list, you may
omit the right index:
 
>>>
list_a[3:]
['the',
'glee', 'club']
 
If you want to access the entire list, you can omit
both left and right index:
 
>>>
list_a[:]
[10,
'members', 'of', 'the', 'glee', 'club']
 
Adding Elements to a List
 
To add an element to a list, you can use the append()
or extend() method.
The append() method is used to add one item
while the extend() method is
used to append more than one item.
 
In Python, methods are invoked by inserting a dot (.)
after the file name and
before the method and parameter.
 
Here’s the syntax for the append() and extend()
methods:
 
list.append(x)  #adds an item at the end
list.extend()     #adds all elements at the end
 

 
Example:
 
Create a list:
 
>>>
odd_list = [1,3,5,7,9,11]
 
Use the append() method to add the integer 13
to the list:
 
>>>
odd_list.append(13)
 
To view the updated list:
 
>>>
print(odd_list)
[1, 3, 5, 7,
9, 11, 13]
 
Use the extend()
method to add a list of odd numbers to odd_list:
>>>
odd_list.extend([15, 17, 19, 21])
 
 
Use print to view the updated odd_list:
 
>>>
print(odd_list)
[1, 3, 5, 7,
9, 11, 13, 15, 17, 19, 21]
 
Changing Elements of a List
 
You can change an element or
a range of elements on a list using the
assignment (=) and the indexing []
operator.
To illustrate, here is a list
of numbers that should have exclusively
contained odd numbers:
>>>
odd = [2,3,5,7,8,9,11]
 
You can replace the first item on the list with this
statement:
 
>>>
odd[0] = 1
 
To view the updated list, use
the print() function:
>>>
print(odd)
[1, 3, 5, 7,
8, 9, 11]
 
If you need to replace several list items, you can
simply specify an index
range instead of accessing individual values.
 
For instance, to replace the odd numbers 7, 8, and 9:
 
>>>
odd[3:6] = [13, 15, 17]
 
To view the updated list, you can just type ‘odd’ on
the Python prompt:
 
>>>
odd
[1, 3, 5, 13,
15, 17, 11]
 
Concatenating and Repeating Lists
 
You can combine two or more
lists with the + operator. You can also repeat
a list at a specified
number of times with the * operator.
For example, to combine two
lists:
>>>
vowels = ['a','e','i','o','u']
>>>
odd = [1,3,5,7,9]
>>>
vowels + odd
['a', 'e', 'i',
'o', 'u', 1, 3, 5, 7, 9]
 
To repeat a list:
>>>
numbers * 2
[1, 2, 3, 4,
5, 1, 2, 3, 4, 5]
 
Inserting Item(s) 
 
The insert method is used to insert an item on
a desired location within a
list.
 
syntax: list.insert(index, object)
 
Index is the target index of
the new item to be inserted to the list while the
object is the new item.
To illustrate, create a list
of even numbers:
>>>
even = [2, 4, 8, 10, 12]
 
Use the insert method to add number 6 on index 2:
 
>>>
even.insert(2,6)
 
Type ‘even’ to view the list:
 
>>>
even
[2, 4, 6, 8,
10, 12]
 

 
Removing or Deleting Items from a List
 
To remove an element from a list, you can use the remove()
method or the
pop() method. The remove() method takes out the
specified item while the
pop() method removes the item at the specified
index. To empty the entire
list, you will use the clear() method.
 
The remove() method
 
syntax:
my_list.remove(object)
For example:
>>>mixed
= ['a', 'b', 'e', 1, 'c', 'd', 95.5]
 
If you want the mixed list to
be an exclusive list of letters, you can use the
remove() method to take
out the integer 1 and the float 95.5 one by one:
>>>
mixed.remove(1)
>>>
mixed.remove(95.5)
 
To view the updated mixed list:
 
>>>
mixed
['a', 'b',
'e', 'c', 'd']
 
The pop() method
The pop() method is
used to remove an item associated with a specified
index. If the index is not
supplied, it removes and returns the last item on
the list.
syntax: list_name.pop(index)
To illustrate, create a new
list:
>>>
my_list = ['giraffe', 'zebra', 'apple', 'python', 'raccoon']
 
The string ‘apple’ is the odd
item on this list. You can use the pop() method
to remove it:
>>>
my_list.pop(2)
'apple'
 
To view the updated my_list:
>>>
my_list
['giraffe',
'zebra', 'python', 'raccoon']
 
Check out what happens when
you use pop() without specifying an index:
>>>
my_list.pop()
'raccoon'
 
The pop() method removed the last element on
the list. To view the updated
list:
 
>>>
my_list
['giraffe',
'zebra', 'python']
 
To empty my_list:
>>>
my_list.clear()
 
To view the updated my_list
 
>>>
my_list
[]
 
The keyword del is another way to delete one or
more items on a list.
 
To delete an item:
 
del
list_name[]
 
To delete a range of items:
del
list_name[:]
 
For example, create new list:
 
>>>new_list
= ['apple', 'banana', 'pear', 'pineapple', 'cantaloupe',
'grape']
 
To delete the first item on the list:
 
>>>
del new_list[0]
 
To view the updated new_list:
 
>>>
new_list
['banana',
'pear', 'pineapple', 'cantaloupe', 'grape']
 
To delete items from index 1
to 3:
>>>
del new_list[1:4]
 
To view what’s left on the list:
 
>>>
new_list
['banana',
'grape']
 
Another way to delete a range of items is by assigning
indices to an empty
list:
 
To illustrate, create a new list:
 
>>>
my_list = [2, 4, 6, 'w', 'o', 'w', 85.5, 87.2]
 
Assign all string items from index 3 to 5 to an empty
list:
 
>>>
my_list[3:6] = []
 
View the updated my_list:
 
>>>
my_list
[2, 4, 6,
85.5, 87.2]
 
You can remove the contents
of a list by assigning all items to an empty list:
>>>
my_list[:] = []
 
To view the updated my_list:
 
>>>
my_list
[]
Sorting Items on a List
 
The sort() method is
used to sort list elements of similar data type in an
ascending order.
syntax: list.sort()
 
To illustrate, create a new list:
 
>>> oceans
= ['Pacific', 'Atlantic', 'Arctic', 'Southern', 'Indian']
 
Use the sort method to
sort the items:
>>>
oceans.sort()
 
Print the oceans list to view
the sorted items:
>>>
print(oceans)
['Arctic',
'Atlantic', 'Indian', 'Pacific', 'Southern']
 
The list is now arranged in ascending order. If you
want to arrange the items
in descending order, you can use the reverse
method.
 
syntax: list.reverse()
 
To use the reverse() method on oceans:
 
>>>
oceans.reverse()
 
To view the oceans list on descending order:
 
>>>
print(oceans)
['Southern',
'Pacific', 'Indian', 'Atlantic', 'Arctic']
 
The count() method
 
The count() method returns the number of items
on  a list that is equal to a
specified item.
 
For example;
>>>
num_list = [1, 2, 5, 8, 2, 9, 5, 2, 5, 10, 7, 5, 6]
 
>>>
num_list.count(5)
4
 
>>>
num_list.count(2)
3
 
>>>
num_list.count(9)
1
 
>>>
num_list.count(10)
1
 
Tuple
 
A tuple is an immutable data type that contains an
ordered collection of
objects. It can hold an unlimited number of items of
different types.

How
to Define a Tuple
To define a tuple, you will enclose the items within
round brackets () and
separate them with a comma:
 
Examples:
new_tuple =
(2, 1, 5, 9, 3, 8, 9)            
#numeric     
string_tuple =
("a", "age", "room")   #string
my_tuple =
(5,75, 12, "voucher")    #mixed
nest_tup
= ("red", (2, 4, 6), [9, 11, 13) 
  #nested
 
Python allows the creation of a tuple with one item.
To avoid conflict with
string creation, you will have to place a comma right after
the item to create
a distinction between a string and tuple:
 
tuple_color =
("blue",)
 
You can also create an empty tuple:
 
nil_tuple = ()
 
While you will always need a square bracket to create
a list, you can do
away with the parentheses to create a tuple:
 
numbers
= 5, 2, 8, 9, 3, 1
Accessing Tuple Elements
 
There are several ways to
access the elements in a tuple.
Indexing
You can access the items in a tuple through indexing
with the same syntax
and procedure you normally use to access a list.
 
To illustrate how indexing
works in tuples, create a new tuple with the
following elements:
>>>word
= ('e', 'n', 'v', 'i', 'r', 'o', 'n', 'm','e', 'n', 't')
To access the first item:
>>>
word[0]
'e'
 
To access the 7th
item:
>>>
word[6]
'n'
 
To access the 9th item:
 
>>>
word[8]
'e'
 
 
Negative Indexing
As it is a sequence type, it is possible to access a
tuple through negative
indexing. The last item has the -1 index, the
penultimate item -2, and so on.
 
Using the word tuple as an example:
 
>>>
word[-1]
't'
 
>>>
word[-5]
'n'
 
Slicing
Slicing is used to access a range of items in a tuple.
You will make use of
the slicing operator to indicate the index of the
elements you want to
access.
 
To illustrate how slicing works with a tuple, define a
new tuple:
 
>>>waste
= ("r", "e", "c", "y", "c",
"l", "e")
 
To access the third up to the fifth item:
 
>>>
waste[2:5]
('c', 'y',
'c')
 
Take note that the 3rd item, “c” is on
index 2 as the first item, “r”, is on
index 0.
 
To access the 5th to the last item:
 
>>>
waste[4:]
('c',
'l', 'e')
Modifying and Reassigning Tuples
 
In general, you cannot change
the elements of a tuple as it is immutable.
However, if a tuple contains an
item of a mutable data type such as a list,
you can modify an element on that
list.
For example:
>>>
my_tuple = ('writer', 75.5, 10, ['a', 2, 3, 4, 5])
To replace the first item of
on the nested list:
>>>
my_tuple[3][0] = 1
 
To view the updated tuple:
 
>>>
my_tuple
('writer',
75.5, 10, [1, 2, 3, 4, 5])
 
While you cannot modify tuple items of other data
types, you can easily
reassign a tuple with an entirely different set of
values.
 
For example, to reassign
my_tuple:
>>>
my_tuple = ('a','e','i','o', 'u')
 
Deleting Tuples
 
To delete a tuple, you will
use the keyword del.
syntax:  del tuple_name
Hence, to delete my_tuple:
del
my_tuple
 
Python Tuple Methods
 
index(a)    
 
Using the index() method on a tuple returns the
index of the first element
that is equal to the specified element.
syntax:
mytuple.index(x)
Example:
>>>
tuple1 = ('s','e','q','u','e','n','c','e')
>>>
tuple1.index('e')
1
 
>>>
tuple1.index('n')
5
 
count(a)   

When used on a tuple, the count() method


returns the number of elements
that is equal to the given element.
 
syntax:
mytuple.count(a)
 
Example:
>>>
tuple2 = ('f','i','r','s','t','c','l','a','s','s')
 
>>>
tuple2.count('s')
3
 
>>>
tuple2.count('r')
1
 
 
Set
 
A set is an unordered
collection of unique items. It is a mutable data type
that contains immutable
elements. Sets are used to perform mathematical
operations such as union,
intersection, or symmetric difference.
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 immutable items of
different data types such as
float, tuple, string, or integer. However, it
cannot contain mutable elements
such as a dictionary, list, or another set. A
comma separates set items.
 
Creating a Set
 
Here are examples of set
creation statements:
>>>
letter_set = {'a', 'b', 'c', 'd', 'e'}
>>>
number_set = {1, 5, 9, 13, 9.5, 12.5}
>>>
mixed_set = {12, "IDLE", (1, 5, 7), 12.5}
 
#set creation
from a list
 
>>>set([5,
2, 4, 1, 3, 4])
{1, 2, 3, 4,
5}    
 
A set’s elements can’t have a duplicate within the
set. Python evaluates the
set creation statement and drops the duplicate item.
 
Example:
Here is a set creation statement with duplicate item
‘red’:
>>>
colorset = {'green', 'red', 'orange', 'yellow', 'red', 'blue', 'purple'}
Python processes the statement and omits the duplicate
item. Hence, if you
view the content of ‘colorset’:
 
>>>
colorset
{'blue',
'green', 'yellow', 'orange', 'purple', 'red'}
 
To create an empty list, you will use the set()
function without providing an
argument.
 
Take note that you cannot use curly braces to create
an empty list as this
will conflict with the statement for the creation of an
empty dictionary.
 
Example:
>>>
empty_set = set()
>>>
type(empty_set)
<class
'set'>
 
Changing Elements on a Set
 
Sets are mutable which means that you can change their
elements.
However, since a set is unordered, you cannot access and change an
item
through indexing or slicing. You can, however, change the set elements
with
the add() or update() method.
 
The add() method is used to add a single
element to a set while the
update() method is used to add multiple
elements. You can use strings,
lists, tuples, or another set as argument to the
update() method.
To illustrate, create a new
set odd_set:
>>>
odd_set = {1,3,5,7,9}
 
To add an element to odd_set:
 
>>>
odd_set.add(11)
>>>
odd_set
{1, 3, 5, 7,
9, 11}
 
To add a set of elements to
odd_set:
>>>
odd_set.update([13,15,17])
 
To view the updated odd_set:
 
>>>
odd_set
{1, 3, 5, 7,
9, 11, 13, 15, 17}
 
Removing Set Elements
 
The remove() method or discard() method
can be used to remove a
specified item from a set. The difference between these
methods lies in their
response to a non-existent argument. The remove()
method causes the
program to raise an error when a given argument does not
exist. With the
discard()  method, the set is simply maintained and no
error is flagged.
Example:
 
To create a new set:
 
>>>
letter_set = {'a', 'b', 'z', 'c', 'x', 'd', 'y', 'e', 'f'}
 
To use discard() to
remove an element:
>>>
my_set.discard ('c')
>>>
my_set
{'a', 'f',
'b', 'e', 'd', 'g'}
 
To use remove() to remove an element:
 
>>>
letter_set.remove('y')
>>>
letter_set
{'c', 'e',
'b', 'f', 'd', 'z', 'a'}
 
If you use the discard() method on an item that
is not found on the set:
 
>>>
letter_set.discard('g')
>>>
letter_set
{'c', 'e',
'b', 'f', 'd', 'z', 'a'}
 
Discarding a non-existent item from a set has no
effect on the set or on the
program.
 
On the other hand, if you use the remove()
method to take out a non-
existent item, it will raise a KeyError.
 
Example:
>>>
letter_set.remove('y')
Traceback
(most recent call last):
  File
"<pyshell#23>", line 1, in <module>
   
letter_set.remove('y')
KeyError: 'y'
The pop() method is used to remove and return a
set element. Since a set is
unordered, the selection is arbitrary.
 
For example:
 
Create a set:
 
>>>
new_set = {'b', 'c', 'd', 'e', 'f'}
 
Use the pop() method to remove a random item:
 
>>>
new_set.pop()
'c'
 
View the updated set:
 
>>>
new_set
{'e', 'f',
'd', 'b'}
 
The clear() method is
used to remove all elements of a set.
>>>
new_set.clear()
>>>
new_set
set()
 
Set
Operations
 
Python sets are used to
perform various set operations.
Set Union
 
A union of two sets is a set that contains all
elements from the given sets.
You will use the | operator or the union()
method to carry out the operation.
The resulting set is a combination of all
elements that are returned in an
ascending order.
 
Examples:
>>> a
= {'a', 'e', 'i', 'o', 'u'}
>>> b
={'b', 'c', 'd', 'e'}
>>> a
| b
{'a', 'i',
'd', 'e', 'c', 'u', 'b', 'o'}
 
Another way to combine two
sets is the use of the union() method:
>>>
a.union(b)
{'a', 'i',
'd', 'e', 'c', 'u', 'b', 'o'}
 
or
 
>>> b.union(a)
{'a', 'i',
'd', 'e', 'c', 'u', 'b', 'o'}
 
Set Intersection
 
The intersection of two sets is 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.
 
Set intersection with & operator:
 
>>> x
= {5, 4, 3, 1, 2, 7, 8}
>>> y
= {8, 2, 9, 12, 4, 10, 6}
>>> x
& y
{8, 2, 4}
 
Set intersection with the intersection()
method:
 
>>>
x.intersection(y)
{8, 2, 4}
 
>>>
y.intersection(x)
{8, 2, 4}
Set
Difference
 
Set difference is the set of elements which are found
in one set but not in
another set. For example, the set difference between X
and Y (X-Y) is a set
of elements that occurs in X but not in Y. On the other
hand, the set
difference of Y and X (Y-X) is a set of elements that occur in Y
but not in
X. The set difference operations is implemented with either the –
operator
or the difference() method.
 
Example:
 
Given two sets x and y:
>>> x
= {1, 2, 4, 7, 9, 5, 3}
>>> y
= {2, 6, 9, 4, 10, 1, 12}
 
To find the set difference between x and y using the –
operator:
 
>>> x
- y
{3, 5, 7}
 
To find the set difference between y and x:
 
>>> y
- x
{10, 12, 6}
 
To find the set difference using the difference()
method:
 
>>>
x.difference(y)
{3, 5, 7}
 
>>>
y.difference(x)
{10, 12, 6}
Set
Symmetric Difference
Set symmetric difference is the set of elements which
are not common in
two sets. It is performed either with the ^ operator
or the
symmetric_difference() method.
 
Example:
Given two sets a and b:
>>> a
= {2, 4, 8, 10, 4, 1}
>>> b
= {1, 5, 8, 7, 12, 9}
 
To find the symmetric difference between a and b using
the ^ operator:
 
>>> a
^ b
{2, 4, 5, 7,
9, 10, 12}
 
>>> b
^ a
{2, 4, 5, 7,
9, 10, 12}
 
To find the symmetric difference using the symmetric_difference()
method:
 
>>>
a.symmetric_difference(b)
{2, 4, 5, 7,
9, 10, 12}
 
>>>
b.symmetric_difference(a)
{2, 4, 5, 7,
9, 10, 12}
 
Dictionary
A dictionary holds unordered
pairs of data. Each pair consists of a key and a
value which are joined by a
colon and separated from other pairs by a
comma. The keys are immutable data
which can only be a string, number,
or tuple. The values are mutable and they
can hold any type of data. You
can only access a value by accessing its key.
All elements of a dictionary
are enclosed in curly {} braces.
The key-value structure of a dictionary resembles the
structure used in
phone books, directories, and menu.
 
Creating a dictionary
Creating a dictionary is as easy as assigning
key-value pairs or an empty
pair of curly braces to a variable.
 
To set up an empty dictionary:
 
my_dict = {}
 
To define a dictionary with key-value pairs:
my_dict =
{key1:value1, key2:value2, key3:value3, key4:value4}
 
Accessing the Elements of a Dictionary
 
Since a dictionary is not an
ordered pair, you cannot use indexing to access
its elements. Instead, you have
to use its keys to access the data. There are
two ways to do it: by providing
the key of the value you need to access
inside square brackets or by applying
the get() method.
For example, create a new
dictionary with the given key-value pairs:
>>>employee_1
= {'Name':'Justin Banks', 'Age':25, 'Number':45}
 
To access the desired value, you can provide the key
inside the square
brackets:
 
>>>
employee_1['Name']
'Justin Banks'
 
>>>
employee_1['Age']
25
 
>>>
employee_1['Number']
45
 
To access the same values
using the get() method:
>>>
employee_1.get('Name')
'Justin Banks'
>>>
employee_1.get('Age')
25
 
>>>
employee_1.get('Number')
45
 
Adding and Modifying Dictionary Entries
 
You can add a new key-value pair to a dictionary with
an assignment
statement:
 
mydict [key] =
x     #x is the value assigned to the key
 
When you assign a new key:value pair to a
dictionary, Python will verify
whether it is a unique or duplicate key. If it
is a unique key, the new
key:value pair is added to the dictionary. If a
similar key exists on the
current dictionary, the value of the existing key is
replaced by the new value
given.
 
To illustrate, you can add a new key-value pair to the
dictionary
employee_1:
 
>>>
employee_1['Gender'] = 'Male'
 
To view the updated
dictionary:
>>>
employee_1
{'Name':
'Justin Banks', 'Gender': 'Male', 'Number': 45, 'Age': 25}
 
To modify a value in the dictionary, you can provide
the new value using
the assignment operator. For example, you can change
the age from 25 to
23 with this statement:
>>>
employee_1['Age'] = 23
 
To view the updated dictionary:
 
>>>
employee_1
{'Age': 23,
'Name': 'Justin Banks', 'Number': 45, 'Gender': 'Male'}
 
Removing or Deleting Dictionary Elements
 
To remove a key:value pair, you can use the pop()
method which removes
the pair and returns the value of the deleted key.
 
For example:
 
>>>my_dict
= {'ocean': 'Arctic Ocean', 'Sea': 'Dead Sea', 'river':'
Mississippi River',
'swamp': 'Okefenokee'}
 
To remove the key ‘swamp’ and its value:
 
>>>
my_dict.pop('swamp')
'Okefenokee'
 
To view the updated
dictionary:
>>>
my_dict
{'ocean':
'Arctic Ocean', 'Sea': 'Dead Sea', 'river': ' Mississippi River'}
 
The popitem() method is another way to remove
key:value pairs. This
method removes and returns a random pair from a
dictionary and takes no
argument.
To illustrate, use the popitem() method on
my_dict:
 
>>> my_dict.popitem()
('ocean',
'Arctic Ocean')
 
The popitem() method randomly removed and
returned the key-value pair
of ocean:Arctic Ocean.
 
To view what’s left of the dictionary:
 
>>>
my_dict
{'Sea': 'Dead
Sea', 'river': ' Mississippi River'}
 
To remove the remaining pairs, you can use the clear()
method:
 
>>>
my_dict.clear()
 
To totally delete my_dict dictionary, you will use the
del keyword:
 
>>>del
my_dict
Other Dictionary Methods
 
keys() method
 
syntax: dict.keys()
 
The keys() method returns a list of dictionary
keys.
 
For example:
>>>vehicles
= {1:'car', 2:'bus', 3:'train', 4:'rail', 5:'taxi'}
 
>>>
vehicles.keys()
dict_keys([1,
2, 3, 4, 5])
 
values() method  
syntax: dict.values()
 
The values() method returns a list of all dictionary
values.
 
>>>vehicles
= {1:'car', 2:'bus', 3:'train', 4:'rail', 5:'taxi'}
 
>>>vehicles.values()
dict_values(['car',
'bus', 'train', 'rail', 'taxi'])
 
update(other)      
 
The update(other) method updates a dictionary
with key-value pairs from
another dictionary. It merges the key-value pairs of
another dictionary with
the base dictionary. When there are common keys between
the dictionaries,
the value of the other key overwrites that of the current
dictionary.
 
Example:
 
>>>
dict_a = {'First Name':'Marcus', 'Age': 25, 'Branch':'Florida'}
 
>>>
dict_b = {'Last Name':'Guy', 'Age':27,'Position':'Supervisor',
'Branch':'New
York'}
 

 
To merge the two
dictionaries:
>>>
dict_a.update(dict_b)
 
To view both dictionaries
after the update:
>>>
dict_a
{'Position':
'Supervisor', 'First Name': 'Marcus', 'Branch': 'New York',
'Age': 27, 'Last
Name': 'Guy'}
 
>>>
dict_b
{'Age': 27,
'Position': 'Supervisor', 'Last Name': 'Guy', 'Branch': 'New
York'}
 
The dict_a key-value pairs reflected the merged
key-value pairs. On the
other hand, no update was made to dict_b.
 
setdefault() method
 
The setdefault() method searches for a given
dictionary key and returns the
value if found. Otherwise, it returns the
specified default value and adds it
to the new dictionary.
 
syntax:
 
dict.setdefault(key,
default=None)
 
Example:
 
>>>
birds = {1:'hawk', 2:'eagle', 3:'owl', 4:'kingfisher'}
 
To use set.default() to search for a key:
 
>>>
birds.setdefault(3, None)
'owl'
 
The setdefault() method searched and found the
key 3 and returned its
value.
 
This time, use the setdefault() method to
search for a key and provide a
value if the key is not found:
 
>>>
birds.setdefault(5, 'Hummingbird')
'Hummingbird'
 
To view the updated dictionary:
 
>>>
birds
{1: 'hawk', 2:
'eagle', 3: 'owl', 4: 'kingfisher', 5: 'Hummingbird'}
 
The copy() method
 
The copy() method does a shallow copy of a
dictionary in which each key-
value pair is duplicated. The method facilitates
editing of a copy or reuse of
the copy without altering the original copy.
 
#original
dictionary
>>>
supplies = {'screw': 15, 'hinge': 12, 'knob': 4, 'runner': 20}
 
#
Create a copy of supplies dictionary:
>>>
hardware = supplies.copy()
 
fromkeys() method
 
The fromkeys() method takes items from a
sequence and uses them as keys
to create a new dictionary. It takes a second
argument which will allow you
to specify a value that will be attached to the
keys of the new dictionary.
 
Here’s a list that will be
used to build a dictionary:
keys =
["paper", "pencil", "pen",
"highlighter",  "eraser"]
 
To create a new dictionary from keys list:
 
>>>
supplies = dict.fromkeys(keys, 15)
 
To view the new supplies
dictionary:
>>>
print(os)
{'highlighter':
15, 'pencil': 15, 'paper': 15, 'eraser': 15, 'pen': 15}
 
Chapter 6

 Functions and Modules


 

Functions
A function is a block of related statements
that performs a specific task.
Functions are reusable structures that you can
incorporate as often as you
want in your program. They make programming more efficient
by reducing
code duplication. They simplify a long and complex program by
decomposing it into simpler pieces of codes. They make programs more
readable.
Function is an object and it can be used
just like any other object in Python.
They can be assigned to variables or
passed as arguments.
There are two types of functions in Python:
 
Built-in functions
User-defined functions
 
Built-in Functions
 
The following are built-in functions that you can
readily use in your
programs:
 
abs() all() ascii()
any() bin() bool()
bytes() bytearray() callable()
chr() compile() classmethod()
complex() delattr() dir()
dict() divmod() enumerate()
exec() eval() filter()
format() float() frozenset()
globals() 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()
 
Here are some of the most commonly used built-in
functions and their
usage:
 
abs()           returns the absolute value of a number
 
>>>
abs(-20)
20
 
print()   print values to screen
 
>>>
print('Programming is fun!')
Programming is
fun!
 
len()    returns the size or length of an object
 
Size of a string:
>>>
len("Programs")
8
 
Size of a list:
>>>
len(['red', 'yellow', 'orange', 'blue', 'green', 'violet'])
6
 
Size of a dictionary:
>>>
len({'student1':'Mark', 'student2':'Gladys', 'student3':'Marie'})
3
 
max()         returns the largest item
>>>
my_list =[1, 35, -100, 90, 40]
>>>
max(my_list)
90
 
min()   returns the smallest item
>>>
my_tup = (23, 19, 8,4, -100)
>>>
min(my_tup)
-100
 
input()  reads keyboard input and returns string
 
The input() function has an optional parameter, a
prompt string, which is
displayed onscreen when the function is called. Python
returns the user’s
response as a string.
For example, here is a program that asks for the name
and age of the user
and prints the information given as string:
 
name =
input('Please enter your name: ')
print('Hello,
' + name + '!')
age =
input('Please enter your age ')
print('Your
name is ' + name + ' and you are ' + age + ' years old.')
 
If you enter ‘David’ and ‘25’, here’s how it would
look on screen:
 
Please enter
your name: David
Hello, David!
Please enter
your age 25
Your name is
David and you are 25 years old.
 
round()       returns the rounded value of a float
>>>
round(25.76)
26
 
id()        returns the memory location of an object
>>> a
= "address"
>>> b
= 24
>>>
id(a)
13757888
>>>
id(b)
1580423808
       
type()  returns object type
>>>
a= 'random'
>>>
type(a)
<class
'str'>
 
>>> b
= ['r', 'a', 'n', 'd', 'o', 'm']
>>>
type(b)
<class
'list'>
 
>>> c
= ('apple', 'pear', 'banana', 'pineapple')
>>>
type(c)
<class
'tuple'>
 
range()       returns an iterable sequence
 
The range() function is used to create an
iterator or  list with arithmetic
progression. It takes a minimum of 1 and a
maximum of 3 integers as
arguments.
 
syntax: range(start, end, step)
 
When only one argument is given, it is considered the
‘end’ of range
argument. When both start and step arguments are omitted, the
range
defaults to the starting point of zero and progression of 1.
 
Examples:
 
>>> range(12)
range(0, 12)
 
To create a list from a given range:
 
>>>
list(range(12))
[0, 1, 2, 3,
4, 5, 6, 7, 8, 9, 10, 11]
 
>>>
list(range(2, 14, 2))
[2, 4, 6, 8,
10, 12]
 
list()     returns a list
 
To create a list from a given string:
 
>>>
list('Python')
['P', 'y',
't', 'h', 'o', 'n']
 
To create a list from a dictionary:
>>>
my_dict = {'color':'blue', 'item':'slacks', 'size':'medium'}
>>>
list(my_dict)
['color',
'item', 'size']
 
dict()   creates 
new dictionary from tuple pairs
 
First, create a list out of tuple pairs:
 
>>>pairs
= [("color", "yellow"), ("animal",
"cat"), ("size", "small")]
 
Next, convert the list to a dictionary using the dict()
function:
 
>>>
new_dict = dict(pairs)
 
To view the new dictionary:
 
>>>
print(new_dict)
{'color':
'yellow', 'size': 'small', 'animal': 'cat'}
 
str()       returns a string format of an object
 
The str() function is used to convert
non-string data to string data.
 
Example:
 
>>>
grade = 96.75
>>>
print('Her average grade is ' + str(grade))
Her average
grade is 96.75
 
User-Defined Functions
 
User-defined functions are created using
Python’s def keyword.
 
Defining a Function
 
To define a function, you will use the def
keyword followed by the function
name, parentheses, and colon. The function’s
body starts on the first
indented line:
 
def
function():
   
function body
 
Programmers usually include a docstring
that explains what the function
does. The docstring is written at the top of
the function’s body.
 
The body of a function may consist of one
or more statements and each line
must use the same indentation to form a block.
 
Parameters or arguments are enclosed in
parentheses. They are used to pass
values to functions. A function can have
optional or default parameters.
Optional parameters need not be provided when
the function is called. The
default values are used when no parameter is given.
 
To illustrate, here is a simple function
that you can type and save on the
editor:
def
Greeter(name="Buddy"):
   
""" Greets a member """
   
print("Good day, " + name + "!")
If you run the
function, you will notice that it doesn’t do anything at all. A
function can
only perform its specific task if you call it. One way of calling
a function is
through the Python prompt.
In the above example, you defined the
function Greet. To call it on the
command prompt with the argument ‘Mitch’:
>>>
print(Greeter('Mitch'))
Good
day, Mitch!
None
 
Notice that it returned the parameters on
the print statement along with the
argument you have supplied.
 
To call the function without supplying
parameters:
>>>
print(Greeter())
Good
day, Buddy!
None
The function returned the parameters on the
print statement along with the
default parameter, ‘Buddy’. Take note that the
function also returned
‘None’.
A function may or may not return a value.
If you want the function to return
a value, you must use a return statement
inside the block. If you don’t
include a return statement as in the Greet
function, the function will return
‘None’.
A return statement uses this syntax:
return
[expression]
 
Here’s a function with a return statement:
def
abs_val(num):
  
"""Returns the absolute value of
        
a number"""
  
if num >= 0:
      
return num
  
else:
      
return -num
 
If you call the function abs_val on the
command prompt:
>>>
print(abs_val(19))
19
 
>>>
print(abs_val(-10))
10
 
A function can
have more than one parameter and each can have default
argument. Non-default
argument/s should always be placed to the left of
those with default arguments.
Here’s a function with two arguments:
 
def
Hello(name, message = 'Good Day'):
   
""" Greets someone and prints a message"""
   
print('Hi' , name + ', ' + message + ‘!’)
 
This time, the function Hello
was called within the program. Since the
parameter ‘name’ lacks a default
argument, you have to provide an
argument when you call the function. If you
run it, you will have this
output:
Hi
Duffy, Good Day!
Hi
Kitty, Happy Birthday!
 
Keyword Arguments
 
By default, the values you supply when you call a
function are assigned
based on the position of the arguments. Hence, when you
supplied the value
‘Duffy’, Python assigned it to the first argument on the
function, ‘name’.
You can override this default arrangement by using keyword
arguments
when you call the function.
 
Keyword arguments are those that assign a value to the
parameter name on
function call.
 
For example, you can call the function Hello on the
command prompt with
these keyword arguments:
 
>>>
Hello(name='Martin', message='Good Afternoon')
Hi Martin,
Good Afternoon!
>>>
Hello(message='Happy Birthday', name='Kitty')
Hi Kitty,
Happy Birthday!
 
When you call a function using both positional and
keyword arguments, the
positional argument must always precede the keyword
argument.
 
For instance, this function call is correct:
 
>>>
Hello('Mitchell', message = 'Happy Anniversary')
Hi Mitchell,
Happy Anniversary!
 
This one will raise an error:
 
>>>
Hello(message = 'Happy Anniversary', name)
SyntaxError:
positional argument follows keyword argument
 
Arbitrary Arguments
 
In some cases, a program may require calling a function
with yet to be
determined number of arguments. Python facilitates this type of
function
call with arbitrary arguments.
 
For example, here’s a function that uses arbitrary
arguments:
 
def
Hello(*students):
   """Greets all names in the students
tuple"""
 
   for name in
students:
      
print("Good day",name)
 
Hello("Melissa","Katherine","Jasmine","Rosemary")
Running the program will yield the following:
 
Good day
Melissa
Good day
Katherine
Good day
Jasmine
Good day
Rosemary
 
Functions calling another function
 
A function can also call another function.
Here’s an example:
#month_sum
calls the week_sum function
 
def
week_sum(num):
    return num
* 5
 
def
month_sum(a):
    return
week_sum(a) + 5
 
print(month_sum(10))
print(month_sum(3))
print(month_sum(5))
 
The output would be:
 
55
20
30
 

 
Modules
 
A module is a file that contains codes,
statements, or definitions. Python has
several custom modules but you can also
make your own. Modules help
make programming more efficient by supporting code
reusability across
different programs and platforms. For instance, you can save
one or more
function definitions in a module and simply import the module and
access a
function as often as you need in your programs. That will save you a
lot of
typing time and make your program look more compact and organized.
 
To illustrate, you can create a module that
contains the definition of three
functions: adder, multiplier, and square. Save
the module as calculator.py:
 
def
adder(num1, num2):
 
  
"""Adds the supplied values and returns the
result"""
 
  
total = num1 +num2
  
return total
 
def
multiplier(num1, num2):
   
"""Multiplies the given values and returns the result
"""
 
   
product = num1 * num2
   
return product
 
def
square(num):
   
"""Doubles the given value and returns the
result"""
   
   
squared = num**2
   
return squared
 
You have to close the file after saving to
prepare it for further processing.
Importing a Module
 
You can only use a module after importing
it in your program. You can do
this with the keyword import and the module
name. To import the
calculator module you created above:
>>>
import calculator
 
The calculator module is now in the active
memory of Python and you can
start using the stored function definitions by
calling them on the command
prompt:
>>>
adder(25, 105)
130
 
>>>
multiplier(3,4)
12
 
>>>
square(8)
64
 
Built-in Modules
 
Python has several custom modules that you
can import in your programs.
These include the math module, random module, time
module, and calendar
modules.
Math Module
 
The math module is one of the most commonly used modules in
Python.
Importing it will provide access to its constants, attributes, and a
wide range
of mathematical functions such as square root, pi, gcd, sine, and cosine.
To
access the contents of the math module, you’ll use a dot operator on math
and specify the method or attribute after the dot.
To import the math module:
>>>import
math
To view the contents of the
math module, you will use the dir keyword:
>>>import
math

To access its definitions and functions:


>>>
math.sqrt(81)
9.0
>>>
math.pi
3.141592653589793
 
>>>
math.gcd(4, 18)
2
 
The Random Module
 
The random module is used when you want a
program to produce a random
item within a specified range. Importing the random
module will give you
access to several functions that are commonly used in
games. You can make
simple games like roll-a-dice, flip-a-coin, pick-a-card and
other games that
require users to pick a random element from a list.
 
To access the contents of the random
module, you have to import the
module:
import
random
Functions
 
The following are the most common random
module functions:
randint
 
The randint() function accepts two
arguments and generates a random
integer. The first argument is the floor value
while the second argument is
the ceiling.
Example:
>>>import
random
>>>print
random.randint(1, 5)
The output would be any of the integers 1,
2, 3, 4, 5.
choice
The choice() function generates a
random value from a sequence.
For example:
import
random
cards
= (['Ace', 2, 3, 4, 5, 6, 7, 8, 9,'King', 'Queen'])
random.choice(cards)
 
print(random.choice(cards)
print(random.choice(cards)
print(random.choice(cards)
 
If you run the program, you might pick
similar results:
2
9
5
 
shuffle
The shuffle() function sorts the
elements on a list and arranges them in
random order.
The syntax is:
random.shuffle(list)
 
Example:
import
random
animals
= ['rabbit', 'elephant', 'tiger', 'giraffe', 'cat']
random.shuffle(animals)
 
print(animals)
 
If you run this code, the result may look
similar to this list:
['cat',
'tiger', 'giraffe', 'rabbit', 'elephant']
 
randrange
The randrange() function generates a
random element from a given range.
Syntax:
random.randrange(start,
stop[, step])
 
Example:
 
import
random
for
y in range(6):
   
print(random.randrange(0, 25, 2))
 
The above code will generate 6 random
numbers:
2
22
14
6
22
12
Practice Set 1:

 Weighted Average
 

 
Students’ quarterly grades are usually computed using
the weighted average
method in which the average of each grading criterion is
given a certain
percentage that adds up to a total of 100%.
 
Following are the grades of the three students in a
class:
 
David Michael 
           Quizzes: 90.5, 95.0, 89.0, 90.0
           Recitation: 88.5, 91.0, 90.0
           Homework: 89.0, 60.0, 98.0
           Test: 85.0
 
Mitchell Buffet
           Quizzes: 100.0, 98.0, 95.0, 100.0
           Recitation: 90.5, 85.0, 95.0
           Homework: 85.0, 75.0, 90.0
           Test: 87.0
 
Danielle Gates
           Quizzes: 99.0, 100.00, 93.0.0, 98.5
           Recitation: 92.0, 87.0, 93.0
           Homework: 99.0, 85.0, 94.0
           Test: 92.0
 
Following are the assigned percentages for each
grading category:
 
Quizzes        30%
Homework  10%
Recitation   30%
Test              30%
 
Instruction:
Write a Python program that
will print the names of the students on
one column and their corresponding
weighted average on the next.
Chapter 7

  Decision Making and Flow Control


 
Decision Making
 
Decision making structures are required whenever you
want a program to
implement a course of action each time a test condition is
satisfied.
 
A decision making block starts with a Boolean
expression. The program
will proceed depending on whether the response is True
or False.
 
Python supports the following decision making
structures
 
if
statements
if else
statements
if…elif…else
statements
 
 
if statements
syntax:
if expression:
   
statement(s)
 
Example:
age =
int(input("Enter your age: "))
if age >=
18:
   
print("Welcome to Wise Adults Forum!")
print("We
accept members from age 18 and above.")
 
When a user responds with ‘19’ to the prompt string,
here’s the onscreen
output:
 
Enter your
age: 19
Welcome to
Wise Adults Forum!
We accept
members from age 18 and above.
 
When a users responds with
‘12’:
Enter your
age: 12
We accept members
from age 18 and above.
 
 
if…else statements
 
In an if…else structure,
Python executes the ‘if block’ if the test condition
yields True and the ‘else
block’ if the condition is False.
syntax:
 
if test
condition:
   
statement(s)
else:
   
statement(s)
 
Example:
#this program
checks if a food order is available
items =
['French Fries', 'Nuggets', 'Pizza', 'Pho', 'Ramen']
 
order =
input("Please enter an order: ")
if order in
items:
   
print("You order of " + order + " will be served in 5
minutes.")
else:
   
print("Sorry, " + order + " is not available at this
time.")
 
If the user responds with
‘Pizza’, the output would be:
Please enter
an order: Pizza
You order of
Pizza will be served in 5 minutes.
 
If the user enters ‘Burger’:
 
Please enter
an order: Burger
Sorry, Burger
is not available at this time.
 
if…elif…if statements
An if…elif…if structure
facilitates the evaluation of multiple expressions.
If the ‘if test expression’
is True, it executes the ‘if block’. If False, it
evaluates the elif (else if)
block. If the ‘elif text condition’ is True, it
executes the elif block. If
False, it executes the else block.
 
syntax:
 
if test
condition:
    if block
elif test
condition:
    elif block
else:
    else block

Example:
#this program
checks if an order is available
#if not
available, it will check if the ordered item is on the pending list
and prints
an appropriate remark
#if the order
is neither available nor pending, the program prints an
appropriate remark
 
available
= ['French Fries', 'Nuggets', 'Pizza', 'Pho', 'Ramen']
pending =
['Barbeque', 'Cheeseburger', 'Tacos']
 
order
= input("Please enter an order: ")
if
order in available:
   
print("You order of " + order + " will be served in 5
minutes.")
elif
order in pending:
   
print("Your order of " + order + " will be served in 15
minutes.")
else:
   
print("Sorry, " + order + " is not available at this
time.")
 
If the user enters Ramen, an item on the available
list:
 
Please enter
an order: Ramen
You order of
Ramen will be served in 5 minutes.
 
If the user enters ‘Tacos’, an item on the pending
list:
 
Please enter
an order: Tacos
Your order of
Tacos will be served in 15 minutes.
 
If the user enters Noodles which is not on available
or pending list:
 
Please enter
an order: Noodles
Sorry, Noodles
is not available at this time.
 
Flow Control
 
A loop is a program control structure that facilitates
complicated execution
paths and repetitive execution of a statement or block of
statements.
 
For Loop
 
A ‘for loop’ is used to iterate over elements of
ordered data types such as
lists, tuples, or strings.
 
Syntax:
 
for val in
sequence:
   
statement(s)
 
In a ‘for loop, the variable holds the value of each
item on the sequence
with every iteration. The loop runs until all items are
processed.
 
Examples:
 
For Loop over a string:
 
for letter in
'Finance':             
  
print('<**', letter, '**>')
 
If you run the loop, this would be the output:
 
<** F
**>
<** i
**>
<** n
**>
<** a
**>
<** n
**>
<** c
**>
<** e
**>
 
for Loop over a list:
 
#iterate over
a list
 
animals 
= ['dog', 'cheetah', 'leopard', 'kangaroo', 'leopard']
 
for x in
animals:
    print('A '
+ x + ' is a cool animal')
print('These
animals are great!')
 
If you run the loop, this will be your output:
 
A dog is a
cool animal
A cheetah is a
cool animal
A leopard is a
cool animal
A kangaroo is
a cool animal
A leopard is a
cool animal
These animals
are great!
Notice that after all the animal names in
the list have been processed by the
loop, control passes to the unindented
print statement.
The While Loop
 
The ‘while loop’ is used when you want to repeatedly
execute a statement
or group of statements while the test condition is True.
When it’s no longer
True, control passes to the line after the loop.
 
syntax:
 
while
condition
   
statement(s)
 
Example:
 
#program adds
number up to an entered number
#total =
1+2+3…+number
 
x =
int(input("Enter a number: "))
 
#initialize
sum and counter
total = 0
ctr = 1
 
while ctr
<= x:
    total =
total + ctr
    ctr = ctr
+ 1             
 
#print the sum
print("The
sum is: ", total)
If you run the program and enter 1, 6, and 10, you
will get these results:
 
Enter a
number: 1
The sum is:  1
 
Enter a
number: 6
The sum is: 
21             #1+2+3+4+5+6
 
Enter a
number: 10           #1+2+3+4+5+6+7+8+9+10
The sum is: 
55
 
Break Statement
 
A break statement ends the loop and passes control to
the statement
immediately after the loop. It allows the termination of the
current iteration
or the loop regardless of the test condition and effectively
prevents the
execution of the ‘else’ statement. It is used when an external
condition
requires immediate exit from the loop.
 
Example:
 
#loop ends
once it reaches a given number
 
contestants =
[1, 2, 3, 4, 5, 6, 7, 8, 9]
 
for num in
contestants:    
   if num ==
5:
      break
   print('In
:', num)
print("Congratulations!")
 
Once it reaches number 5, the loop ends and control
passes to the next
unindented line:
 
In : 1
In : 2
In : 3
In : 4
Congratulations!
 
Continue Statement
 
The continue statement directs the program to proceed
to the next iteration
after reaching a specified item in the list.
 
To illustrate, you can use the above example and
replace the break
statement with the continue statement:
 
contestants =
[1, 2, 3, 4, 5, 6, 7, 8, 9]
 
for num in
contestants:    
   if num ==
5:
      continue
   print('In
:', num)
print("Congratulations!")
 
When you run the program, it skips iteration for
number 5 and proceeds to
the other numbers on the list:
 
In : 1
In : 2
In : 3
In : 4
In : 6
In : 7
In : 8
In : 9
Congratulations!
 
Pass Statement
 
Pass is a null operation in which the interpreter
reads the statement but does
nothing. It is typically used as a place holder
for a statement required by
syntax but is not available when a program has to
be run. Programmers use
the pass statement in place of unwritten codes to allow
them to test other
parts of the program.
 
Syntax:
   pass
 
Example:
#pass
statement in an empty function block
def adder(a): 
   
pass
Try and Except Statements
 
Python’s built-in exceptions cause a program to return
an error whenever a
problem occurs. When an error or exception occurs, the
current process
terminates and control passes to the calling process and so on
until it is
handled. Failure to handle the error or exception will cause the
program to
crash.
 
Try and except statements are
used to handle program errors in Python. A
critical area of a program is placed
within the ‘try clause’ while the
statement/s that will handle the exception is
given within the ‘except
clause’.
Example:
try:
    x =
int(input("Please enter a number: "))
   
print("You entered %d." % x)
except
ValueError:
   
print("You entered an invalid character. Please try again.")
 
Python will attempt to
execute the statement/s within the ‘try block’. In this
part of the program,
there is a possibility that a value other than a number
will be entered by a
user. Hence, this block was placed under the try clause.
Whenever a ValueError
is encountered, control passes to the ‘except block’
which handles the error. 
If you test the program using
an integer and a letter input, here’s what you
would get:
Please
enter a number: 5
You
entered 5.
Please
enter a number: a
You
entered an invalid character. Please try again.
Practice Set 2

 Password Verification
 

 
You are given the following details from a company’s
database:
Users    Password
Marie    201624
Mark     MARKbest
Mandy  Man5254
Fred      9595
Instructions:
Prepare a program that will ask for the user’s name. If
the user’s name
does not match any of the names in the database, print ‘Sorry,
you
don’t have access to this system. If the user’s name matches one of the
user names in the above database, ask the user to enter a password. If
the
given password matches the password under the user’s name, print
‘Thank you’.
If the given password doesn’t match the user’s password,
print ‘You entered an
invalid password.’
 
Chapter 8

 File Management
 

 
File is a named memory location that is used to store and
access data.
Python manages file through a file object.
There are 4 basic file
operations in Python:
·      
opening a file
·      
reading from a file
·      
writing to a file
·      
closing a file
 
Opening a File
 
The open() function creates a file object or
handle that can be used to call
other methods.  You will use this function to
open the file for reading,
writing, or both.
syntax:
file object=open(filename [, access_mode][,
buffering])
 
The filename refers to the file that you want to
access.
The access mode is an optional parameter that will
allow you to specify the
access mode. There are two types of files that can be
opened: a text file and
binary file. There are several access modes for both
files.
Modes for Accessing Text Files
r      read mode (default); opens  a file
for reading
w         write mode; creates a new file or overwrites
existing one
r+   read and write mode
w+      read and write mode; creates a new file or
overwrites an existing one
a          append mode; adds data at end of file or
creates  new file if the file
is non-existent
a+       read and append mode: appends data at end of
file or creates new file
if file is non-existent
x          opens file for exclusive creation and fails
if the file is already in
existence
 
Modes for Accessing Binary Files
rb+      read and write
wb+    read and write mode; creates a new file or
overwrite an existing file
ab+     read and append mode; adds data at end of file
or create a new file if
the file is non-existent

The buffering option lets users


specify their preferred buffering style. When
the value given is one, buffering
is implemented as you access files. When
the value exceeds one, buffering is
carried out according to the specified
buffer size. When a negative value is
given, Python uses the system default.
To open a file in the default mode, the
read mode:
 
f = open("diary.txt")     
 
To open a file in write mode:
 
f = open("diary.txt",'w')
 
To read and write to a file in binary format:
f = open("reflection.bmp",'rb+')
 
Writing to a File
 
Before you can start writing
to a file, you have to open the file with a file
object:
>>> notes = open("myfile.txt",
"w")
 
To start writing to a file, you will use
the write method on the file object:
 
>>>
notes.write("A file can be used to store important data.")
43
>>>
notes.write("Files are objects that you can use in your
program.")
51
 
Python returns the number of characters written on
each line.
When you’re
done writing to a file, you have to close the file for proper
processing and to
avoid accidental erasure or alteration:
 
notes.close()
 
Reading a File
 
There are several ways to read
a file:
·      
the readlines() method
·      
‘while’ statement
·      
through an iterator
 
The readlines() Method
The readlines() method is a simple way to read and parse
lines in a text file.
Using the file you created above, here are the steps:
Use a file object to open the file:
>>> notes = open("myfile.txt",
"r")
 
Use the readlines() method on the file object to read each
text line from the
file. Create a variable that will store the text lines read:
 
>>> lines = notes.readlines()
 
Type the variable name on the Python prompt to access the
contents of the
file:
 
>>> lines
['A
file can be used to store important data. Files are objects that you
can use in
your program.']
 
Close the file:
>>>notes.close()
 
Reading Files with a ‘while
loop’
Reading files with a ‘while loop’ is a
more efficient way to read larger files.
To illustrate, build a new file with
the open() function:
>>>
message = open("newfile.txt", "w")
 
Write the following lines with a new line character
(\n) at the end of each
line:
 
>>>
message.write("This file stores important messages.\n")
37
 
>>>
message.write("Attendance is a must.\n")
22
 
 
Close the
file:
 
>>>message.close()
 
To read the file using the readline method and the
while loop:
# Open the linefile.txt on read only mode:
message = open('newfile.txt')
 
# Read the first line
textline = message.readline()
 
# keep reading line one at a time until file is
empty
while textline:
    print(textline)
    textline = message.readline()
message.close()
 
When you run the above program, you will see the
following line-by-line
output on the Python shell:
This file stores important messages.
 
Attendance is a must.
 
Reading
files with an iterator:
 
To read the
newfile.txt with an iterator:
 
message = open('newfile.txt')
 
for x in iter(message):
    print(x)
 
message.close()
 
Appending
Data to a File
 
To append data to an existing file, you
need to open the file on append
mode.
 
For example, to append data to
newfile.txt, open the file and assign it to a
new file handle:
 
>>> messages = open('newfile.txt', 'a')
 
Write a new line using the write method:
messages.write("Appending a line is as easy
as writing a new line.")
50
 
Close the
file:
 
>>> messages.close()
 
Use readlines() to view the updated
newfile.txt:
>>>messages
= open('newfile.txt')
>>>
lines = messages.readlines()
>>> lines
['This
file stores important messages.\n', 'Attendance is a must.\n',
'Appending a
line is as easy as writing a new line.']
Chapter 9

 Regular Expressions
 

 
A regular expression is used to
search, filter, replace, and parse text or
textstrings with complex character
patterns. It is a sequence of characters
that you will use to search for
strings or groups of strings.
Regular expressions are used
with a specialized syntax under Python’s re
module.
The re module is most
commonly used to find patterns in a text.
For example, to search for the
terms ‘both’ and ‘catch’ in a statement:
import re
searchterms = [ 'both', 'catch' ]
text = 'How do you catch a fish?'
for item in searchterms:
    print('Searching for "%s" in
"%s" ->' % (item, text))
    if re.search(item, text):
        print('Found it!')
    else:
        print('Sorry, no match!')

The output would be:


Searching for "both" in "How do you
catch a fish?" ->
Sorry, no match!
Searching for "catch" in "How do
you catch a fish?" ->
Found
it!
Chapter 10

 Solution
to Practice Sets
 
Practice Set 1: Weighted Average
 
David =
{'Name': 'David Michael', 
'Quizzes': [90, 95., 89.0, 90.0],
'Recitation': [88.5, 91.0, 90.0],
'Homework': [89.0, 60.0, 98.0],
'Tests': [85.0, 90.0]}
 
Mitchell =
{'Name': 'Mitchell Buffet',
'Quizzes': [100.0, 98.0, 95.0, 100.0],
'Recitation': [90.5, 85.0, 95.0],
'Homework': [85.0, 75.0, 90.0],
'Tests': [87.0, 92.0]}
 
Danielle =  {'Name':
'Danielle Gates',
'Quizzes': [99.0, 100.00, 93.0, 98.5],
'Recitation': [92.0, 87.0, 93.0],
'Homework': [99.0, 85.0, 94.0],
'Tests': [92.0, 94.0]}
 
def
average(numbers):
 total=sum(numbers)
 result = total/len(numbers)
 return result
   
 
def get_average(student):
    Quizzes =
average(student['Quizzes'])
    Recitation
= average(student['Recitation'])
    Homework =
average(student['Homework'])
    Tests =
average(student['Tests'])
   
print(student['Name'])
    return
.3*Quizzes + .3*Recitation + .1*Homework + .3*Tests
 
print(get_average(David))
print(get_average(Mitchell))
print(get_average(Danielle))
 
Practice Set 2: Password Verification
 
usernames
= {'Marie':'201624', 'Mark':'MARKbest', 
'Mandy':'Man5254', 'Fred':'9595'}
 
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 invalid password.')
 
else:
   
print("Sorry, you don't have access to this system.")
Conclusion

 
I hope this book was able to help you learn the essentials
of Python
Programming and inspire you to create relevant and practical
programs.
The next step is to take your learning to the next level and
acquire advance
skills to develop larger and more useful programs that will
make use of the
many powerful features of Python. 
I wish you the best of luck!
 

You might also like