Lesson 2: Data Types and Variables
Learning Path: Python for Programmers, Module 1: Python Fundamentals
Table of Content
This lesson is a part of Learning Path, Python for Programmers.
Value
Value: A value is one of the fundamental things in any program. A value may be a letter or a number that a program manipulates.
For example,
- 2 is of numeric data type.
- Hello, World! is of sequence data type.
To determine the type of a value, we use a built-in python function type()
.
More on built-in functions in the latter part of the series.
print(type(2))
print(type('Hello World'))
print(type(3.2))
print(type('3.2'))
<class 'int'>
<class 'str'>
<class 'float'>
<class 'str'>
In the 4th statement, we have enclosed 3.2 in quotation marks '
. Thus the floating-point number 3.2
is treated as a string.
Variable
Variable: a name to which a value can be assigned.
Variables allow us to give a meaningful name to a value(data).
The assignment statement creates new variables and gives them values. The simplest way to assign a value to a variable is through an =
operator.
A big advantage of variables is that they allow us to store data and can later be used to perform operations or manipulate the data of the variable in the code.
In Python, the value of a mutable variable can always be updated or replaced.
Variables are mutable(something that is changeable or has the ability to change).
In Python, everything is treated as an object.
Every object has these three attributes:
- Identity - refers to the address of an object in a computer’s memory.
- Type - refers to the kind of object that is created. For example – integer, dictionary, list, string, etc.
- Value - refers to the data stored in the object. For example – num_list=[1,2,3] would hold the numbers 1,2 and 3.
While
identity
andtype
cannot be changed once it’s created,values
can be changed for mutable objects.
Naming Convention
There are some rules we need to follow when picking the name for a variable:
- The first character must start with an UPPERCASE or LOWERCASE letter of alphabet or UNDERSCORE(_)
- Rest of the name can consist of UPPERCASE or LOWERCASE letter of alphabet or UNDERSCORE(_) or DIGITS(0-9)
- Spaces are not allowed. Instead, use
snake_case
to make variable names readable. - Names are case-sensitive,
myworld
andmyWorld
are not the same. - The name of the variable should be something meaningful that describes the value it holds, instead of being random characters.
Data Type
Data Type: The data type of a value defines the type and range of values that data can have.
Python language provides 3 main data types:
- Numeric type
- Booleans
- Sequence type
Numeric Data Type
The numeric data type represents the data that has a numeric value.
Integers
The integer data type is comprised of all the positive and negative whole numbers.
0 takes up 24 bytes whereas 1 occupies 28 bytes.
print(55) # A positive integer
print(-3000) # A negative integer
num = 987654321 # Assigning an integer to a variable
print(num)
num = -12345678 # Assigning a new integer
print(num)
55
-3000
987654321
-12345678
Floating Point Numbers
Floating-point numbers, or floats, refer to positive and negative decimal numbers.
A floating-point occupies 24 bytes of memory.
print(1.00000000005) # A positive float
print(-21.21312) # A negative float
flt_point = 1.23232 # Assigning float number
print(flt_point)
1.00000000005
-21.21312
1.23232
Complex Numbers
Python supports numbers made up of real part and imaginary part, which is specified as (real part) + (imaginary part)j
.
Built-in function complex()
is used to create complex numbers.
A complex number usually takes up 32 bytes of memory.
print(complex(2, 20)) # Represents the complex number (2 + 20j)
print(complex(1.5, -1.2)) # Represents the complex number (1.5 - 1.2j)
complex_1 = complex(0, 2)
complex_2 = complex(2, 0)
print(complex_1)
print(complex_2)
(2+20j)
(1.5-1.2j)
2j
(2+0j)
Complex numbers are useful for modeling physics and electrical engineering models in Python.
Booleans
The Boolean(bool) data type allows us to choose between two values: true
and false
. It is used to determine whether the logic of an expression or a comparison is correct.
The first letter of a bool needs to be capitalized in Python.
print(True)
f_bool = False
print(f_bool)
True
False
While comparing two values, the expression is evaluated and Python returns the Boolean answer.
print(10 > 9)
print(10 == 9)
print(10 < 9)
True
False
False
0 is considered as False and 1 as True.
x = 1
y = 0
print(bool(x))
print(bool(y))
True
False
Sequence Data Type
A string is a collection of characters or a sequence of bytes representing Unicode characters enclosed within single '
or double "
quotation marks.
In python there is no character data type, a character is a string of length 1.
print("Winter Soldier!") # Double quotation marks
avengers = 'Captain America: The Winter Soldier' # Single quotation marks
print(avengers)
print("@") # Single character
empty = "" # Empty string
print(empty)
flt_point = "2.3" # float point number
print(flt_point)
Winter Soldier!
Captain America: The Winter Soldier
@
2.3
Length of string
We can use the built-in function len()
to get the length of a string.
random_string = 'I can do this all day.' # 22 characters
print(len(random_string))
22
Indexing and Accessing Characters
Every character in a string is given a numerical index based on its position in the sequence.
A string sequence in Python is indexed from 0 to n-1 where n is the length of the sequence.
cap_america = "Steve Rogers"
first = cap_america[0] # Accessing the first character
print(first)
space = cap_america[5] # Accessing the empty space in the string
print(space)
last = cap_america[len(cap_america) - 1] # len(cap_america)=12
print(last)
# The following will produce an error since the index is out of range
err = cap_america[len(cap_america)]
S
s
Traceback (most recent call last):
File "<stdin>", line 13, in <module>
IndexError: string index out of range
If we try to execute the 13th statement, we would get an error because the maximum index is len(cap_america) - 1
which is 11, and we are trying to access the 12th index of the variable.
We can also use negative indices. For example, -1
corresponds to the last index.
capAmerica = 'Steve Rogers'
print(capAmerica[-1]) # corresponds to capAmerica[11]
print(capAmerica[-5]) # corresponds to capAmerica[7]
s
o
String Slicing
Slicing: is the process of obtaining a portion or substring of a string by using its indices.
To obtain a substring we can use: string[start:end]
my_string = "Give me a scotch, I am starving."
print(my_string[0:4]) # From the start till before the 4th index
print(my_string[1:7])
print(my_string[8:len(my_string)]) # From the 8th index till the end
Give
ive me
a scotch, I am starving.
Slicing using Step: We can also define a step to skip characters in the string using string[start:end:step]
.
my_string = "Give me a scotch, I am starving."
print(my_string[0:12]) # A step of 1
print(my_string[0:12:2]) # A step of 2
print(my_string[0:12:5]) # A step of 5
Give me a sc
Gv eas
Gms
Reverse Slicing: Strings can also be sliced to return a reversed substring.
my_string = "Give me a scotch, I am starving."
print(my_string[13:2:-1]) # 1 step back each time
print(my_string[17:0:-2]) # 2 step back each time
tocs a em e
htc mei
Partial Slicing: Specifying the start and end are optional.
my_string = "Give me a scotch, I am starving."
print(my_string[:8]) # All the characters before 'a'
print(my_string[8:]) # All the characters starting from 'a'
print(my_string[:]) # prints The whole string
print(my_string[::-1]) # The whole string in reverse (step is -1)
Give me
a scotch, I am starving.
Give me a scotch, I am starving.
.gnivrats ma I ,hctocs a em eviG
Type Conversions
There may be times when we need to change data from one type to another. When the data type is manually changed by the user as per their requirement we call it Explicit Type Conversion
.
There are built-in functions that allow us to perform such explicit type conversions. More about functions in the Functions module.
int()
Convert data into an integer.
print(int("12") * 10) # String to integer
print(int(20.5)) # Float to integer
print(int(False)) # Bool to integer
print(int("Hello")) # this won't work
120
20
0
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
ValueError: invalid literal for int() with base 10: 'Hello'
ord()
Character to Unicode value. ord()
expects character value.
print(ord('j'))
print(ord('Y'))
106
89
float()
Converts data into floating-point numbers.
print(float(25))
print(float('25.5'))
print(float(True))
25.0
25.5
1.0
str()
Converts data into a string.
print(str(122) + ".3213")
print(str(True))
print(str(123.213))
122.3213
True
123.213
bool()
Converts data into a boolean value.
Strings are always converted to
True
, except if it is empty.
Floats and integers with a value of zero are considered to beFalse
.
print(bool(10))
print(bool(0.0))
print(bool("Hello"))
print(bool(""))
True
False
True
False
There are other conversions as well, which we will cover as we progress through the series.
I'll be sharing the practice problem set as we finish one complete module.
In the next section, we will start with Operators.