0% found this document useful (0 votes)
82 views33 pages

Computer10.q3module - Reso

The document provides an introduction to Python programming for beginners. It discusses installing Python and the PyCharm IDE on Windows. It then explains how to create a "Hello World" Python program in PyCharm by writing a simple print statement. Key concepts covered include Python syntax, data types, functions like print(), and how to run and test programs.

Uploaded by

Glenn Xavier
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views33 pages

Computer10.q3module - Reso

The document provides an introduction to Python programming for beginners. It discusses installing Python and the PyCharm IDE on Windows. It then explains how to create a "Hello World" Python program in PyCharm by writing a simple print statement. Key concepts covered include Python syntax, data types, functions like print(), and how to run and test programs.

Uploaded by

Glenn Xavier
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

THIRD QUARTER MODULE

BRIEF INTRODUCTION:

Hello dear students! Welcome to the second quarter of the school year. I hope your enthusiasm and excitement got more ignited
and challenged to our new mode of learning amidst this COVID-19 outbreak. In our computer class, we will focus on basic flowchart
designing. In this subject, your prior knowledge in your previous computer classes will still be used for you to be able to cope with
given tasks/ activities. I hope you will enjoy our lessons! Thus, in this second quarter learning module, you are expected to acquire the
essential knowledge and develop the basic skills prescribed by DepEd’s learning standards aligned with the MELCs as shown in the
table below. God bless and let’s get into it!

MODULEWEEK 1. Getting Started with Python

Content Standard The learners demonstrate an understanding of key concepts, underlying


principles and core competencies in Computer Programming.
Performance Standard The learners shall be able to independently create/provide quality product or
service in computer programming.
Most Essential Learning Competencies Define Python, Install Python, Start Python, Create a Python Program, Follow
(MELCs) the steps and procedures in programming

21st Century Learning Skills Creativity, Critical Thinking, Collaboration, Career Learning, Cross-cultural
Understanding, Computer Technology, Communication
Core Values Academically Excellent, Social Responsibility, Community Building, Christian
Witnessing

TOPIC: Introduction to Python


__________________________________________________________________________

INTRODUCTION:

In this Python tutorial for beginners, you will learn Python programming basics and advanced concepts. This Python course
contains all the Python basics from installation to advanced stuff like Python data science. This Python programming tutorial helps
you to learn Python free with Python notes and Python tutorial PDF. These Python tutorials will help you learn the basics of
Python.

CONTENT DISCUSSION:

Python is an interpreted, object-oriented, high-level programming language. It has high-level built-in data structures with
dynamic typing and binding.
Python’s syntax is easy to learn. The Python interpreter and standard library are available without charge for all major
platforms can be freely distributed.
Programmers use python because it increases productivity. Since there is no compilation step, the edit-test-debug cycle is
fast and effective. The quickest way to debug a program is to add a few print statements to the source.

How to Install Python on Windows [Pycharm IDE]

PyCharm is a cross-platform editor developed by JetBrains. Pycharm provides all the tools you need for productive Python
development.
Below are the detailed steps for installing Python and PyCharm

How to Install Python IDE


Below is a step by step process on how to download and install Python on Windows:

Step 1) To download and install Python, visit the official website of Python https://www.python.org/downloads/ and choose your
version. We have chosen Python version 3.6.3

1
Step 2) Once the download is completed, run the .exe file to install Python. Now click on Install Now.

Step 3) You can see Python installing at this point.

Step 4) When it finishes, you can see a screen that says the Setup was successful. Now click on “Close”.

2
How to Install Pycharm
Here is a step by step process on how to download and install Pycharm IDE on Windows:

Step 1) To download PyCharm visit the website https://www.jetbrains.com/pycharm/download/ and Click the “DOWNLOAD” link
under the Community Section.

Step 2) Once the download is complete, run the exe for install PyCharm. The setup wizard should have started. Click “Next”.

Step 3) On the next screen, Change the installation path if required. Click “Next”.

3
Step 4) On the next screen, you can create a desktop shortcut if you want and click on “Next”.

Step 5) Choose the start menu folder. Keep selected JetBrains and click on “Install”.

Step 6) Wait for the installation to finish.

4
Step 7) Once installation finished, you should receive a message screen that PyCharm is installed. If you want to go ahead and run it,
click the “Run PyCharm Community Edition” box first and click “Finish”.

Step 8) After you click on “Finish,” the Following screen will appear.

Creating First Program


Step 1) Open PyCharm Editor. You can see the introductory screen for PyCharm. To create a new project, click on “Create New
Project”.

5
Step 2) You will need to select a location.

1. You can select the location where you want the project to be created. If you don’t want to change location than keep it as it is
but at least change the name from “untitled” to something more meaningful, like “FirstProject”.
2. PyCharm should have found the Python interpreter you installed earlier.
3. Next Click the “Create” Button.

Step 3) Now Go up to the “File” menu and select “New”. Next, select “Python File”.

6
Step 4) A new pop up will appear. Now type the name of the file you want (Here we give “HelloWorld”) and hit “OK”.

Step 5) Now type a simple program – print (‘Hello World!’).

Step 6) Now Go up to the “Run” menu and select “Run” to run your program.

Step 7) You can see the output of your program at the bottom of the screen.

Step 8) Don’t worry if you don’t have Pycharm Editor installed, you can still run the code from the command prompt. Enter the
correct path of a file in command prompt to run the program.

The output of the code would be

7
Python print() function
The print() function in Python is used to print a specified message on the screen. The print command in Python prints strings or
objects which are converted to a string while printing on a screen.

Syntax:

print(object(s))

How to Print a simple String in Python?


