0% found this document useful (0 votes)
55 views37 pages

Programming in Python PDF

The document provides an overview of Python programming. It discusses that Python is an interpreted, interactive, and object-oriented scripting language designed to be highly readable. It then covers Python's history, starting with its creation in the late 1980s. Key features of Python are highlighted, including that it is simple, minimalistic, easy to get started with, free and open source, portable, and supports both procedure-oriented and object-oriented programming.

Uploaded by

Ryusui Nanami
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
55 views37 pages

Programming in Python PDF

The document provides an overview of Python programming. It discusses that Python is an interpreted, interactive, and object-oriented scripting language designed to be highly readable. It then covers Python's history, starting with its creation in the late 1980s. Key features of Python are highlighted, including that it is simple, minimalistic, easy to get started with, free and open source, portable, and supports both procedure-oriented and object-oriented programming.

Uploaded by

Ryusui Nanami
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 37

What I Need to Know

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.

Upon completion of this module, the students should be able to:


LO1. Explain the process of Computer Programming
LO2. Perform Basic Programming Operations using Python Programming
Language LO3. Create Functional Computer Programs through the use of Python

To get the most from this Module, you need to do the following:

1. Begin by reading and understanding the Learning Outcome/s and Performance


Standards. These tell you what you should know and be able to do at the end
of this Module.
2. Find out what you already know by taking the Pre-test then check your answer
against the Answer Key. If you get 99 to 100% of the items correctly, you may
proceed to the next Lesson. This means that you do not need to go through
the Lesson because you already know what it is about. If you failed to get 99
to 100% correctly, go through the Lesson again and review especially those
items which you failed to get.
3. Do the required Learning Activities. They begin with one or more Information
Sheets. An Information Sheet contains important notes or basic information that
you need to know. After reading the Information Sheet, test yourself on how
much you learned by answering the Self-check. Refer to the Answer Key for
correction. Do not hesitate to go back to the Information Sheet when you do not
get all test items correctly. This will ensure your mastery of basic information.
4. Demonstrate what you have learned by doing what the Activity / Operation /Job
Sheet directs you to do.
5. You must be able to apply what you have learned in another activity or in real
life situation.
6. Accomplish the Scoring Rubrics for you to know how well you performed.

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.

_____1. A set of instructions that tells the computer what to do.


_____2. The process of creating a program.
_____3. It refers to the logical sequence of steps or procedures to solve a problem.
_____4. It is a detailed description of an algorithm, displayed in an easily
understandable language.
_____5. They are used to store information to be referenced and manipulated in a
computer program
_____6. In computer programming, a _______ is a value that cannot be altered by the
program during normal execution.
_____7. In computer programming, a _________ is traditionally a sequence of
characters, either as a literal constant or as some kind of variable.
_____8. It is an ordered sequence of items.
_____9. It is an unordered collection of unique items defined by values separated by
comma inside braces.
_____10. It is a whole number (not a fraction) that can be positive, negative, or zero.

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:

1. Problem Definition and Analysis


2. Algorithm Development
After determining the problem and its requirements, we then develop the
programs’ algorithm. An algorithm refers to the logical sequence of steps and
procedures to solve the problem. We break down the solution step by step. This
is one of the most important phases in program development.
The program’s algorithm is commonly represented in two (2) ways: using either a
flowchart or a pseudocode.
a. Flowchart is a diagram that represents the algorithm. It contains various
shapes connected by arrows.
b. Pseudocode is a detailed description of an algorithm, displayed in an easily
understandable language, usually in English, and not in a complicated
programming language.
3. Coding
4. Testing and Debugging
5. Maintenance

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 Quick Guide

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.

Download & Installation for Windows


1. Go to Download Python page on the official site:www.python.org 2. Click

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

To create a file in IDLE, go to File > New file (Shortcut: Ctrl+N).

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

o Save it in a folder where we keep all our Python files.

6. Go to Run > Run module (Shortcut: F5) to see the output.

Download & Installation for Cellphones

Installation for Androids

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.

First Python Program


Type the following text at the Python prompt and press the Enter −
>>> print "Hello, Python!"

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!

Please proceed to page 24-26 for the Activity 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.9
Let’s Remember

Learning a new programming language is trying something new. To


produce our desired output, there are times when we feel confident and
skip a few steps. We must be daring and conscientious when going
through the steps when trying something new, especially in
programming.

