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

L4-L5. Element of Python

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

L4-L5. Element of Python

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Manipal University, Jaipur

Object Oriented Programming


(AI2104)

Lecture 4-5

Elements of Python
Dr. Yadvendra Pratap Singh
Course Details Asst. Professor(SS)
(B. Tech. III Sem) CSE

Object Oriented Programming Unit I


1
12/03/2024
Topic Objective

The students will study the elements of Python like Keywords and
Identifiers, Variables, Data types and Operators, Comments.

Object Oriented Programming Unit I


03/12/2024 2
Elements of Python (CO1)

• Keywords and Identifiers


• Variables
• Data types and type conversion
• Operators in Python
• Expressions in Python
• Comments

03/12/2024 Object Oriented Programming Unit I 3


Keywords (CO1)

• Keywords are the reserved words in Python.


• 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.
• In Python, keywords are case sensitive.
• All the keywords except True, False and None are in lowercase, and
they must be written as they are.
• Example
• and, as, assert, await, async, break, class, continue, def, del, elif, else,
except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or,
pass, raise, return, try, while, with, yield, True, False, None

03/12/2024 Object Oriented Programming Unit I 4


Identifiers (CO1)

An identifier is a name given to entities like class, functions,


variables, etc. It helps to differentiate one entity from another.

03/12/2024 Object Oriented Programming Unit I 5


Rules for writing Identifiers (CO1)

• Identifiers can be a combination of letters in lowercase (a to z) or


uppercase (A to Z) or digits (0 to 9) or an underscore _.

• An identifier cannot start with a digit.

• Keywords cannot be used as identifiers.

• Cannot use special symbols like !, @, #, $, % etc. in identifier.

• An identifier can be of any length.

03/12/2024 Object Oriented Programming Unit I 6


Variables (CO1)

• A variable is a location in memory used to store some data (value).

• Unique names are given to them to differentiate between different


memory locations.

• No need to declare a variable before using it. The declaration


happens automatically when a value is assigned to a variable.

• The Assignment operator (=) is used to assign values to variables.

03/12/2024 Object Oriented Programming Unit I 7


Variables (CO1)

• The operand to the left of the = operator is the name of the


variable and the operand to the right of the = operator is the value
stored in the variable.
• For example
>>> num = 347 # An integer assignment
>>> x = 45.89 # A floating point
>>> name = “Aman" # A string

03/12/2024 Object Oriented Programming Unit I 8


Multiple Assignment in Variables (CO1)

• A single value may be assigned to several variables simultaneously.


• For example
>>> a = b = c = 1
• Here, an integer object is created with the value 1, and all three
variables are assigned to the same memory location.
• It also allows to assign multiple objects to multiple variables.
• For example −
>>> a, b, c = 23, 29.45, “Ram”
• Here, one integer objects with value 23, one float object with value
29.45 are assigned to variables a and b respectively, and one string
object with the value “Ram" is assigned to the variable c.

03/12/2024 Object Oriented Programming Unit I 9


Data types (CO1)

• Every value in Python has a datatype, that are used to define the
operations possible on them and the storage method for each of
them.
• Since everything is an object in Python programming, data types are
classes and variables are instance (object) of these classes.

03/12/2024 Object Oriented Programming Unit I 10


Standard Data types (CO1)
Types of Data class Name Examples
Types (datatype name)
Text Type str ‘Hello Students’ , “Hello Students”
‘‘‘Hello Students’’’, “““Hello Students””
Numeric Types int, float, complex 23, 45.78, (4+7j)
Sequence Types list, tuple, range [2, 6.8, ‘Hi’], (21, 45, 7.8, ‘abc’),
range(1,10,2)
Mapping Type dict {‘name’: ‘Amit’, ‘Salary’: 20000}
Set Types set {2,5,1,6,8,9}
Boolean Types bool True, False
Binary Types bytes b‘\x00\x00’

03/12/2024 Object Oriented Programming Unit I 11


Literals in Python(CO1)

• literals are a notation for representing a fixed value in source code.


They can also be defined as raw value or data given in variables or
constants.
• Python has different types of literals.
• Numeric literals
• String literals
• Boolean literals
• Literal Collections
• Special literals