More often then not you require to Print strings in your coding construct.

Here is how to print statement in Python 3:

Example: 1
To print the Welcome to Guru99, use the Python print statement as follows:

print ("Welcome to Guru99")

Output:
Welcome to Guru99

In Python 2, same example will look like

print "Welcome to Guru99"


Example 2:
If you want to print the name of five countries, you can write:

print("USA")
print("Canada")
print("Germany")
print("France")
print("Japan")

Output:
USA
Canada
Germany
France
Japan

How to print blank lines


Sometimes you need to print one blank line in your Python program. Following is an example to perform this task using Python print
format.

Example:
Let us print 8 blank lines. You can type:

print (8 * "\n")
8
or:

print ("\n\n\n\n\n\n\n\n\n")

Here is the code


print ("Welcome to Guru99")
print (8 * "\n")
print ("Welcome to Guru99")

Output

Welcome to Guru99

Welcome to Guru99

Print end command


By default, print function in Python ends with a newline. This function comes with a parameter called ‘end.’ The default value of this
parameter is ‘\n,’ i.e., the new line character. You can end a print statement with any character or string using this parameter. This is
available in only in Python 3+

Example 1:

print ("Welcome to", end = ' ')


print ("Guru99", end = '!')
Output:

Welcome to Guru99!

Example 2:

# ends the output with ‘@.’

print("Python" , end = '@')

REVISED KNOWLEDGE: Actual answer to the process questions/ focus questions


1. What is Python?
Python is an object-oriented programming language created by Guido Rossum in 1989. It is ideally designed for rapid
prototyping of complex applications. It has interfaces to many OS system calls and libraries and is extensible to C or C+
+. Many large companies use the Python programming language, including NASA, Google, YouTube, BitTorrent, etc.

2. What are the steps in installing Python?


Step 1) To download and install Python, visit the official website of Python https://www.python.org/downloads/ and
choose your version. We have chosen Python version 3.6.3
Step 2) Once the download is completed, run the .exe file to install Python. Now click on Install Now.
Step 3) You can see Python installing at this point.
Step 4) When it finishes, you can see a screen that says the Setup was successful. Now click on “Close”.

3. How do we create our first Python program?


Step 1) Open PyCharm Editor. You can see the introductory screen for PyCharm. To create a new project, click on
“Create New Project”.
Step 2) You will need to select a location.
 You can select the location where you want the project to be created. If you don’t want to change location than
keep it as it is but at least change the name from “untitled” to something more meaningful, like “FirstProject”.
 PyCharm should have found the Python interpreter you installed earlier.
 Next Click the “Create” Button.
Step 3) Now Go up to the “File” menu and select “New”. Next, select “Python File”.
Step 4) A new pop up will appear. Now type the name of the file you want (Here we give “HelloWorld”) and hit “OK”.
Step 5) Now type a simple program – print (‘Hello World!’).
Step 6) Now Go up to the “Run” menu and select “Run” to run your program.
Step 7) You can see the output of your program at the bottom of the screen.

9
Step 8) Don’t worry if you don’t have Pycharm Editor installed, you can still run the code from the command prompt.
Enter the correct path of a file in command prompt to run the program.

4. How do we follow the steps in programming conscientiously?


Learn. Unlearn. Relearn. Learning a new programming language is tying 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.

FINAL KNOWLEDGE: Generalization/ Synthesis/ Summary


Python is an object-oriented programming language created by Guido Rossum in 1989. It is ideally designed for rapid prototyping of
complex applications. It has interfaces to many OS system calls and libraries and is extensible to C or C++. Many large companies use
the Python programming language, including NASA, Google, YouTube, BitTorrent, etc.

MODULEWEEKS2-3. Distinguishing Keywords from Identifiers

Most Essential Learning Know how to use keywords and identifies in Python programming, Use indents
Competencies (MELCs) and comments to describe the different parts of the program, Learn the standard
formatting in Python

TOPIC: Python Keywords and Identifiers


_______________________________________________________________________________

CONTENT DISCUSSION:

Python Keywords

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

The list of all the keywords is given below.

Python Keywords List

False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield

Python Identifiers
Identifiers are the name given to variables, classes, methods, etc. For example,

language = 'Python'

10
Here, language is a variable (an identifier) which holds the value 'Python'.
We cannot use keywords as variable names as they are reserved names that are built-in to Python. For example,

continue = 'Python'

The above code is wrong because we have used continue as a variable name. To learn more about variables, visit Python Variables.

Rules for Naming an Identifier


 Identifiers cannot be a keyword.
 Identifiers are case-sensitive.
 It can have a sequence of letters and digits. However, it must begin with a letter or _. The first letter of an identifier cannot be a
digit.
 It's a convention to start an identifier with a letter rather _.
 Whitespaces are not allowed.
 We cannot use special symbols like !, @, #, $, and so on

Some Valid and Invalid Identifiers in Python

Valid Identifiers Invalid Identifiers

score @core

return_value return

highest_score highest score

name1 1name

convert_to_string convert to_string

REVISED KNOWLEDGE: Actual answer to the process questions/ focus questions

1. What is a Python keyword?


Keywords are the reserved words in Python. They are in lowercase except for True, False, and None.

2. What are the keywords used in Python?

False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield

3. What is a Python identifier?


Identifiers are the names given to entities like classes, functions, variables, etc. in Python. They help differentiate one entity
from another.

4. What are the rules for using identifiers in Python?


 Identifiers cannot be a keyword.
 Identifiers are case-sensitive.
 It can have a sequence of letters and digits. However, it must begin with a letter or _. The first letter of an identifier
cannot be a digit.
 It's a convention to start an identifier with a letter rather _.