DISTINGUISHING KEYWORDS FROM IDENTIFIERS


Python Keywords
Keywords are the reserved words in Python. We cannot use a keyword as a variable,
name, function name, or any other identifier. They are used to define the syntax and structure
in Python.
o Keywords are case-sensitive. That is why we must be careful when writing or typing
them.
o There are 33 keywords in Python (specifically in versions 3.3 and above), and this
number may change slightly in time. (This happens when there are updates in the
program.)
o All the keywords except True, False, and None are in lowercase, and they must be
written as they are.

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

and exec not

assert finally or

break for pass

class from print

continue global raise

def if return

del import try

elif in while

else is with

except lambda Yield

True False None

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),

b. letters in uppercase (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

Using Camel Create an Identifier for placeOfBirth

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.

Please proceed to page 27 for Activity 4, 5 & 6.

USING STATEMENTS, INDENTATIONS, AND COMMENTS


Statements
The commands that Python can execute are called statements. The line A = 1 is an
assignment statement. The end of a statement is marked by a newline character. The
newline character is set by pressing the Enter key.
We can also extend statements over multiple lines with the line continuation
character or using the backslash(\).
Example:
A = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9

Line continuation is implied inside parenthesis ( ), brackets [ ], and braces {


}. Example:

A = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)

In using ( ), [ ], and { }, line continuation is implied.


Example:
Color_scheme – [‘red’, ‘blue’, ‘green’]

Multiple statements can also be put in a single line using a semicolon


(;). Example:
A = 1; B = 2; C = 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.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.

Incorrect indentation will result in a SyntaxError message.

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

Another way of putting comments is by enclosing the comments in three (3)


single quotes (“ “), or there (3) double quotes (“”” “””).
Example:
‘‘‘This is also an
Example of using
Comments in multiline.’’’

“““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.

Let’s Browse Back


Using Statements, Indentations, and Comments
The commands in Python are called statements. The end of a statement is
marked by a newline character.
To extend statements over multiple lines, we use the backslash (\).
Line continuation is implied inside the parentheses ( ), brackets [ ], and braces {
}.
Multiple statements can be put in a single line using a semicolon
(;). Python uses indentation to define a block of code.
The amount of indentation, by default, is four (4) spaces.
Comments describe what is going on inside a program.
To write a comment, we use the hash (#) symbol or enclose it with three (3)
single quotes (‘‘‘ ’’’), or three (3) double quotes (“““ ”””).

DECLARING VARIABLES, CONSTANTS, AND LITERALS


Variable
Variable is a named location used to store data in the memory. Each variable
must have a unique name called identifier. Variables are like containers that hold data
that can be changed later throughout programming.
In Python, variable declaration or variable initialization happens automatically
when we assign a value to a variable. We use the equal (=) sign to assign the value to
a variable.
Example 1:
#Example 1
website = “python.org”
print (website)
When executed, it will display python.org as the output. There is no initialization
that the variable website will contain a string. Python automatically knows that values in
quotation marks are treated as string.
Example 2:
#Example 2
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.15
Text = “apples”
#assign a new value to website
Text = “oranges”

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

Examples of assigning the same value to multiple variables at


once: #Assigning a value to multiple vairables at
once
Section_A = Section_B = Section_C = 42
print(Section_A)
print(Section_B)
print(Section_C)

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

#Show the values.


print(a, b, c, d)
print(float_1, float_2)

Output:
10 100 200 300
10.5 15.0

In the program above, we assigned different literals to different variables: a is a binary


literal, b is a decimal literal, c is an octal literal, and d is a hexadecimal literal. When
It has been changed to make it work on many platforms. We can use Python on Linux,
Windows, Macintosh, Solaris, PlayStation, and many more.17
we print the variables, all the literals are converted to their decimal equivalent.
The same applies to the float literals. The figures 10.5 and 15e2 are floating
point literals. The figures 1.5e2 is exponential form and is equivalent to 150.0 when
converted.
2. String literals are sequences of characters surrounded by quotes. We use
single, double, or triple quotes for a string. A character literal is a single
character surrounded by single or double quotes.

17
Program:
#String Literals
string = “This is a string.”
char = “C”
print(string)
print(char)

Output:
This is a string.
C

This is a string. is a string literal and C is a character literal.

Please proceed to page 29-30 for Activity 10, 11 & 12.

IDENTIFYING AND CONVERTING DATA TYPES

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:

Program: 2.0 is of type <class ‘float’>


a=5
print(a, “is of type”, type(a)) Did you
FLOAT defines a variable with a fractional
a = 2.0 know?
print (a, “is of type”, type(a)) value. Numbers created using a float variable
declaration will have digits on both sides of a
decimal point.
Output:
5 is of type <class ‘int’>

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.

Assigning Values to Variables


[Tutorialpoint.com]
In Python, variable declaration or variable initialization happens automatically when we
assign a value to a variable. We use the equal (=) sign to assign the value to a
variable.

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

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

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

str = 'Hello World!'

print (str ) # Prints complete string


print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:] ) # Prints string starting from 3rd character
print (str * 2 ) # Prints string two times
print (str + "TEST") # Prints concatenated string