03/12/2024 Object Oriented Programming Unit I 12


Numbers (CO1)

• Numbers represent numeric values. Number objects are created when a value
is assigned to them. For ex:
>>> var1 = 1
>>> var2 = 10
• The reference to a number object can be deleted by using the del statement.
The syntax of the del statement is
>>> del var # Deletes variable var
>>> del var1,var2,var3 # Deletes the variables var1, var2, var3
• A single object or multiple objects can be deleted by using the del statement.
For example
>>> del var
>>> del var_a, var_b
03/12/2024 Object Oriented Programming Unit I 13
Types of Number Literals(CO1)

1. int (signed integers)

2. float (floating point real values)

3. complex (complex numbers)

03/12/2024 Object Oriented Programming Unit I 14


Examples of Number Literals (CO1)

int float complex


10 0.6 (2 + 7j)
-457 15.20 (45.3j)
0b1101 -21.9 (-4 - 6j)
0o60 32.3e+18 (.876j)
-0o450 -90.6 (-.6545 + 0j)
0x260 -32.54E100 (3e+26j)

03/12/2024 Object Oriented Programming Unit I 15


Strings (CO1)

• Strings in Python are the sequence of characters stored in


contiguous memory locations and represented in the quotation
marks.

• Python allows for either pairs of single(‘ ’), double quotes(“ ”) or


triple quotes(‘‘‘ ’’’ or “““ ”””).

• Declaration python string object


>>> mystr = “Hello Students”

03/12/2024 Object Oriented Programming Unit I 16


Indexing of String Object (CO1)

• Indexing allows to access the individual element of the string object.


• Elements of string object can be accessed by specifying the index of
the element inside pair of square bracket.
>>> mystr[4] # ‘o’ is the element
>>> mystr[-7] # ‘t’ is the element
Positive Indexing
0 1 2 3 4 5 6 7 8 9 10 11 12 13
H e l l o S t u d e n t s
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

03/12/2024 Object Oriented Programming Unit I


Negative Indexing17
Slicing of strings object (CO1)
• Slicing of the string object is the subset of it.
• Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes
starting at 0 in the beginning of the string and working their way from +1 till the
end.
>>> mystr = “Hello Students”
>>> mystr[3:9] # index range is 3,4,5,6,7,8 and subset is ‘lo Stu’
>>> mystr[-12:-6] # index range is -12,-11,-10,-9,-8,-7 and subset is ‘llo St’
>>> mystr[:9] # index range is 0,1,2,3,4,5,6,7,8 and subset is ‘Hello Stu’
>>> mystr[3:] # index range is 3,4,5,6,7,8,9,10,11,12,13 and subset is ‘lo Students’
>>> mystr[:] #index range is 0 to 13 and subset is ‘Hello Students’

03/12/2024 Object Oriented Programming Unit I 18


Concatenation of strings object (CO1)

• The plus (+) sign is the string concatenation operator


>>> s1 = “Hello”
>>> s2 = “Students”
>>> s3 = s1 + s2 # s3 is the concatenation of s1 and s2
>>> s3
“HelloStudents”

[Note: s1 and s2 remain same after concatenation. s1 + s2 creates


another string object.]

03/12/2024 Object Oriented Programming Unit I 19


Appending of strings object (CO1)

• Appending is the joining the another string object on the end of first
string object.
>>> s1 = “Hello”
>>> s2 = “Students”
>>> s1 = s1 + s2
>>> s1
“HelloStudents”
[Note: New memory location is created for s1 after appending with s2.]

03/12/2024 Object Oriented Programming Unit I 20


Multiplication of string object with integer object (CO1)

• The plus (*) sign is the multiplication operator.


>>> s1 = “Hello”
>>> print(s1*4)
“HelloHelloHelloHello”
>>> print(4*s1)
“HelloHelloHelloHello”

03/12/2024 Object Oriented Programming Unit I 21


Strings (CO1)

