Professional Documents
Culture Documents
Untitled
Untitled
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
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
Installing Python in Mac
Mac users can download the
installation package from this link:
https://www.python.org/downloads/mac-osx/
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
File Menu
The
Edit Menu
The
Shell Menu
The Shell menu has options for viewing the
most recent restart and for
restarting the Python Shell.
The
Debug Menu
The
Window Menu
The
Help Menu
The Help menu allows users to access
Python’s documentation and help
files.
Using
IDLE to Write Your Program
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
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:
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
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
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)
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
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
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
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
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!')
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!