0% found this document useful (0 votes)
32 views

Module Weeks 4 5

The document discusses declaring variables, constants, and literals in Python. It defines variables as containers that store data, constants as variables whose values cannot change, and literals as raw data values. It describes assigning values to variables, changing variable values, and naming rules for variables. It also discusses numeric, boolean, string, and collection literals, as well as built-in constant and data types in Python.
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)
32 views

Module Weeks 4 5

The document discusses declaring variables, constants, and literals in Python. It defines variables as containers that store data, constants as variables whose values cannot change, and literals as raw data values. It describes assigning values to variables, changing variable values, and naming rules for variables. It also discusses numeric, boolean, string, and collection literals, as well as built-in constant and data types in Python.
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/ 8

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


_______________________________________________________________________________

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.


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

 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

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

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,

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

# 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

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.

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.

You might also like