• For example
>>> str = ‘Hello World!’
>>> print(str) # Prints complete string
>>> print(str[0]) # Prints first character of the string
>>> print(str[2:5]) # Prints characters starting from 3rd to 5th
>>> print(str[2:]) # Prints string starting from 3rd character
>>> print(str * 2) # Prints string two times
>>> print(str + ‘TEST’) # Prints concatenated string

03/12/2024 Object Oriented Programming Unit I 22


Slicing Strings (CO1)

Slicing
• A range of characters can be returned by using the slice syntax.
• Specify the start index and the end index, separated by a colon, to
return a part of the string.
Example
Get the characters from position 2 to position 5 (not included):
Program
b = "Hello, World!"
print(b[2:5])
Program Output
llo
03/12/2024 Object Oriented Programming Unit I 23
Program to demonstrate slicing of Strings (CO1)

# String slicing
String ='ASTRING'
# Using slice constructor
s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
03/12/2024 Object Oriented Programming Unit I 24
Output of slicing of Strings (CO1)

Output:
String slicing
AST
SR
GITA

03/12/2024 Object Oriented Programming Unit I 25


Boolean literals(CO1)

There are only two Boolean literals in Python.


They are True and False.
Example:
a = (1 == True)
b = (1 == False)
c = True + 3
d = False + 7

print("a is", a)
print("b is", b)
print("c:", c)
print("d:", d)

03/12/2024 Object Oriented Programming Unit I 26


Literal Collections(CO1)

• There are four different types of literal collections


• List literals
• Tuple literals
• Dict literals
• Set literals

03/12/2024 Object Oriented Programming Unit I 27


List literals (CO1)

• List contains items of different data types.


• The values stored in List are separated by comma (,) and enclosed
within square brackets([]).
• We can store different types of data in a List.
• # List literals (Example)
number = [1, 2, 3, 4, 5]
name = ['Amit', 'kabir', 'bhaskar', 2]
print(number)
print(name)

03/12/2024 Object Oriented Programming Unit I 28


Tuple literals(CO1)

• A tuple is a collection of different data-type.


• It is enclosed by the parentheses ‘()‘ and each element is separated
by the comma(,).
# Tuple literals(Example)
even_number = (2, 4, 6, 8)
odd_number = (1, 3, 5, 7)

print(even_number)
print(odd_number)

03/12/2024 Object Oriented Programming Unit I 29


Dictionary literals(CO1)

• Dictionary stores the data in the key-value pair.