This will produce the following result −

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']

print (list) # Prints complete list


print (list[0]) # Prints first element of the list

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

This produce the following result −


['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

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

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')

print (tuple ) # Prints the complete tuple

print (tuple[0] ) # Prints first element of the tuple

print (tuple[1:3]) # Prints elements of the tuple starting from 2(nd


till 3rd)
print (tuple[2:] # Prints elements of the tuple starting from 3rd
element
print (tinytuple * 2 # Prints the contents of the tuple twice

print (tuple + tinytuple # Prints concatenated tuples

This produce the following result −


('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
The following code is invalid with tuple, because we attempted to update a tuple, which
is not allowed. Similar case is possible with lists −

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}

Conversion of Data Types


We can convert between different data types by using different type conversion
functions like int(), float(), str(), etc.
Let us take a look at the code float(5). The number 5 is an integer. The float
function will convert the integer 5 to 5.0 (its equivalent value in float). >>> float (5)
5.0

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

Conversion to and from string must contain compatible values.

>>> float (‘2.5’)


2.5
>>> str(25)
‘25’

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 /

20) Python statement:

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

Declare Variables, Constants, and Literals

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.

Last_Name = ___________________________________ #Enter last name


First_Name = ___________________________________ #Enter first
name

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.

#What is the output?


mynie = “moe”
eenie = “mynie”
meenie = “eenie”
moe = “meenie”
print(eenie)
print(meenie)
print(mynie)
print(moe)

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.

#What is the output?


a = 7
b = 1
a = 9
c = 4
print(a)
print(b)
print(c)

Activity 12
Recognize the Index List
Given the list below, identify the value X[3]. Write your answer on the line.

X = [5, 10, 15, 20 25, 30]


Index in Python starts from zero (0).________________________________

Let’s Remember

Different types of variables store different types of values. When


we assign a wrong value to a certain type of identifier, we encounter
errors. To avoid mistakes, we must be careful when assigning values.
We must also know the type of value in an identifier.

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.

Program Line Result

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.

The value of x is 5 and y is 10.

What I Have Learned


Identify the Part
Identify the part being referred to in each sentence. Write your answers on the
lines.

1. A floating point number is accurate up to __________________ places.


2. _______________________ is an ordered sequence of items. 3.
_______________________ is a sequence of characters.
4. _______________________ is an unordered collection of unique items defined
by values separated by comma inside braces.
5. Conversion of a float to int will __________________ the value.

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.

_____________1. Python version 1.0 was released in January 1994.

_____________2. Python 3.0 removed the duplicate programming constructs and


modules.
_____________3. Python can be embedded within the C/C++ programs.
_____________4. Python is an interpreter language. There is no separate
compilation and execution steps.
_____________5. The file extension of Python program is .py.

II. Write the Rules


Write the rules of naming identifiers on the lines.
1. ________________________________________________________________
______________________________________________________ a.
____________________________________________________ b.
____________________________________________________ c.
____________________________________________________ d.
____________________________________________________
2. ________________________________________________________________
______________________________________________________ 3.
________________________________________________________________
______________________________________________________ 4.
________________________________________________________________
______________________________________________________ 5.
________________________________________________________________
______________________________________________________

III. Let’s Test Ourselves


Write True on the line if the statement is correct, and False if otherwise.
______1. The sample shown is not a valid statement.

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’}

IV. Import Constants


Enumerate the steps in importing the value of constants and displaying the values.
Use the following data for constants:
RIGHT_ANGLE = 90
BOILING_PT_WATER = 100

Write your codes below.


constant.py main.py

#Assign Constants #Display RIGHT_ANGLE


#Display BOILING_PT_WATER

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

You might also like