Lesson 4
Lesson 4
VARIABLES, CONSTANTS,
LITERALS AND DATA TYPES 4
INTRODUCTION
The basis of a programming language contains data elements and the block in
which they are being stored. Specific names are given for each of these, and special
functionalities can be performed on them. In a programming language, they are called as
Variables, Constants, and Literals. In this article, we will look at Python Constants,
Variables, and Literals along with their types and examples.
Apart from those, you will also know the various data types that Python
recognizes. Data types are important concepts in programming that cannot be missed
out.
LESSON PROPER
PYTHON VARIABLES
A variable is a named location used to store data in the memory. It is helpful to think of
variables as a container that holds data that can be changed later in the program. For
example,
number = 10
Here, we have created a variable named number. We have assigned the value 10 to the
variable.
You can think of variables as a bag to store books in it and that book can be replaced at
any time.
number = 10
number = 1.1
Initially, the value of number was 10. Later, it was changed to 1.1.
Note: In Python, we don't actually assign values to the variables. Instead, Python
gives the reference of the object(value) to the variable.
As you can see from the above example, you can use the assignment operator = to
assign a value to a variable.
Output
apple.com
In the above program, we assigned a value apple.com to the variable website. Then, we
printed out the value assigned to website i.e. apple.com
Note: Python is a type-inferred language, so you don't have to explicitly define the
variable type. It automatically knows that apple.com is a string and declares
the website variable as a string.
print(website)
Output
apple.com
nipsc.edu.ph
In the above program, we have assigned apple.com to the website variable initially. Then,
the value is changed to nipsc.edu.ph.
print (a)
print (b)
print (c)
If we want to assign the same value to multiple variables at once, we can do this as:
x = y = z = "same"
print (x)
print (y)
print (z)
The second program assigns the same string to all the three variables x, y and z.
CONSTANTS
You can think of constants as a bag to store some books which cannot be replaced once
placed inside the bag.
In Python, constants are usually declared and assigned in a module. Here, the module is
a new file containing variables, functions, etc which is imported to the main file. Inside
the module, constants are written in all capital letters and underscores separating the
words.
Create a constant.py:
PI = 3.14
GRAVITY = 9.8
Create a main.py:
import constant
print(constant.PI)
print(constant.GRAVITY)
Output
3.14
9.8
In the above program, we create a constant.py module file. Then, we assign the constant
value to PI and GRAVITY. After that, we create a main.py file and import
the constant module. Finally, we print the constant value.
Note: In reality, we don't use constants in Python. Naming them in all capital
letters is a convention to separate them from variables, however, it does not
actually prevent reassignment.
snake_case
MACRO_CASE
camelCase
CapWords
2. Create a name that makes sense. For example, vowel makes more sense than v.
3. If you want to create a variable name having two words, use underscore to
separate them. For example:
my_name
current_salary
LITERALS
Literal is a raw data given in a variable or constant. In Python, there are various types of
literals they are as follows:
Numeric Literals
#Float Literal
float_1 = 10.5
float_2 = 1.5e2
#Complex Literal
x = 3.14j
print(a, b, c, d)
print(float_1, float_2)
print(x, x.imag, x.real)
Output
String literals
A string literal is a sequence of characters surrounded by quotes. We can use both single,
double, or triple quotes for a string. And, a character literal is a single character
surrounded by single or double quotes.
print(strings)
print(char)
print(multiline_str)
print(unicode)
print(raw_str)
Output
This is Python
C
This is a multiline string with more than one line code.
Ünicöde
raw \n string
In the above program, This is Python is a string literal and C is a character literal.
The value in triple-quotes """ assigned to the multiline_str is a multi-line string literal.
Boolean literals
A Boolean literal can have any of the two values: True or False.
print("x is", x)
print("y is", y)
print("a:", a)
print("b:", b)
Output
x is True
y is False
a: 5
b: 10
In the above program, we use boolean literal True and False. In Python, True represents
the value as 1 and False as 0. The value of x is True because 1 is equal to True. And, the
value of y is False because 1 is not equal to False.
Similarly, we can use the True and False in numeric expressions as the value. The value
of a is 5 because we add True which has a value of 1 with 4. Similarly, b is 10 because we
add the False having value of 0 with 10.
Special literals
Python contains one special literal i.e. None. We use it to specify that the field has not
been created.
def menu(x):
if x == drink:
print(drink)
else:
print(food)
menu(drink)
menu(food)
Output
Available
None
In the above program, we define a menu function. Inside menu, when we set the
argument as drink then, it displays Available. And, when the argument is food, it
displays None.
Literal Collections
There are four different literal collections: List literals, Tuple literals, Dict literals, and Set
literals.
print(fruits)
print(numbers)
print(alphabets)
print(vowels)
Output
DATA TYPES
Python Numbers
Integers, floating point numbers and complex numbers fall under Python numbers
category. They are defined as int, float and complex classes in Python.
We can use the type() function to know which class a variable or a value belongs to.
Similarly, the isinstance() function is used to check if an object belongs to a particular
class.
a=5
print(a, "is of type", type(a))
a = 2.0
Output
Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part. Here are some examples.
>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
>>> c = 1+2j
>>> c
(1+2j)
Python List
List is an ordered sequence of items. It is one of the most used datatype in Python and is
very flexible. All the items in a list do not need to be of the same type. Declaring a list is
pretty straight forward. Items separated by commas are enclosed within brackets [ ].
We can use the slicing operator [ ] to extract an item or a range of items from a list. The
index starts from 0 in Python.
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
Output
a[2] = 15
a[0:3] = [5, 10, 15]
a[5:] = [30, 35, 40]
Lists are mutable, meaning, the value of elements of a list can be altered.
a = [1, 2, 3]
a[2] = 4
print(a)
Output
[1, 2, 4]
Python Tuple
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.
Tuples are used to write-protect data and are usually faster than lists as they cannot
change dynamically.
t = (5,'program', 1+3j)
We can use the slicing operator [] to extract items but we cannot change its value.
t = (5,'program', 1+3j)
# t[1] = 'program'
print("t[1] = ", t[1])
# Generates error
# Tuples are immutable
t[0] = 10
Output
t[1] = program
t[0:3] = (5, 'program', (1+3j))
Traceback (most recent call last):
File "test.py", line 11, in <module>
t[0] = 10
TypeError: 'tuple' object does not support item assignment
Python Strings
String is sequence of Unicode characters. We can use single quotes or double quotes to
represent strings. Multi-line strings can be denoted using triple quotes, ''' or """.
s = "This is a string"
print(s)
s = '''A multiline
string'''
print(s)
Output
This is a string
A multiline
string
Just like a list and tuple, the slicing operator [ ] can be used with strings. Strings,
however, are immutable.
s = 'Hello world!'
# s[4] = 'o'
print("s[4] = ", s[4])
# s[6:11] = 'world'
print("s[6:11] = ", s[6:11])
# Generates error
# Strings are immutable in Python
s[5] ='d'
Output
s[4] = o
s[6:11] = world
Traceback (most recent call last):
File "<string>", line 11, in <module>
TypeError: 'str' object does not support item assignment
Python Set
a = {5,2,3,1,4}
Output
a = {1, 2, 3, 4, 5}
<class 'set'>
We can perform set operations like union, intersection on two sets. Sets have unique
values. They eliminate duplicates.
a = {1,2,2,3,3,3}
print(a)
Output
{1, 2, 3}
Since, set are unordered collection, indexing has no meaning. Hence, the slicing operator
[ ] does not work.
>>> a = {1,2,3}
>>> a[1]
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
TypeError: 'set' object does not support indexing
Python Dictionary
In Python, dictionaries are defined within braces {} with each item being a pair in the
form key:value. Key and value can be of any type.
>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>
We use key to retrieve the respective value. But not the other way around.
d = {1:'value','key':2}
print(type(d))
# Generates error
print("d[2] = ", d[2])
Output
<class 'dict'>
d[1] = value
d['key'] = 2
Traceback (most recent call last):
File "<string>", line 9, in <module>
KeyError: 2
We can convert between different data types by using different type conversion
functions like int(), float(), str(), etc.
>>> float(5)
5.0
Conversion from float to int will truncate the value (make it closer to zero).
>>> int(10.6)
10
>>> int(-10.6)
-10
>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1p'
>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}
SUMMARY
A variable is a named location used to store data in the memory. It is helpful to think
of variables as a container that holds data that can be changed later in the program.
You can use the assignment operator = to assign a value to a variable.
A constant is a type of variable whose value cannot be changed. It is helpful to think
of constants as containers that hold information which cannot be changed later.
Rules and Naming Convention for Variables and constants
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
(_).
Create a name that makes sense.
If you want to create a variable name having two words, use underscore
to separate them.
Use capital letters possible to declare a constant.
Never use special symbols like !, @, #, $, %, etc.
Don't start a variable name with a digit.
Literal is a raw data given in a variable or constant.
The following are Python data types:
Numbers
Lists
Tuples
String
Set
Dictionary
SELF-LEARNING ASSESSMENT
Let us see how much you have learned from this lesson. Answer
the following questions.
ESSAY: Based on your understanding, discuss the following items using your own words.
Each item is 10 points.
1. What are the differences between variables, constants and literals? Their
similarities?
ENRICHMENT ACTIVITY
You work in baseball operations at the NY Mets and are purchasing baseball caps from
NewEra for next season. NewEra sells two types of caps, a snapback and a flex cap. The
price points for each hat are listed below. Based on forecasted demand for next season
you plan to buy 40,000 snapbacks and 70,000 flex hats.
Flex=$12.45
Snapback=$10.60
Create variables for: snap_num (the number of snap caps), flex_num (the number of flex
caps), along with the corresponding prices: snap_px, flex_px.