11
 Whitespaces are not allowed.
 We cannot use special symbols like !, @, #, $, and so on

FINAL KNOWLEDGE: Generalization/ Synthesis/ Summary

Keywords are the reserved words in Python. They are in lowercase except for True, False, and None.
Identifiers are the names given to entities like classes, functions, variables, etc. in Python. They help differentiate one entity from
another.
An underscore (_) or camel case (camelCase) are used to separate multiple words.
A variable should have name that is close to the value it holds.

Python is a case-sensitive language. This means, Variable and variable are not the same.


Always give the identifiers a name that makes sense. While c = 10 is a valid name, writing count = 10 would make more sense, and it
would be easier to figure out what it represents when you look at your code after a long gap.
Multiple words can be separated using an underscore, like this_is_a_long_variable.

TOPIC: Using Statements, Indentations, and Comments


2 _______________________________________________________________________________

CONTENT DISCUSSION:

Statements
A statement is an instruction that a Python interpreter can execute. So, in simple words, we can say anything written in Python is
a statement.Python statement ends with the token NEWLINE character. It means each line in a Python script is a statement.
For example, a = 10 is an assignment statement. where a is a variable name and 10 is its value. There are other kinds of statements
such as if statement, for statement, while statement, etc., we will learn them in the following lessons.
There are mainly four types of statements in Python, print statements, Assignment statements,  Conditional statements, Looping
statements.
The print and assignment statements are commonly used. The result of a print statement is a value. Assignment statements don’t
produce a result it just assigns a value to the operand on its left side.A Python script usually contains a sequence of statements. If there
is more than one statement, the result appears only one time when all statements execute.

Example

# statement 1
print('Hello')

# statement 2
x =20

# statement 3
print(x)

Output

Hello

20

