UNIT II
NUMBERS
⦿ The number data type are used to store the
numeric values.
⦿ Python supports
⚫ Integers
⚫ floating-point numbers
⚫ complex numbers.
⦿ 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.
NUMBERS
⦿ Integers and floating points are
separated by the presence or absence
of a decimal point.
? 5 is an integer
? 5.42 is a floating-point number.
? Complex numbers are written in the
form, x + yj, where x is the real part
and y is the imaginary part.
⦿ We can use the type() function to know
which class a variable or a value
belongs to.
NUMBERS
Example
num1 = 5
print(num1, 'is of type', type(num1))
num2 = 5.42
print(num2, 'is of type', type(num2))
num3 = 8+2j
print(num3, 'is of type', type(num3))
Output
5 is of type <class 'int'>
5.42 is of type <class 'float'>
(8+2j) is of type <class 'complex'>
NUMBER SYSTEM
⦿ Number System
? Binary Number System (base or radix =2)
? Octal Number System (base or radix = 8)
? Decimal Number System (base or radix = 10)
? Hexadecimal Number System (base or radix = 16)
⦿ The numbers we deal with every day are
of the decimal (base 10) number system.
⦿ But computer programmers need to work
with binary (base 2), hexadecimal (base
16) and octal (base 8) number systems.
⦿ In Python, we can represent these
numbers by appropriately placing a prefix
before that number.
NUMBER SYSTEM
⦿ The following table lists these prefixes.
Number System Prefix
Binary 0b or 0B
Octal 0o or 0O
Hexadecimal 0x or 0X
⦿ Examples
print(0b1101011) # prints 107
print(0o15) # prints 13
print(0xFB + 0b10) # prints 253
print(0b1101011) # prints 107
1 1 0 1 0 1 1
1 * 20 =
1
1 * 21 =
2
0 * 22 =
0
1 * 23 =
8
0* 24 =
0
1* 25 =
32
1* 26 =
64
64 + 32 + 0 + 8 + 0 + 2 + 1 = 107
print(0o15) # prints 13
1 5
5 * 80 =
5
1 * 81 =
8
8 + 5 = 13
print(0xFB + 0b10) # prints 253
F B
11 * 160 =
11 240 + 11 =
251
15 * 161 =
240
1 0
0 * 20 =
0 0+2 =
2
1 * 21 =
2
Ans : 251+2 = 253
TYPE CONVERSION IN PYTHON
⦿ In programming, type conversion is the
process of converting one type of number
into another.
⦿ Operations like addition, subtraction
convert integers to float implicitly
(automatically), if one of the operands is
float.
⦿ Eg: print(1 + 2.0) # prints 3.0
Here, we can see above that 1
(integer) is converted into 1.0 (float) for
addition and the result is also a floating
point number.
EXPLICIT TYPE CONVERSION
⦿ We can also use built-in functions like int(),
float() and complex() to convert between
types explicitly.
⦿ These functions can even convert from
strings
num1 = int(2.3)
print(num1) # prints 2
num2 = int(-2.8)
print(num2) # prints -2
num3 = float(5)
print(num3) # prints 5.0
EXAMPLE 1: ADD TWO NUMBERS
num1 = 1.5
num2 = 6.3
# Add two numbers
sum = num1 + num2
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2,
sum))
Output
The sum of 1.5 and 6.3 is 7.8
EXAMPLE 2: ADD TWO NUMBERS WITH USER INPUT
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2,
sum))
Output
Enter first number: 1.5
Enter second number: 6.3
The sum of 1.5 and 6.3 is 7.8
OPERATOR
Operator in Python:
⦿ Operators are the special symbols in python and are
used to execute an Arithmetic or Logical computation.
⦿ An operator alone cannot perform an activity, it
needs an Operand.
Operand in Python:
⦿ An Operand is a value that the operator needs to
complete a task.
TYPES OF OPERATORS IN
PYTHON
We have multiple operators in Python, and each operator
is subdivided into other operators.
⦿ Arithmetic operators
⦿ Comparison operators
⦿ Assignment operators
⦿ Logical operators
⦿ Bitwise operators
⦿ Membership operators
⦿ Special operators
◼ Identity operators
◼ Membership operators
ARITHMETIC OPERATORS
⦿ Arithmetic operators are used for executing
the mathematical functions in Python which
includes, addition, subtraction, multiplication,
division,
Operator
etc.
Description Example
+Plus Adds two Operands. 3+3= 6
-Minus Right hand Operand subtracted from the left hand operand. 20-10=10
* Multiplication It Multiplies the values on either side of the operands. 10*10 = 100
/ Division left hand operand divided by right hand operand. 50/5 = 10
It divides the left hand operand by right hand one and also returns
% Percent 6/2 = 3
reminder.
>>>5.0/2
Division that results into whole number adjusted to the left in the 2.5
// Floor division
number line. >>> 5.0 /2
2.0
** Exponent Left operand is raised to the power of right 10 to the power of 30
PYTHON COMPARISON OPERATORS
⦿ The name itself is explaining that this
operator is used to compare different
things or values with one another.
⦿ In Python, the Comparison operator is
used to analyze either side of the values
and decides the relation between them.
⦿ Comparison operator is also termed as a
relational operator because it explains
the connection between them.
PYTHON COMPARISON OPERATORS
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
PYTHON ASSIGNMENT OPERATORS
Operator Name Example
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
PYTHON LOGICAL OPERATORS
⦿ Logical operators are used in any programming
language to make decision based on multiple
conditions.
⦿ In python, we use Logical operators to
determine whether a condition is True or False
by taking Operand values as base.
Operator Description Example
and Returns True if both x < 5 and x < 10
statements are true
or Returns True if one of the x < 5 or x < 4
statements is true
not Reverse the result, returns not(x < 5 and x < 10)
False if the result is true
PYTHON SEQUENCES
⦿ In Python programming, sequences are a
generic term for an ordered set which
means that the order in which we input the
items will be the same when we access
them.
⦿ Python supports six different types of
sequences.
⦿ These are
◼ Strings
◼ Lists
◼ Tuples
◼ byte sequences
◼ byte arrays
◼ range objects.
PYTHON STRINGS
⦿ Strings are a group of characters
written inside a single or double-
quotes.
⦿ Python does not have a character type
so a single character inside quotes is
also considered as a string.
Code:
name = “Python”
type(name)
Output:
<class ‘str’>
PYTHON LISTS
⦿ Python lists are similar to an array but
they allow us to create a
heterogeneous collection of items
inside a list.
⦿ A list can contain
? Numbers
? Strings
? Lists
? Tuples
? Dictionaries
? Objects
⦿ Lists are declared by using square
brackets around comma-separated
items.
Syntax:
list1 = [1,2,3,4]
list2 = [‘red’, ‘green’, ‘blue’]
list3 = [‘hello’, 100, 3.14, [1,2,3] ]
Code:
list = [10,20,30,40]
list[1] = 100
print( list)
Output:
[10, 100, 30, 40]
PYTHON TUPLES
⦿ Tuples are also a sequence of Python
objects.
⦿ A tuple is created by separating items
with a comma.
⦿ They can be optionally put inside the
parenthesis () but it is necessary to
put parenthesis in an empty tuple.
⦿ A single item tuple should use a
comma in the end.
Code:
tup = ()
print( type(tup) )
tup = (1,2,3,4,5)
tup = ( “78 Street”, 3.8, 9826 )
print(tup)
Output:
<class ‘tuple’>
(‘78 Street’, 3.8, 9826)
BYTES SEQUENCES IN PYTHON
⦿ The bytes() function in Python is used to
return an immutable bytes sequence.
⦿ Since they are immutable, we cannot
modify them.
⦿ This is how we can create a byte of a given
integer size.
Code:
size = 10
b = bytes(size)
print( b )
Output:
b’\x00\x00\x00\x00\x00\x00\x00\x00\
x00\x00′
BYTE ARRAYS IN PYTHON
⦿ Byte arrays are similar to bytes sequence.
⦿ The only difference here is that byte arrays are
mutable while bytes sequences are immutable.
⦿ So, it also returns the bytes object the same
way.
Code:
a = bytearray([1,3,4,5])
print(a)
a[2] = 2
print(a)
Output:
bytearray(b’\x01\x03\x04\x05′)
bytearray(b’\x01\x03\x02\x05′)
PYTHON RANGE() OBJECTS
⦿ range() is a built-in function in Python that returns
us a range object.
⦿ The range object is nothing but a sequence of
integers.
⦿ It generates the integers within the specified start
and stop range.
Code:
for i in range(5):
print(i)
Output:
0
1
2
3
4
STRINGS OPERATOR
1. Concatenation
◼The operator (+) is used to concatenate
the second element to the first.
◼For example – [1,3,4] + [1,1,1] will
evaluate to [1,3,4,1,1,1].
◼We can concate all other sequences like
this.
2. Repeat
◼The operator (*) is used to repeat a
sequence n number of times.
◼For example – (1,2,3) * 3 will evaluate to
(1,2,3,1,2,3,1,2,3).
3. Membership Operators
◼Membership operators (in) and (not in) are
used to check whether an item is present
in the sequence or not.
◼They return True or False.
◼For example – ‘la’ in “Manilla” evaluates to
True and ‘a’ not in ‘all’ evaluates to False.
4. Slicing Operator
◼All the sequences in Python can be sliced.
◼The slicing operator can take out a part of
a sequence from the sequence.
print( "The new york times"[4:10] )
‘new yo’
STRINGS BUILT IN FUNCTION
1. len()
◼ The len() function is very handy when you want to
know the length of the sequence.
◼ Code:
len(“This is a sentence”)
◼ Output:
18
2. min() and max()
◼The min() and max() functions are used to get the
minimum value and the maximum value from
the sequences respectively.
◼Code:
print(min([5,3,2,1]))
print(max([5,3,2,1]))
◼Output:
1
5
3. index()
◼ The index() method searches an element in
the sequence and returns the index of the first
occurrence.
◼ Code:
“Hahaha”.index(“a”)
◼ Output:
1
4. count()
◼ The count() method counts the number of
times an element has occurred in the
sequence.
◼ Code:
“Hahaha”.count(“a”)
◼ Output:
3
STRING OTHER BUILT IN FUNCTIONS
Method Description
center() Returns a centered string
islower() Returns True if all characters in the string are
lower case
isnumeric() Returns True if all characters in the string are
numeric
isdecimal() Returns True if all characters in the string are
decimals
isdigit() Returns True if all characters in the string are
digits
isidentifier() Returns True if the string is an identifier
capitalize() Converts the first character to upper case
LIST
⦿ Lists are used to store multiple items in a
single variable.
⦿ Lists are created using square brackets:
⦿ Example
thislist = ["apple", "banana", "cherry"]
print(thislist)
⦿ Output
['apple', 'banana', 'cherry']
List Items
⦿ List items are ordered, changeable, and allow
duplicate values.
⦿ List items are indexed, the first item has
index [0], the second item has index [1] etc.
⦿ Ordered
◼When we say that lists are ordered, it
means that the items have a defined
order, and that order will not change.
◼If you add new items to a list, the new
items will be placed at the end of the list.
⦿ Changeable
◼The list is changeable, meaning that we
can change, add, and remove items in a
list after it has been created.
⦿ Allow Duplicates
◼ lists are indexed, lists can have items
with the same value
LIST TYPE BUILT IN METHODS
⦿ List Length
◼ To determine how many items a list has, use
the len() function
◼ Code
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
◼ Output
3
⦿ List Items - Data Types
◼ A list can contain different data types
◼ Code
list1 = ["abc", 34, True, 40, "male"]
print(list1)
◼ Output
['abc', 34, True, 40, 'male']
SORT LISTS
⦿ Ascending Order
⦿ List objects have a sort() method that will
sort the list alphanumerically, ascending, by
default
⦿ Code
thislist = ["orange", "mango", "kiwi",
"pineapple",
"banana"]
[Link]()
print(thislist)
⦿ Output
['banana', 'kiwi', 'mango', 'orange',
'pineapple']
SORT LISTS
⦿ Descending order
⦿ To sort descending, use the keyword
argument reverse = True
⦿ Code
thislist = ["orange", "mango", "kiwi",
"pineapple",
"banana"]
[Link](reverse = True)
print(thislist)
⦿ Output
['pineapple', 'orange', 'mango', 'kiwi',
'banana']
JOIN LIST
⦿ There are several ways to join, or
concatenate, two or more lists in
Python.
⦿ One of the easiest ways are by using
the + operator.
⦿ Code
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
⦿ Output
['a', 'b', 'c', 1, 2, 3]
TUPLES
⦿ Tuples are used to store multiple items in a single
variable.
⦿ A tuple is a collection which is ordered
and unchangeable.
⦿ Tuples are written with round brackets
⦿ Code
thistuple = ("apple", "banana", "cherry")
print(thistuple)
⦿ Output
('apple', 'banana', 'cherry')
⦿ Tuple Items
⦿ Tuple items are ordered, unchangeable, and allow
duplicate values.
⦿ Tuple items are indexed, the first item has
index [0], the second item has index [1] etc.
⦿ Ordered
◼When we say that tuple are ordered, it
means that the items have a defined
order, and that order will not change.
◼If you add new items to a tuple, the new
items will be placed at the end of the
tuple.
⦿ Unchangeable
◼The tuple is unchangeable, meaning that
we cannot change, add, and remove
items in a tuple after it has been created.
⦿ Allow Duplicates
◼tuple are indexed, tuples can have items
with the same value
TUPLES BUILT IN FUNCTIONS
⦿ Access Tuple Items
⦿ You can access tuple items by referring
to the index number, inside square
brackets
⦿ Code
thistuple = ("apple", "banana",
"cherry")
print(thistuple[1])
⦿ Output
banana
TUPLES BUILT IN FUNCTIONS
⦿ Change Tuple Values
⦿ Once a tuple is created, you cannot change its
values.
⦿ Tuples are unchangeable, or immutable as it also
is called
⦿ Code
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
⦿ Output
("apple", "kiwi", "cherry")
TUPLES BUILT IN FUNCTIONS
⦿ Add Items
⦿ Since tuples are immutable, they do not
have a build-in append() method, but
there are other ways to add items to a
tuple.
? 1. Convert into a list
? 2. Add tuple to a tuple
1. CONVERT INTO A LIST
⦿ you can convert it into a list, add your item(s),
and convert it back into a tuple.
⦿ Code
thistuple=("apple", "banana",
"cherry")
y = list(thistuple)
[Link]("orange")
thistuple = tuple(y)
print(thistuple)
⦿ Output
('apple', 'banana', 'cherry',
'orange')
2. ADD TUPLE TO A TUPLE
⦿ You are allowed to add tuples to tuples, so if
you want to add one item, (or many),
create a new tuple with the item(s), and
add it to the existing tuple
⦿ Code
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
⦿ Output
('apple', 'banana', 'cherry', 'orange')
⦿ Remove Items
⦿ Tuples are unchangeable, so you cannot
remove items from it, but you can use
the same workaround as we used for
changing and adding tuple items
⦿ Code
thistuple = ("apple", "banana",
"cherry")
y = list(thistuple)
[Link]("apple")
thistuple = tuple(y)
print(thistuple)
⦿ Output
('banana', 'cherry')
⦿ Join Tuples
⦿ To join two or more tuples you can use the + operator
⦿ Code
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
⦿ Output
('a', 'b', 'c', 1, 2, 3)
⦿ Multiply Tuples
⦿ If you want to multiply the content of a tuple a given
number of times, you can use the * operator
⦿ Code
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
⦿ Output
('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')
THANK YOU