• It is enclosed by curly-braces ‘{}‘ and each pair is separated by the
commas(,).
• We can store different types of data in a dictionary.
# Dict literals(Example)
alphabets = {'a': 'apple', 'b': 'ball', 'c': 'cat’}
information = {'name': 'amit', 'age': 20, 'ID': 20}

print(alphabets)
print(information)

03/12/2024 Object Oriented Programming Unit I 30


Set literals(CO1)

• Set is the collection of the unordered data set.


• It is enclosed by the {} and each element is separated by the
comma(,).
• # Set literals
vowels = {'a', 'e', 'i', 'o', 'u’}
fruits = {"apple", "banana", "cherry"}

print(vowels)
print(fruits)

03/12/2024 Object Oriented Programming Unit I 31


Set literals(CO1)

• Set is the collection of the unordered data set.


• It is enclosed by the {} and each element is separated by the
comma(,).
• # Set literals
vowels = {'a', 'e', 'i', 'o', 'u’}
fruits = {"apple", "banana", "cherry"}

print(vowels)
print(fruits)

03/12/2024 Object Oriented Programming Unit I 32


Special literals(CO1)

• Python contains one special literal (None).


• ‘None’ is used to define a null variable.
• If ‘None’ is compared with anything else other than
a ‘None’, it will return false.
• # Special literals
water_remain = None
print(water_remain)

03/12/2024 Object Oriented Programming Unit I 33


Type conversion (CO1)

• The process of converting the value of one data type (integer, string,
float, etc.) to another data type is called type conversion.
• Python has two types of type conversion.
• Implicit Type Conversion
• Explicit Type Conversion

03/12/2024 Object Oriented Programming Unit I 34


Implicit Type conversion (CO1)

• Python automatically converts one data type to another data type


without any user involvement.
• It always converts smaller data types to larger data types to avoid
the loss of data.
• Example
>>> a = 4
>>> b = 2.3
>>> c = a + b
• In above example, data type of a and b are int and float,
respectively. Data type of c will be float and its value is 6.3

03/12/2024 Object Oriented Programming Unit I 35


Explicit Type conversion (CO1)

• In Explicit Type Conversion, users convert the data type of an object


to required data type.
• The predefined functions like int(), float(), str() are used to perform
explicit type conversion.
• This type of conversion is also called typecasting because the user
casts/changes the data type of the objects.
• Syntax
<datatype>(expression)
• Example
>>> a = 2.6
>>> c = int(a)

03/12/2024 Object Oriented Programming Unit I 36


Function of type conversion (CO1)
Function Description
int(x) Convert x to an integer
float(x) Convert x to a float number
str(x) Convert x to a string
tuple(x) Convert x to a tuple
list(x) Convert x to a list
set(x) Convert x to a set
ord(x) Convert x to ASCII code
bin(x) Convert x to a binary
oct(x) Convert x to an octal
hex(x) Convert x to a hexadecimal
chr(x) Convert x to a character

03/12/2024 Object Oriented Programming Unit I 37


Operators in Python (CO1)

• Operator is the symbol that specifies the type of operation


between the operands.
• Example: Arithmetic, relational and arithmetic operator.
• Expression is the valid sequence of operators and operators that
evaluates to single value.

03/12/2024 Object Oriented Programming Unit I 38


Operators in Python (CO1)

• Types of operators in Python


• Arithmetic Operators (+,-,*,/,//,%,**)
• Relational Operators (<, >, <=,>=,==,!=)
• Logical Operators (and, or , not)
• Bitwise Operators (&, |, ^, ~,<<,>>)
• Assignment Operators (=)
• Membership Operators (in, not in)
• Identity Operators (is, is not)

03/12/2024 Object Oriented Programming Unit I 39


Arithmetic Operators (CO1)
Operator Description Example
(a=5, b=3)
+ Adds values on either side of the operator. a+b=8

- Subtracts right hand operand from left hand operand. a–b=2

* Multiplies values on either side of the operator a * b = 15

/ Divides left hand operand by right hand operand (may be a/b=


precise upto 15 digits of decimal places) 1.6667
% Divides left hand operand by right hand operand and provide a % b = 2
remainder.
** Performs exponential (power) calculation on operators a**b =5 3
=
125
// The division of operands where the result is the quotient in a//b=1
which the digits after the decimal point are removed.

03/12/2024 Object Oriented Programming Unit I 40


Floor Division Operator(//) (CO1)

a//b = floor(a/b)
• When a and b are of same sign. Quotient is of +ve sign
• Example:
12/5 = -12/-5 = 2.4
12//5 = -12//-5 = floor(2.4) = 2
• When a and b are of opposite sign. Quotient is of -ve sign
• Example:
12/(-5) = (-12)/5 = -2.4
12//(-5) = (-12)//5 = floor(-2.4) = -3

03/12/2024 Object Oriented Programming Unit I 41


Modulus Operator(%) (CO1)

a%b = a – b*floor(a/b)
• When a and b are of same sign.
• Example:
12%5 = 12 - 5*floor(12/5) = 12 – 5*2 = 2
-12%-5 = -12 – (-5)*floor(-12/-5)=-12-(-5)*(2) = -2
• When a and b are of opposite sign.
• Example:
12%(-5) = 12 –(-5)*floor(12/(-5)) = 12-(-5)*(-3) = -3
-12%5 = -12 – 5*floor(-12/5) = -12-5*(-3) = 3

03/12/2024 Object Oriented Programming Unit I 42


Relational Operators (CO1)

• Relational operators are used to compare two arithmetic


expression.
• It evaluates to either True or False.
• Example : <, >, <=, >=, ==, !=

03/12/2024 Object Oriented Programming Unit I 43


Relational Operators (CO1)
Example
Operator Description
a=5, b=3
If the values of two operands are equal, then the a == b is not
==
condition becomes true true.
If values of two operands are not equal, then condition a!=b is true
!=
becomes true.
If the value of left operand is greater than the value of a > b is true
>
right operand, then condition becomes true.
If the value of left operand is less than the value of right a < b is not true
<
operand, then condition becomes true.
a >= b is true
If the value of left operand is greater than or equal to the
>=
value of right operand, then condition becomes true.
If the value of left operand is less than or equal to the a <= b is not true
<=
value of right operand, then condition becomes true.
03/12/2024 Object Oriented Programming Unit I 44
Logical Operators (CO1)

• Logical operators are used to combine two or more relational expression.


• It evaluates to True or False when combining relational expression.
• When arithmetic expression are combined, then it evaluates to numeric
values.
• Logical operators are the and, or, not operators.

Operator Description

and True if both the operands are true

or True if either of the operands is true

not True if operand is false (complements the operand)


03/12/2024 Object Oriented Programming Unit I 45
Logical Operators (CO1)

a b a and b a or b not a

True True True True False

True False False True False

False True False True True

False False False False True

03/12/2024 Object Oriented Programming Unit I 46


Bitwise Operators (CO1)

• Bitwise operators manipulate the data at bit level.


• These are applicable on integer values.
• Types
 & (Bitwise and operator)
 | (Bitwise or operator)
 ^ (Bitwise XOR operator)
 ~ (Bitwise one’s complement operator)
 << (Bitwise left-shift operator)
 >> (Bitwise right-shift operator)

03/12/2024 Object Oriented Programming Unit I 47


Bitwise Operators (CO1)

a b a&b a|b a^b ~a

0 0 0 0 0 1

0 1 0 1 1 1

1 0 0 1 1 0

1 1 1 1 0 0

03/12/2024 Object Oriented Programming Unit I 48


Bitwise Operators (CO1)

Operator Let a = (92)10 =(0101 1100)2 and b = (14)10 = (0000 1110)2


0101 1100
& 0000 1110
& c = (a & b) = 92 & 14 --------------------
0000 1100 = (12)10
0101 1100
| 0000 1110
I c = (a | b) = 92 | 14 --------------------
0101 1110 = (94)10
0101 1100
^ 0000 1110
^ c = (a ^ b) = 92 ^ 14 --------------------
0101 0010 = (82)10

03/12/2024 Object Oriented Programming Unit I 49


Bitwise Operators (CO1)

Let a = (92)10 =(0101 1100)2 and b = (14)10 = (0000 1110)2


Operator

~ c = ~a = ~92 c = ~(0101 1100) = 1010 0011


(~n = -(n+1))

<< c = a << 1 = 46 << 1 C = 00101 110 << 1 = 01011100 = (92)10

>> c = a >> 2 = 92 >> 2 C = 0101 1100 >> 2 = 0001 0111 = (23)10

03/12/2024 Object Oriented Programming Unit I 50


Assignment Operators (CO1)

Operator Syntax Description


Assigns values from right side operands(b) to left
= a=b
side operand (a)
It adds right operand to the left operand and
+= a += b is same as a = a + b
assign the result to left operand
It subtracts right operand from the left operand
-= a -= b is same as a = a - b
and assign the result to left operand
It multiplies right operand with the left operand
*= a *= b is same as a = a * b
and assign the result to left operand
It divides left operand with the right operand
/= a /= b is same as a = a / b
and assign the result to left operand

03/12/2024 Object Oriented Programming Unit I 51


Assignment Operators (CO1)

Operator Syntax Description

%= It takes modulus using two operands


a %= b is same as a = a % b and assign the result to left operand

Performs exponential (power)


**= a **= b is same as a = a ** b calculation on operators and assign
value to the left operand

It performs floor division on operators


//= a //= b is same as a = a //b and assign value to the left operand

03/12/2024 Object Oriented Programming Unit I 52


Membership Operators (CO1)

• in and not in are the membership operators in Python.


• They are used to test whether a value or variable is found in a
sequence (string, list, tuple, set and dictionary).
• In a dictionary, we can only test for presence of key, not the value.

Operator Description Example Result


x = {2,3,5}
in True if value/variable is found in the sequence 5 in x True

not in True if value/variable is not found in the 5 not in x False


sequence

03/12/2024 Object Oriented Programming Unit I 53


Identity Operators (CO1)

• Identity operators compare the memory locations of two objects.


• is and is not are the identity operators in Python.
• They are used to check if two values (or variables) are located on
the same part of the memory.
• Two variables that are equal does not imply that they are identical.
Example
Operator Description a = ‘Hello’ Result
b = ‘Hello’
True if the operands are identical (refer to the
is same object) a is b True

is not True if the operands are not identical (do not a is not b False
refer to the same object)

03/12/2024 Object Oriented Programming Unit I 54


Operator Precedence and associativity(CO1)

• When an expression contains two or more than two operators, then


it is evaluated based on operator precedence and associativity.
• Each operator of same precedence is grouped in same level and
operator of higher precedence is evaluated first.
• Two or more operators having equal precedence are evaluated
either left-to-right(LTR) or right-to-left(RTL) based on their
associativity.

03/12/2024 Object Oriented Programming Unit I 55


Operator Precedence and associativity(CO1)
Operator Description Associativity Rules
() Parenthesis Left-to-right
** Exponentiation Right-to-left
~,+,- Unary operators Right-to-left
*,/,//,% Arithmetic multiply, division, floor and Left-to-right
modulo division
+, - Addition and subtraction Left-to-right
>>,<< Bitwise left and right shift operator Left-to-right
& Bitwise and operator Left-to-right
^ Bitwise Ex-or operator Left-to-right
| Bitwise or operator Left-to-right

03/12/2024 Object Oriented Programming Unit I 56


Operator Precedence and associativity(CO1)
Operator Description Associativity Rules
<=,>=,<,> Relational inequality operators Left-to-right
==, != Equal and not equal operators Left-to-right
is, is not Identity operators Left-to-right
in, not in Membership operators Left-to-right
not Logical not operator Right-to-left
and Logical and operator Left-to-right
or Logical or operator Left-to-right
=,*=,/=,//=, Assignment operators Right-to-left
%=,+=,-
=,**=,&=

03/12/2024 Object Oriented Programming Unit I 57


Expressions in Python (CO1)

• Expressions are representations of value.


• It is the valid sequence of operands and operators that evaluates to
single value.
• Python expression contains identifiers, literals, and operators.
• They are different from statement in the fact that statements are
the instructions executed by the Python interpreter while
expressions are representation of value.
• For Example
a*b + c/d –f is an expression.
x = a*b + c/d –f is the statement.

03/12/2024 Object Oriented Programming Unit I 58


Expressions in Python (CO1)

• Expressions can be of two types


• Arithmetic Expression
• Boolean Expression
• Expressions which generates a number type result are termed as
arithmetic expressions.
• A=B+C*D/E
• W=X**Y % Z
• Expressions which generates either True or False result are termed
as Boolean expressions.
• p=x==y
• q=(a<b) and (c<d)

03/12/2024 Object Oriented Programming Unit I 59


print() function in Python (CO1)

• The print() function prints the specified message to the screen, or


other standard output device.
• The message can be a string, or any other object, the object will be
converted into a string before written to the screen.
• print() is a built-in function, which means that you don’t need to
import it from anywhere.
• Syntax:
print(object(s), sep=separator, end=end, file=file, flush=flush)

03/12/2024 Object Oriented Programming Unit I 60


print() function in Python (CO1)
Parameter Description
object(s) Any object, and as many as you like. Will be converted to string
before printing
sep='separator' Optional. Specify how to separate the objects, if there is more
than one. Default is ‘ '

end='end' Optional. Specify what to print at the end. Default is '\n' (line
feed)
file Optional. An object with a write method. Default is sys.stdout

flush Optional. A Boolean, specifying if the output is flushed (True)


or buffered (False). Default is False

03/12/2024 Object Oriented Programming Unit I 61


Comments in Python (CO1)

• Comments are non-executable part of the program.


• These are documentation of program.
• They are used to describe the meaning of source code.
• Types of comments
• Single line comment (Statement prefixed with #)
• Multiline comments (Statements enclose within ‘‘‘’’’ or “““”””)

03/12/2024 Object Oriented Programming Unit I 62


Thank you.

You might also like