As you can see, we have used three statements in our program. Also, we have added the comments in our code. In Python, we use the
hash (#) symbol to start writing a comment. In Python, comments describe what code is doing so other people can understand it.

We can add multiple statements on a single line separated by semicolons, as follows:

# two statements in a single


l =10; b =5

# statement 3
print('Area of rectangle:', l * b)

# Output Area of rectangle: 50

Multi-Line Statements

Python statement ends with the token NEWLINE character. But we can extend the statement over multiple lines using line
continuation character (\). This is known as an explicit continuation.
12
Example

addition =10+20+ \
30+40+ \
50+60+70
print(addition)
# Output: 280

Implicit continuation:

We can use parentheses () to write a multi-line statement. We can add a line continuation statement inside it. Whatever we add inside
a parentheses () will treat as a single statement even it is placed on multiple lines.

Example:

addition =(10+20+
30+40+
50+60+70)
print(addition)
# Output: 280

As you see, we have removed the the line continuation character (\) if we are using the parentheses ().

We can use square brackets [] to create a list. Then, if required, we can place each list item on a single line for better readability.
Same as square brackets, we can use the curly { } to create a dictionary with every key-value pair on a new line for better readability.

Example:

# list of strings
names =['Emma',
'Kelly',
'Jessa']
print(names)

# dictionary name as a key and mark as a value


# string:int
students ={'Emma':70,
'Kelly':65,
'Jessa':75}
print(students)

Output:

['Emma', 'Kelly', 'Jessa']

{'Emma': 70, 'Kelly': 65, 'Jessa': 75}

Indentation
Indentation refers to the spaces at the beginning of a code line.Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.Python uses indentation to indicate a block of code.

A code of block starts with indentation and ends with first unindented line.The amount if indentation is up to us, but we make sure that
it is consistent throughout that block.

Four (4) spaces are used for indentation and is preferred over using tabs.

13
In the above block of code, the indentation is used after the “if” and “else” statement so that the Python interpreter can  execute the
print statement and gives the proper output; else if it is not properly indented, then it would throw us an error which is seen in below
output. The print statement (“ n is greater than 5” ) and the print statement ( “ n is not greater than 5” )are two different clocks of code.
To indicate these blocks of code, Python uses indentation at the beginning of each line of the block with the same number of spaces
that are 4 spaces.

Comments

In computer programming, comments are hints that we use to make our code more understandable.
Comments are completely ignored by the interpreter. They are meant for fellow programmers. For example,

# declare and initialize two variables


num1 = 6
num2 = 9

# print the output


print('This is output')

Here, we have used the following comments,


 declare and initialize two variables
 print the output

Types of Comments in Python


In Python, there are two types of comments:
 single-line comment
 multi-line commeny

14
Single-line Comment in Python
A single-line comment starts and ends in the same line. We use the # symbol to write a single-line comment. For example,
# create a variable
name = 'Eric Cartman'

# print the value


print(name)
Run Code
Output

Eric Cartman

Here, we have created two single-line comments:


1. # create a variable
2. # print the value

We can also use the single-line comment along with the code.

name = 'Eric Cartman'# name is a string

Here, code before # are executed and code after # are ignored by the interpreter.

Multi-line Comment in Python


Python doesn't offer a separate way to write multiline comments. However, there are other ways to get around this issue.
We can use # at the beginning of each line of comment on multiple lines. For example,

# This is a long comment


# and it extends
# to multiple lines

Here, each line is treated as a single comment, and all of them are ignored.

Another way of doing this is to use triple quotes, either ''' or """.

These triple quotes are generally used for multi-line strings. But if we do not assign it to any variable or function, we can use it as a
comment.

The interpreter ignores the string that is not assigned to any variable or function.

Let's see an example,

''' This is also a


perfect example of
multi-line comments '''

Here, the multiline string isn't assigned to any variable, so it is ignored by the interpreter. Even though it is not technically a
multiline comment, it can be used as one.

Use of Python Comment


1. Make Code Easier to Understand
If we write comments in our code, it will be easier for future reference.
Also, it will be easier for other developers to understand the code.
2. Using Comments for Debugging
If we get an error while running the program, we can comment the line of code that causes the error instead of removing it. For
example,

print('Python')

# print("Error Line )

15
print('Django')

Here, print("Error Line) was causing an error so we have changed it as a comment. Now, the program runs without any errors.

This is how comments can be a valuable debugging tool.

REVISED KNOWLEDGE: Actual answer to the process questions/ focus questions

1. What is a Python statement?


A statement is an instruction that a Python interpreter can execute. So, in simple words, we can say anything written in
Python is a statement.Python statement ends with the token NEWLINE character. It means each line in a Python script is a
statement.
2. What are indentations?
Indentation refers to the spaces at the beginning of a code line.Where in other programming languages the indentation in code is
for readability only, the indentation in Python is very important.Python uses indentation to indicate a block of code.

3. What are comments?


In computer programming, comments are hints that we use to make our code more understandable.

FINAL KNOWLEDGE: Generalization/ Synthesis/ Summary

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 semi-colon (;).
Python uses indentation to define a block of code.
The amount of indentation, by default, is hour (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) singlequotes(‘‘‘ ’’’), or three (3) double quotes (“““ ”””).

16
MODULE WEEKS 4-5. Declaring Variables, Constants, and Literals

Most Essential Learning Know how to use variables, constants, and literals are data that they will used in
Competencies (MELCs) programming, Work with data types and different type conversion, Realize that
knowing the type of fata that they will be using can be a very useful tool in
programming

REFERENCES:(Please be guided with the given references to help you perform the given activities. Click the given links and
hyperlinks to access the suggested learning resources.)

 Printed: Cobre, E. J., Olalia, N., &Tingzon, K. (2019). ICT Tools Today High School Series Computers for Digital Learners
Grade 10 (1st ed., Vol. 1) [Book]. The Phoenix Publishing house Inc.

 Online: Learn Python Programming. (n.d.). https://www.programiz.com/python-programming

TOPIC: Python Variables, Constants and Literals


_______________________________________________________________________________

INTRODUCTION:
In this week’s module, you will learn about Python variables, constants, literals with the help of examples.

Below is the Learning Target/ Specific Objective:


1. Define variables, constants and literals
2. Use variables, constants, and literals in programming
3. Apply the rules of using variables, constants, and literals
4. Identify the types of values assigned to the variables

Exploration of Prior Knowledge

Directions: Fill in the K-W-H-L Chart below to assess your prior knowledge and understanding of the topic

What I Know What I Want to Find Out How I Can Learn What I Have Learned
More

Skills I expect to use:

PROCESS QUESTIONS/ FOCUS QUESTIONS:


Below are the key guide questions that you should remember as you perform all the activities in this lesson. You should be
able to answer them at the end of the week.
1. What are variables, constants and literals?

SHORT EXERCISES/DRILLS:
Activity 1.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)

CONTENT DISCUSSION:

Python Variables
In programming, a variable is a container (storage area) to hold data. For example,

number = 10

Here, number is a variable storing the value 10.

17
Assigning values to Variables in Python
As we can see from the above example, we use the assignment operator = to assign a value to a variable.

# assign value to site_name variable


site_name = 'programiz.pro'

print(site_name)

# Output: programiz.pro

Output

apple.com

In the above example, we assigned the value programiz.pro to the site_name variable. Then, we printed out the value assigned
to site_name

Changing the Value of a Variable in Python


site_name = 'programiz.pro'
print(site_name)

# assigning a new value to site_name


site_name = 'apple.com'

print(site_name)
Output

programiz.pro
apple.com

Here, the value of site_name is changed from 'programiz.pro' to 'apple.com'.

Example: Assigning multiple values to multiple variables


a, b, c = 5, 3.2, 'Hello'

print(a) # prints 5
print(b) # prints 3.2
print(c) # prints Hello

If we want to assign the same value to multiple variables at once, we can do this as:
site1 = site2 ='programiz.com'

print(site1) # prints programiz.com


print(site2) # prints programiz.com
Here, we have assigned the same string value 'programiz.com' to both the variables site1 and site2.

Rules for Naming Python Variables


 Constant and variable names should have a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or
an underscore (_). For example:

snake_case
MACRO_CASE
camelCase
CapWords

 Create a name that makes sense. For example, vowel makes more sense than v.
 If you want to create a variable name having two words, use underscore to separate them. For example:

my_name
current_salary

18
 Python is case-sensitive. So num and Num are different variables. For example,

var num = 5
var Num = 55
print(num) # 5
print(Num) # 55

 Avoid using keywords like if, True, class, etc. as variable names.

Python Constants
A constant is a special type of variable whose value cannot be changed.
In Python, constants are usually declared and assigned in a module (a new file containing variables, functions, etc which is imported to
the main file).
Let's see how we declare constants in separate file and use it in the main file,
Create a constant.py:

# declare constants
PI = 3.14
GRAVITY = 9.8

Create a main.py:

# import constant file we created above


import constant

print(constant.PI) # prints 3.14


print(constant.GRAVITY) # prints 9.8

In the above example, we created the constant.py module file. Then, we assigned the constant value to PI and GRAVITY.
After that, we create the main.py file and import the constant module. Finally, we printed the constant value.

Python Literals
Literals are representations of fixed values in a program. They can be numbers, characters, or strings, etc. For example, 'Hello,
World!', 12, 23.0, 'C', etc.
Literals are often used to assign values to variables or constants. For example,

site_name = 'programiz.com'

In the above expression, site_name is a variable, and 'programiz.com' is a literal.

Python Numeric Literals


Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3 different numerical types: Integer, Float,
and Complex.

Type Example Remarks

Decimal 5, 10, -68 Regular numbers.

0b101,
Binary Start with 0b .
0b11

Octal 0o13 Start with 0o .

Hexadecimal 0x13 Start with 0x .

Floating-point
10.5, 3.14 Containing floating decimal points.
Literal

Numerals in the form a + bj , where a is real and b is


Complex Literal 6 + 9j
imaginary part

19
Python Boolean Literals
There are two boolean literals: True and False.
For example,

pass = true

Here, true is a boolean literal assigned to pass.

String and Character Literals in Python


Character literals are unicode characters enclosed in a quote. For example,

some_character = 'S'

Here, S is a character literal assigned to some_character.


Similarly, String literals are sequences of Characters enclosed in quotation marks.
For example,

some_string = 'Python is fun'

Here, 'Python is fun' is a string literal assigned to some_string.

Special Literal in Python


Python contains one special literal None. We use it to specify a null variable. For example,
value = None

print(value)

# Output: None
Here, we get None as an output as the value variable has no value assigned to it.

Literal Collections
There are four different literal collections List literals, Tuple literals, Dict literals, and Set literals.
# list literal
fruits = ["apple", "mango", "orange"]
print(fruits)

# tuple literal
numbers = (1, 2, 3)
print(numbers)

# dictionary literal
alphabets = {'a':'apple', 'b':'ball', 'c':'cat'}
print(alphabets)

# set literal
vowels = {'a', 'e', 'i' ,'o', 'u'}
print(vowels)

Output

['apple', 'mango', 'orange']


(1, 2, 3)
{'a': 'apple', 'b': 'ball', 'c': 'cat'}
{'e', 'a', 'o', 'i', 'u'}

In the above example, we created a list of fruits, a tuple of numbers, a dictionary of alphabets having values with keys designated to
each value and a set of vowels.

REVISED KNOWLEDGE: Actual answer to the process questions/ focus questions

20
1. What are variables, constants and literals?
 Variable is a named location used to store data in the memory. It has a unique name called identifier. We use the
equal (=) sign to assign the value to a variable.
 A constant is a variable whose values do not change. It is usually assigned and declared on a module. They are
written in all capital letters and underscores to separate the words.
 Literal is a raw data given in a variable constant.

FINAL KNOWLEDGE: Generalization/ Synthesis/ Summary

Variable is a named location used to store data in the memory. It has a unique name called identifier. We use the equal (=) sign to
assign the value to a variable.
A constant is a variable whose values do not change. It is usually assigned and declared on a module. A module is a new file that
contains values or functions, which is imported to the main file. They are written in all capital letters and underscores to separate the
words.
Literal is a raw data given in a variable constant.
Numeric literals are unchangeable. The four (34) numerical types are: plain, integers, long integers, floating point numbers, and
imaginary numbers.
A string literal is a sequence of characters surrounded by single, double, or triple quotes.
A character literal is a single character surrounded by single or double quotes.

TOPIC: Identifying and Converting Data Types


_______________________________________________________________________________
2
CONTENT DISCUSSION:

In computer programming, data types specify the type of data that can be stored inside a variable. For example,

num = 24

Here, 24 (an integer) is assigned to the num variable. So the data type of num is of the int class.

Python Data Types

Data Types Classes Description

Numeric int, float, complex holds numeric values

String str holds sequence of characters

Sequence list, tuple, range holds collection of items

Mapping dict holds data in key-value pair form

Boolean bool holds either True or False

Set set, frozeenset hold collection of unique items

Since everything is an object in Python programming, data types are actually classes and variables are instances(object) of these
classes.

Python Numeric Data type

In Python, numeric data type is used to hold numeric values.

Integers, floating-point numbers and complex numbers fall under Python numbers category. They are defined
as int, float and complex classes in Python.

 int - holds signed integers of non-limited length.


 float - holds floating decimal points and it's accurate up to 15 decimal places.
 complex - holds complex numbers.

We can use the type() function to know which class a variable or a value belongs to.

Let's see an example,

21
num1 = 5
print(num1, 'is of type', type(num1))

num2 = 2.0
print(num2, 'is of type', type(num2))

num3 = 1+2j
print(num3, 'is of type', type(num3))
Run Code

Output

5 is of type <class 'int'>


2.0 is of type <class 'float'>
(1+2j) is of type <class 'complex'>

In the above example, we have created three variables named num1, num2 and num3 with values 5, 5.0, and 1+2j respectively.
We have also used the type() function to know which class a certain variable belongs to.
Since,
 5 is an integer value, type() returns int as the class of num1 i.e <class 'int'>
 2.0 is a floating value, type() returns float as the class of num2 i.e <class 'float'>
 1 + 2j is a complex number, type() returns complex as the class of num3 i.e <class 'complex'>

Python List Data Type

List is an ordered collection of similar or different types of items separated by commas and enclosed within brackets [ ]. For example,

languages = ["Swift", "Java", "Python"]

Here, we have created a list named languages with 3 string values inside it.

Access List Items

To access items from a list, we use the index number (0, 1, 2 ...). For example,

languages = ["Swift", "Java", "Python"]

# access element at index 0


print(languages[0]) # Swift

# access element at index 2


print(languages[2]) # Python
Run Code

In the above example, we have used the index values to access items from the languages list.
 languages[0] - access first item from languages i.e. Swift
 languages[2] - access third item from languages i.e. Python

Python Tuple Data Type

Tuple is an ordered sequence of items same as a list. The only difference is that tuples are immutable. Tuples once created cannot be
modified.
In Python, we use the parentheses () to store items of a tuple. For example,

product = ('Xbox', 499.99)

Here, product is a tuple with a string value Xbox and integer value 499.99.

Access Tuple Items

Similar to lists, we use the index number to access tuple items in Python .

For example,
# create a tuple
product = ('Microsoft', 'Xbox', 499.99)

# access element at index 0


print(product[0]) # Microsoft

22
# access element at index 1
print(product[1]) # Xbox

Python String Data Type

String is a sequence of characters represented by either single or double quotes. For example,
name = 'Python'
print(name)

message = 'Python for beginners'


print(message)
Run Code
Output

Python
Python for beginners

In the above example, we have created string-type variables: name and message with values 'Python' and 'Python for


beginners' respectively.

Python Set Data Type

Set is an unordered collection of unique items. Set is defined by values separated by commas inside braces { }.

For example,
# create a set named student_id
student_id = {112, 114, 116, 118, 115}

# display student_id elements


print(student_id)

# display type of student_id


print(type(student_id))R

Output

{112, 114, 115, 116, 118}


<class 'set'>

Here, we have created a set named student_info with 5 integer values.


Since sets are unordered collections, indexing has no meaning. Hence, the slicing operator [] does not work.

Python Type Conversion

In programming, type conversion is the process of converting data of one type to another. For example: converting integer data
to string.
There are two types of type conversion in Python.
 Implicit Conversion - automatic type conversion
 Explicit Conversion - manual type conversion

Python Implicit Type Conversion


In certain situations, Python automatically converts one data type to another. This is known as implicit type conversion.

Example 1: Converting integer to float


Let's see an example where Python promotes the conversion of the lower data type (integer) to the higher data type (float) to avoid
data loss.
integer_number = 123
float_number = 1.23

new_number = integer_number + float_number

# display new value and resulting data type


print("Value:",new_number)
print("Data Type:",type(new_number))
Run Code

23
Output

Value: 124.23
Data Type: <class 'float'>

In the above example, we have created two variables: integer_number and float_number of integer and float type respectively.


Then we added these two variables and stored the result in new_number.
As we can see new_number has value 124.23 and is of the float data type.
It is because Python always converts smaller data types to larger data types to avoid the loss of data.

Note:
 We get TypeError, if we try to add string and integer. For example, '12' + 23. Python is not able to use Implicit Conversion in
such conditions.
 Python has a solution for these types of situations which is known as Explicit Conversion.

Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to required data type.
We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes) the data type of the objects.

Example 2: Addition of string and integer Using Explicit Conversion


num_string = '12'
num_integer = 23

print("Data type of num_string before Type Casting:",type(num_string))

# explicit type conversion


num_string = int(num_string)

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string

print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Output

Data type of num_string before Type Casting: <class 'str'>


Data type of num_string after Type Casting: <class 'int'>
Sum: 35
Data type of num_sum: <class 'int'>

In the above example, we have created two variables: num_string and num_integer with string and integer type values respectively.

Notice the code,

num_string = int(num_string)

Here, we have used int() to perform explicit type conversion of num_string to integer type.
After converting num_string to an integer value, Python is able to add these two variables.
Finally, we got the num_sum value i.e 35 and data type to be int.

Key Points to Remember


1. Type Conversion is the conversion of an object from one data type to another data type.
2. Implicit Type Conversion is automatically performed by the Python interpreter.
3. Python avoids the loss of data in Implicit Type Conversion.
4. Explicit Type Conversion is also called Type Casting, the data types of objects are converted using predefined functions by the
user.
5. In Type Casting, loss of data may occur as we enforce the object to a specific data type.

REVISED KNOWLEDGE: Actual answer to the process questions/ focus questions


1. What are the different data types in Python?
The different data types in Python are integer, list, tuple, and sting. An integer can be of any length yet only limited by the
memory available .A list is an ordered sequence of items. Items separated by comma and enclosed within brackets. A tuple is an
ordered sequence of items, same as a list. It is immutable and defined within parentheses where items are separated by commas.
A string is a sequence of characters. Multiline strings can be denoted using triple quotes.
24
2. How do we convert data types in Python?
We can convert between data types by using different type conversion functions like int(), float(), str(), etc.

FINAL KNOWLEDGE: Generalization/ Synthesis/ Summary


Numbers in Python can either be integers, floating point numbers, or complex numbers.
The type() function is sued to know which class is a variable or a value belongs to.
The instance() function is used to check if an object belongs to a particular class.
An integer can be of any length yet only limited by the memory available .
A list is an ordered sequence of items. Items separated by comma and enclosed within brackets.
A tuple is an ordered sequence of items, same as a list. It is immutable and defined within parentheses where items are separated by
commas.
A string is a sequence of characters. Multiline strings can be denoted using triple quotes.
A set is an unordered collection of unique items. It is defined by values separated by comma inside braces.

MODULE 6. Displaying Input, Output, and Import Modules

Most Essential Learning Competencies Use the input, output and built-in modules
(MELCs)

TOPIC: Python Basic Input and Output


__________________________________________________________________________

CONTENT DISCUSSION:

Python Output

In Python, we can simply use the print() function to print output. For example,


print('Python is powerful')

# Output: Python is powerful

Here, the print() function displays the string enclosed inside the single quotation.

Syntax of print()
In the above code, the print() function is taking a single parameter.
However, the actual syntax of the print function accepts 5 parameters

print(object= separator= end= file= flush=)

Here,
 object - value(s) to be printed
 sep (optional) - allows us to separate multiple objects inside print().
 end (optional) - allows us to add add specific values like new line "\n", tab "\t"
 file (optional) - where the values are printed. It's default value is sys.stdout (screen)
 flush (optional) - boolean specifying if the output is flushed or buffered. Default: False

Example 1: Python Print Statement


Output
In the above example, the print() statement only includes the object to be printed. Here, the value for end is not used. Hence, it takes
the default value '\n'.
So we get the output in two different lines.
# print with end whitespace
print('Good Morning!', end= ' ')

print('It is rainy today')


Output

Good Morning! It is rainy today

Notice that we have included the end= ' ' after the end of the first print() statement.
Hence, we get the output in a single line separated by space.

25
Example 2: Python print() with sep parameter
print('New Year', 2023, 'See you soon!', sep= '. ')
Output

New Year. 2023. See you soon!

In the above example, the print() statement includes multiple items separated by a comma.


Notice that we have used the optional parameter sep= ". " inside the print() statement.
Hence, the output includes items separated by . not comma.

Example: Print Python Variables and Literals


We can also use the print() function to print Python variables. For example,
number = -10.6

name = "Programiz"

# print literals
print(5)

# print variables
print(number)
print(name)
Output

5
-10.6
Programiz

Example: Print Concatenated Strings


We can also join two strings together inside a print() statement. For example,
print('Programiz is ' + 'awesome.')

Output

Programiz is awesome.

Here,
 the + operator joins two strings 'Programiz is ' and 'awesome.'
 the print() function prints the joined string

Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by using the str.format() method. For
example,
x = 5
y = 10

print('The value of x is {} and y is {}'.format(x,y))


Here, the curly braces {} are used as placeholders. We can specify the order in which they are printed by using numbers (tuple index).

Python Input
While programming, we might want to take the input from the user. In Python, we can use the input() function.
Syntax of input()

input([prompt])

Here, prompt is the string we wish to display on the screen. It is optional.

Example: Python User Input


# using input() to take user input
num = input('Enter a number: ')

26
print('You Entered:', num)

print('Data type of num:', type(num))


Run Code
Output

Enter a number: 10
You Entered: 10
Data type of num: <class 'str'>

In the above example, we have used the input() function to take input from the user and stored the user input in the num variable.
It is important to note that the entered value 10 is a string, not a number. So, type(num) returns <class 'str'>.
To convert user input into a number we can use int() or float() functions as:

num = int(input('Enter a number: '))

Here, the data type of the user input is converted from string to integer .

REVISED KNOWLEDGE: Actual answer to the process questions/ focus questions


1. What are the steps in input, output and importing modules?
In displaying input, output and importing modules, certain functions are used. The print() function is used to display the output data on
the screen.The str.format() method is used to format the output.The curly braces {} are used as placeholders.The input() function is
used to define value of variables.Prompt is the string we wish to display on the screen.A module contains the Python definitions and
statements.Definitions inside a module can be imported to another module or the interactive interpreter in Python.

FINAL KNOWLEDGE: Generalization/ Synthesis/ Summary

The print() function is used to display the output data on the screen.
The str.format() method is used to format the output.
The curly braces {} are used as placeholders.
The input() function is used to define value of variables.
Prompt is the string we wish to display on the screen.
A module contains the Python definitions and statements.
Definitions inside a module can be imported to another module or the interactive interpreter in Python.

MODULE WEEK 7. Using Operators

Most Essential Learning Competencies Learn to use assignment operators to assign the specific data to its container
(MELCs)
REFERENCES:(Please be guided with the given references to help you perform the given activities. Click the given links and
hyperlinks to access the suggested learning resources.)

 Printed: Cobre, E. J., Olalia, N., &Tingzon, K. (2019). ICT Tools Today High School Series Computers for Digital Learners
Grade 10 (1st ed., Vol. 1) [Book]. The Phoenix Publishing house Inc.

 Online: Learn Python Programming. (n.d.). https://www.programiz.com/python-programming

TOPIC: Python Operators


___________________________________________________________________________
INTRODUCTION:

In this week’s module, we'll learn everything about different types of operators in Python, their syntax and how to
use them with examples

Below is the Learning Target/ Specific Objective:


1. Define operators
2. Enumerate the arithmetic operators
3. Enumerate the comparison operators
4. Enumerate the logic operators
5. Enumerate the assignment operators
6. Enumerate the identity operators
7. Formulate solutions to problems
Exploration of Prior Knowledge

27
Directions: Fill in the K-W-H-L Chart below to assess your prior knowledge and understanding of the topic, Select Case
Structure.
What I Want to Find How I Can Learn
What I Know What I Have Learned
Out More

Skills I expect to use:

PROCESS QUESTIONS/ FOCUS QUESTIONS:


Below are the key guide questions that you should remember as you perform all the activities in this lesson. You should be
able to answer them at the end of the week.
1. What are operators?
2. What are the arithmetic operators?
3. What are the comparison operators?
4. What are the logic operators?
5. What are the assignment operators?
6. What are the identity operators?
7. How do we formulate solutions to problems?

SHORT EXERCISES/DRILLS:
Direction: Evaluate the Program Line
Analyze this code: x = 15
y=4

Evaluate each program line. Write the output on the line.


_________________________________1 print(‘ x + y = ’, x + y)
.
_________________________________2 print(‘ x * y =’, x*y)
.
_________________________________3 print(‘x/y = ’ x/y) CONTENT
. DISCUSSION:
_________________________________4 print(‘x//y=’, x//y)
. Python Operators
_________________________________5 print(‘x**y=’,x**y) Operators are special
symbols that perform
.
operations on variables
and values. For example,
print(5 + 6) # 11

Here, + is an operator that adds two numbers: 5 and 6.

Types of Python Operators


Here's a list of different types of Python operators that we will learn in this tutorial.
1. Arithmetic operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Special Operators

1. Python Arithmetic Operators


Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc. For example,

sub = 10 - 5# 5

Here, - is an arithmetic operator that subtracts two values or variables.

Operator Operation Example

+ Addition 5+2=7

- Subtraction 4-2=2

28
* Multiplication 2*3=6

/ Division 4/2=2

% Modulo 5%2=1

** Power 4 ** 2 = 16

Example 1: Arithmetic Operators in Python


a = 7
b = 2

# addition
print ('Sum: ', a + b)

# subtraction
print ('Subtraction: ', a - b)

# multiplication
print ('Multiplication: ', a * b)

# division
print ('Division: ', a / b)

# modulo
print ('Modulo: ', a % b)

# a to the power b
print ('Power: ', a ** b)
Output

Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Modulo: 1
Power: 49

In the above example, we have used multiple arithmetic operators,


 + to add a and b
 - to subtract b from a
 * to multiply a and b
 / to divide a by b
 % to get the remainder
 ** to get a to the power b

2. Python Assignment Operators


Assignment operators are used to assign values to variables. For example,

# assign 5 to x
var x = 5
Here, = is an assignment operator that assigns 5 to x.
Here's a list of different assignment operators available in Python.

Operator Name Example

= Assignment Operator a=7

29
+= Addition Assignment a += 1 # a = a + 1

-= Subtraction Assignment a -= 3 # a = a - 3

*= Multiplication Assignment a *= 4 # a = a * 4

/= Division Assignment a /= 3 # a = a / 3

%= Remainder Assignment a %= 10 # a = a % 10

**= Exponent Assignment a **= 10 # a = a ** 10

Example 2: Assignment Operators


# assign 10 to a
a = 10

# assign 5 to b
b = 5

# assign the sum of a and b to a


a += b # a = a + b

print(a)

# Output: 15
Here, we have used the += operator to assign the sum of a and b to a.
Similarly, we can use any other assignment operators according to the need.

3. Python Comparison Operators


Comparison operators compare two values/variables and return a boolean result: True or False. For example,
a = 5
b =2

print (a >b) # True


Here, the > comparison operator is used to compare whether a is greater than b or not.

Operator Meaning Example

== Is Equal To 3 == 5 gives us False

!= Not Equal To 3 != 5 gives us True

> Greater Than 3 > 5 gives us False

< Less Than 3 < 5 gives us True

>= Greater Than or Equal To 3 >= 5 give us False

<= Less Than or Equal To 3 <= 5 gives us True

Example 3: Comparison Operators


a = 5

b = 2

# equal to operator

30
print('a == b =', a == b)

# not equal to operator


print('a != b =', a != b)

# greater than operator


print('a > b =', a > b)

# less than operator


print('a < b =', a < b)

# greater than or equal to operator


print('a >= b =', a >= b)

# less than or equal to operator


print('a <= b =', a <= b)
Output

a == b = False
a != b = True
a > b = True
a < b = False
a >= b = True
a <= b = False

4. Python Logical Operators


Logical operators are used to check whether an expression is True or False. They are used in decision-making. For example,
a = 5
b = 6

print((a >2) and (b >= 6)) # True


Here, and is the logical operator AND. Since both a > 2 and b >= 6 are True, the result is True.

Operator Example Meaning

Logical AND:
and a and b
True only if both the operands are True

Logical OR:
or a or b
True if at least one of the operands is True

Logical NOT:
not not a
True if the operand is False and vice-versa.

Example 4: Logical Operators


# logical AND
print(TrueandTrue) # True
print(TrueandFalse) # False

# logical OR
print(TrueorFalse) # True

# logical NOT
print(notTrue) # False

Python Special operators


Python language offers some special types of operators like the identity operator and the membership operator. They are described
below with examples.

31
Identity operators
In Python, is and is not are used to check if two values are located on the same part of the memory. Two variables that are equal does
not imply that they are identical.

Operator Meaning Example

is True if the operands are identical (refer to the same object) x is True

is not True if the operands are not identical (do not refer to the same object) x is not True

Example 4: Identity operators in Python


x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]

print(x1 isnot y1) # prints False

print(x2 is y2) # prints True

print(x3 is y3) # prints False


Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. Same is the case
with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them separately in memory although they
are equal.

REVISED KNOWLEDGE: Actual answer to the process questions/ focus questions


1. What are operators?
Operators are special symbols in Python that perform arithmetic or logical computations.Operands are the values
used by the operator.

2. What are the arithmetic operators?

3. What are the comparison operators?

4. What are the logic operators?

32
5. What are the assignment operators?

6. What are the identity operators?

7. How do we formulate solutions to problems?


Formulating solutions to problems cannot start with an empty head. We fill our minds with knowledge and enrich
our experiences through reading. We gather information to solve problems. We keep solving. A winner goes through
a problem; a loser goes around it, and never gets past it.

FINAL KNOWLEDGE: Generalization/ Synthesis/ Summary


Operators are special symbols in Python that perform arithmetic or logical computations.
Operands are the values used by the operator.
Arithmetic operators perform mathematical operations.
Comparison operators compare values from left to right. They either return True or False according to the condition.
Logical operators are and, or, and not.
Assignment operators assign values to variables.
The operators is and is notare identity operators in Python. These are used to check if two (2) values or variable are stored in the same
part of the memory.

Prepared: Checked:

GLENN XAVIER B. MAGNO LEVELYN D. GARCIA


Subject Teacher/Coordinator Curriculum Coordinator

Noted:

ANNABELLE G. TACADENA
School Principal

33

You might also like