Programming in Python PDF
Programming in Python PDF
This module covers the knowledge, skills and attitude in understanding computer
programming. This includes (1) learning the concepts behind the creation and
development of computer programs, (2) familiarizing the syntax of Python programming
language and (3) performing sequential programming using Python.
To get the most from this Module, you need to do the following:
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.1
PROGRAMMING FUNDAMENTALS II
At the end of the lesson the learner will be able to identify the different
generations through which programming languages have evolved, differentiate the
characteristics of these generations of programming languages and explain the
motivation behind the evolution of programming languages from one generation to the
next.
What I Know
Before starting with this module, let us measure what you already know about
Computer Programming. This will give you an idea of the lessons that you will come
across within this subject. Follow and answer the activity below.
Instruction: Read the statements carefully then answer the following questions to test
your understanding on Computer Programming.
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.2
UNDERSTANDING COMPUTER PROGRAMMING
Programming
We have seen how computers and mobile devices changed the way the world
moves. They perform and automate tasks instantly. Computers automatically scan the
barcode, calculate the total price of the groceries, accept payment, and then compute
the change. Smartphones, on the other hand, display the letters that we type, then send
the message to the recipient as soon as the Send button is pressed.
These devices, however, would not work without something telling them what to
do. They follow a program. A program is a set of specific instructions that tells the
computer what to do. If done correctly, the computer executes the program. The
process of creating a set of instructions or program is known as programming. It is also
referred to as coding.
Program Development Life Cycle
Programmers follow a guide that helps them create and develop any type of
program. This guide is called program development life cycle (PDLC). It involves five (5)
phases:
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.3
GETTING STARTED WITH PYTHON
Python Overview
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable. It uses English keywords frequently where as
other languages use punctuation, and it has fewer syntactical constructions than other
languages.
∙ Python is Interpreted − Python is processed at runtime by the interpreter. You do
not need to compile your program before executing it. This is similar to PERL
and PHP.
∙ Python is Interactive − You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
∙ Python is Object-Oriented − Python supports Object-Oriented style or technique
of programming that encapsulates code within objects.
∙ Python is a Beginner's Language − Python is a great language for the
beginner-level programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.4
History of Python
Python was conceptualized in the late 1980s by Guido Van Rossum. He worked
as an implementer on a computer language called ABC at the National Research
Institute for Mathematics and Computer Science. ABC has greatly influenced the
design of Python.
He published the first version of Python code (version 0.9.0) at alt.sources in
February 1991. This release already included exception handling, functions, and core
data types of list, dict, str, and others. It was also object-oriented and had a module
system.
Python version 1.0 was released in January 1994. This release featured the
functional programming tools lambda, map, filter, and reduce, which he never liked.
In October 2000, Python 2.0 was introduced. It included list comprehensions, a
full garbage collector, and supporting Unicode.
Python flourished for another 8 years in the 2.x series before the next major
release as Python 3.0 (also known as Python 3000 or Py3K) was introduced. The
emphasis in Python 3.0 is the removal of duplicate programming constructs and
modules.
Python Features
1. It is a simple and minimalistic language.
Reading a good Python program feels almost like reading English. This
pseudocode nature of Python is one of its greatest strengths. It allows us to
concentrate on the solution to the problem rather than the syntax (i.e., the
language itself).
2. It is extremely easy to get started with.
It has an extraordinary simple syntax as already mentioned.
3. It is free and open source.
We can freely distribute copies of this software, read the software’s source code,
make changes to it, use it pieces in other programs, and know that we can do
these things.
4. It is a high-level language.
We do not have to bother about low-level details such as managing the memory
used by our program.
5. It is portable
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.5
6. It is an interpreted language.
There is no separate compilation and execution steps. We just run the program
from the source code. We do not have to worry about linking, loading with
libraries, etc.
7. It supports procedure-oriented programming.
It also supports object-oriented programming, especially when compared to
languages like C++ or Java.
8. It is extensible
If we need a critical piece of code to run very fast, we can achieve this by writing
that piece of code in C, and then combine that with our Python program.
9. It can be embedded within our C/C++ program.
It gives scripting capabilities for our program’s users.
10.It has an extensive standard library.
It helps us do various thins involving regular expressions, documentation
generation, unit testing, threading, databases, web browsers, etc. All these are
always available wherever Python is installed.
11.It is an exciting and powerful language.
It has the right combination of performance and features that makes writing
programs in Python both fun and easy.
Python Applications
∙ Graphical user interface (GUI)-based desktop applications
Python makes it a desirable choice for developing desktop-based
applications, which include image processing and graphic design
applications; scientific and computational applications; and
games.
∙ Web frameworks and web applications
Python has been used to create a variety of web frameworks that provide
standard libraries and modules for content management, interaction and
interfacing with different internet protocols, an open source ERP, a consolidated
suite of business applications, and Google App engine.
∙ Enterprise and business applications
With features that include special libraries, extensibility, scalability, and
easily readable syntax, Python is a suitable coding language for
customizing larger applications. Reddit was rewritten in Python in 2005.
Python also contributed a large part to the functionality of YouTube.
∙ Operating systems
Python is often an integral part of Linux distributions.
∙ Language development
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.6
Python’s design and module architecture has influenced development of
numerous languages similar to Python. Syntax of languages like Apple’s Swift,
CoffeeScript, Cobra, and OCaml all share similarity with Python.
∙ Prototyping
Besides being quick and easy to learn, Python is free an has the support
of a large community. This makes Python the preferred choice for
prototype development.
the Download Python 3.7.3 (We may see a different version name).
3. When the download is complete, double-click the file and follow the instructions
to install it.
When Python is installed, a program called IDLE (Integrated Development
and Learning Environment) is also installed along with it. It provides graphical
user interface to work with Python.
4. Open IDLE, and create a new File
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.7
Copy the following code below, and press Enter.
5. Type the Python code and save (Ctrl+S) with .py file
extension.
o We may create a New Folder for all our Python Files.
We save this folder wherein it could be retrieved easily.
o We may save it as hello.py or my-first-program.py
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.8
Python - Basic Syntax
The Python language has many similarities to Perl, C, and Java. However, there are
some definite differences between the languages.
If you are running new version of Python, then you would need to use print statement
with parenthesis as in print ("Hello, Python!");. However in Python version 2.4.3, this
produces the following result −
Hello, Python!
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.9
Let’s Remember
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.10
Here is a list of all the keywords:
Keywords in Python
assert finally or
def if return
elif in while
else is with
11
We may be overwhelmed
looking at the
keywords. Do not worry! We
will know how
to use them in Python as we progress in
the other lessons.
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.11
Python Identifiers
Identifiers are the names given to entities like classes, functions, variables, etc. in
Python. They help differentiate one entity from another.
1. It can be a combination of:
a. letters in lowercase (a-z),
c. digits (0-9), or
d. underscore(_).
The examples myClass, var_1 and print_this_to_screen are valid
identifiers.
2. It cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
3. It cannot use keywords.
4. It cannot use special symbols like !, @, #, $, %.
5. It can be of any length.
CamelCase firstName
First_Name
Date_of_Birth dateOfBirth
Do’s in Python
These are some guidelines that we must keep in mind when using Python. Not
only will these help us write codes efficiently, but also help us create programs with
ease.
1. Python is a case-sensitive language.
For example, Variable and variable are not the same. We should always
name the identifiers that make sense.
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.12
2. Multiple words can be separated using an underscore (e.g.,
this_is_a_long_variable) or camel case style or writing (e.g.,
ThisIsAShortVariable).
For example, using c = 5 as a value in counters is valid. It would be easier
though to understand if we use counter = 5, instead.
A = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.13
Indentation
Most of the programming languages use brace { } to define a block of code.
Python uses indentation.
A code of block starts with indentation and ends with the first unindented line.
The amount of indentation is up to us, but we make sure that it is consistent throughout
the block.
Four (4) spaces are used for indentation and is preferred over using
tabs. Example:
if r in range (1, 11):
print(r)
if r == 5:
Indentation in Python makes the code look neat and clean. Overall, this makes
Python programs look similar and consistent.
Comments
Comments make a program easier to understand. They describe what is going
on inside a program.
In Python, the hash (#) symbol is used to write a comment. The Python
interpreter ignores all the statement after the hash symbol.
Examples:
#This is a comment.
#Everything after the # symbol is not
executable. #I hope you enjoy Python
“““This is another
example of using
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.14
comments in multiline.”””
Please proceed to page 28 for Activity 7, 8 & 9.
print (text)
When we run this program, the output is oranges. The new value of text has
been replaced by the assignment operator.
Example of assigning multiple values to multiple variables.
#Multiple value to multiple variables
a, b, c, = 2, 3.6, “Hello”
print(a)
print(b)
print(c)
Output:
2
3.6
Hello
Output:
42
42
42
Constant
Constant is a variable whose values do not change. In Python, a constant is
usually assigned and declared on a module. The module means a new file containing
values or functions is imported to the main file. A constant is written in all capital letters
and underscores to separate the words.
Let us create a new file and name it: constant.py
Inside this file, we assign the following values:
PI = 3.14
GRAVITY = 9.8
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.16
We will now create another file and name it main.py. Inside main.py, we will
import the constant module we created.
Program:
#Accessing values from contant.py
import constant
print(constant.PI)
print(constant.GRAVITY)
Output:
3.14
9.8
Literal
Literal is raw data given in a variable constant. In Python, there are various types
of literals.
1. Numeric literals are unchangeable.
There are four (4) types: plain integers, long integers, floating point
numbers, and imaginary numbers. There are no complex literals since
complex numbers can be formed by adding a real number and an imaginary
number. We will focus on integer and float only.
Program
#Integer and Float
a = 0b1010 #Binary Literal
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal
#Float Literal
float_1 = 10.5
float_2 = 1.5e2
Output:
10 100 200 300
10.5 15.0
17
Program:
#String Literals
string = “This is a string.”
char = “C”
print(string)
print(char)
Output:
This is a string.
C
Data Types
Every value in Python has a data type. Since everything is an object in Python, data
types are actually classes, and variables are instances (object) of these classes.
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.18
Numbers in Python can either be plain integers, long integers, floating point
numbers, or complex numbers. They are defined as int, float, and complex
class.
We can use the type() function to know which class a variable r a value belongs to
and the instance(), function to check if an object belongs to a particular class. Let us
take a look at this example:
Integers can be of any length; it is only limited by the memory available. A floating point
number is accurate up to fifteen (15) decimal places. Integer and floating points are
separated by decimal points. The number 1 is an integer, while 1.0 is a floating point
number.
Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The equal
sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to
the right of the = operator is the value stored in the variable. For example −
Live
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.19
Demo
print (counter)
print (miles)
print (name)
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name
variables, respectively. This produces the following result −
100
1000.0
John
Python Strings
A string is a sequence of characters. Python allows for either pairs of single or double
quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with
indexes starting at 0 in the beginning of the string and working their way from -1 at the
end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator. For example −
Live
Demo
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.20
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists
Lists are the most versatile of Python's compound data types. A list contains items
separated by commas and enclosed within square brackets ([]). To some extent, lists
are similar to arrays in C. One difference between them is that all the items belonging
to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The
plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition
operator. For example −
Live
Demo
print (list[0])
tinylist = [123, 'john']
20
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.21
Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed
within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed, while tuples are enclosed in parentheses
( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example
–
Live
Demo
21
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.22
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
Set
A set is an unordered collection of unique items. It is defined by values separated
by comma inside braces {}. The items in a set are not ordered. Let us take a look at this
example:
Program:
a = {5, 2, 3, 1, 4}
print (“a = “, a)
print (type(a))
Output:
a = {1, 2, 3, 4, 5}
<class ‘set’>
We can perform set operations like union intersection on two (2) sets. Sets have unique
values. Let us take a look at this example:
Program:
a = {1, 2, 2, 3, 3, 3}
print (a)
Output:
{1, 2, 3}
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.23
22
Conversion of a float() to int() will truncate the value.
>>> int(10.6)
10
>>>int(-10.6)
-10
Please proceed to page 30-31 for Activities 13, 14, & 15.
What’s More
Activity 1
Introduce Yourself
Create a flowchart and a Python program that introduces yourself to the world.
Indicate you name, dream job, and province or city.
Flowchart
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.24
Program
Activity 2
Display Counting Numbers
Create a flowchart and a Python program that displays the first ten (10) counting
numbers.
Flowchart:
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.25
Program
Activity 3
Understand Keywords and Identifiers
1. Open your Python IDLE and type help().
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.26
You will see options on the type of help you need.
2. Type keywords
Activity 4
Eliminate Invalid identifiers
Given the set of words below, cross out the identifiers that are not valid.
Alph um 2form
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.27
x-value #total firstName
y8 #result globalvariable
if while value_@_ten
username Password go
Activity 5
Rename the Variables
Rename the following variables by using an underscore or CamelCase.
Variable Underscore CamelCase
Total Sale
Area of a Square
Sum of 7 Entries
Average Scores
Total Orders
Activity 6
Write Comments
On the line, write your full name preceded by the hash symbol.
________________________________________________________________
You just created a non-executable line in your program. This is how comments are
written in Python programming.
27
Activity 7
Write the Statements
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.28
Write the equation in its equivalent Python format. Limit each line to at most three
(3) numbers for each explicit line continuation.
Equation:
Final_grade = (50% x 97 / 100) + (25% x 89 / 100) + (25% x 20 /
Activity 8
Add comments
Follow the steps below. Write your output in the box below.
1. On the first line, put your name in a comment.
2. On the second line, put the title of the project in a comment. (Use Sum of Two
Squares as the title of this activity.)
3. On the third line, put the date today in a comment.
Activity 9
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.29
Supply the information requested. Write your answers on the lines.
Let’s Remember
Compliance with the rules on statement, indentation, and comments makes
programming easier for the programmer and the reader. Programming standards make
things easier. There might come a time when other programmers may want to develop
or enhance our code or vice versa. In both cases, compliance with standards can be
very helpful for everyone.
What I Can Do
Activity 10
Identify the Output
Identify the output of the code below. Write your answer in the box.
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.30
Activity 11
Identify the output of the code below. Write your answer in the box.
Activity 12
Recognize the Index List
Given the list below, identify the value X[3]. Write your answer on the line.
Let’s Remember
Activity 13
Enumerate the Data Types
Give what are asked in each number. Write your answers on the
lines. 1. Five (5) examples of int data type
___________________________
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.31
___________________________
___________________________
___________________________
2. Five (5) examples of float data type
___________________________
___________________________
___________________________
___________________________
Activity 14
Supply the New Value
Write the result for each program line.
1. int (5.7)
2. float (9)
3. str (53)
4. #Given Code
x = ‘Happy Birthday!’
print(“x[8] = “, x[8])
5. #Given Code
W = {9, 9, 3, 3, 5, 5}
print(W)
Activity 15
Format the Output
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.32
Research on what the following blocks do.
1. Type the code in IDLE.
x = 5; y = 10
2. R
print('The value of x is {} and y is
{}.'.format(x,y)) u
n the code. Your output should be similar to the output below.
Assessment
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.33
I. Write True or False
Write True if the statement is correct, and write False if otherwise.
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.34
#This is a statement.
______2. The statement below is valid.
#Start of the Program -----------------------
______3. The second line is a valid statement.
If a == 0;
A = 1: B = 2: C = 3
______4. Incorrect indentation will result in an IndentationError message.
______5. The code below is a valid statement.
color_scheme = {‘red’,
‘blue’,
‘green’}
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.35
Answer
KeyAssessment I What I have Learned What I Know
3. String Pseudocode 5. 10.Integer
1. True 2. True 3. 4. Set Variables 6. 11.E
False 4. False 5. 5. Truncate/shorten Constant 12.B
True 1. Program 7. String 13.A
2. Programming 3. 8. Tuple 14.D
1. 15 decimal
Algorithm 4. 9. Set 15.D
2. Tuple
References
Computers for Digital Learners; Programming; ICT Tools Today High School
Series; Phoenix Publishing House
https://www.tutorialspoint.com
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.36
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.37