Unit - 2 CAP.pptx

COMPUTING APPLICATIONS WITH PYTHON
UNIT – II
Operators and expressions
Operators:
The operator can be defined as a symbol which is responsible for a particular operation between two
operands. Operators are the pillars of a program on which the logic is built in a specific programming
language. Python provides a variety of operators, which are described as follows.
• Arithmetic operators
• Comparison operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
1. Arithmetic Operators:
Assume variable a holds 10 and variable b holds 20, then:
2. Comparison Operators:
3. Assignment Operators:
Unit - 2 CAP.pptx
4. Bitwise Operators:
Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13; Now In binary format they
will be as follows:
1. Compliment operator
2. And (&)
3. Or (|)
4. Xor (^)
Unit - 2 CAP.pptx
5. Logical Operators:
6. Membership Operators:
In addition to the operators discussed previously, Python has membership operators, which test for membership in a
sequence, such as string s, lists, or tuples. There are two membership operators explained below:
7. Identity Operators:
Identity operators compare the memory locations of two objects. There are two Identity operators explained below:
Expressions
• An expression is a combination of operators and operands that is interpreted to produce some other value.
• An expression is evaluated as per the precedence of its operators. So that if there is more than one operator
in an expression, their precedence decides which operation will be performed first.
1. Constant Expressions: These are the expressions that have constant values only.
example: x = 15 + 1.3
print(x)
output: 16.3
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators, and
sometimes parenthesis. The result of this type of expression is also a numeric value. The operators used in
these expressions are arithmetic operators like addition, subtraction, etc. Here are some arithmetic operators in
Python:
Example: Arithmetic Expressions
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
3. Integral Expressions: These are the kind of expressions that produce only integer results after all
computations and type conversions.
Example:
a = 13
b = 12.0
c = a + int(b)
print(c)
Output: 25
4. Floating Expressions: These are the kind of expressions which produce floating point numbers as result
after all computations and type conversions.
Example:
a = 13
b = 5
c = a / b
print(c)
Output: 2.6
5. Relational Expressions: In these types of expressions, arithmetic expressions are written on both sides of
relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated first, and then compared as per
relational operator and produce a Boolean output in the end. These expressions are also called Boolean
expressions.
Example :
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output: True
6. Logical Expressions: These are kinds of expressions that result in either True or False. It basically specifies
one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it is not correct, so
it will return False. Studying logical expressions, we also come across some logical operators which can be
seen in logical expressions most often. Here are some logical operators in Python:
Example:
P = (10 == 9)
Q = (7 > 5)
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)
7. Bitwise Expressions: These are the kind of expressions in which computations are performed at bit level.
Example:
a = 12
x = a >> 2
y = a << 1
print(x, y)
8. Combinational Expressions: We can also use different types of expressions in a single expression, and
that will be termed as combinational expressions.
Example:
a = 16
b = 12
c = a + (b >> 1)
print(c)
Multiple operators in expression (Operator Precedence)
Operator Precedence simply defines the priority of operators that which operator is to be executed first. Here
we see the operator precedence in Python, where the operator higher in the list has more precedence or
priority:
Unit - 2 CAP.pptx
# Multi-operator expression (operator precedence).
Examples:
a = 10 + 3 * 4 =
print(a)
b = (10 + 3) * 4
print(b)
c = 10 + (3 * 4)
print(c)
Control Flow:-
If Statement:
• Here, the program evaluates the test expression and will execute statement(s) only if the text expression is True.
• If the text expression is False, the statement(s) is not executed.
• In Python, the body of the if statement is indicated by the indentation. Body starts with an indentation and the
first un-indented line marks the end.
• Python interprets non-zero values as True. None and 0 are interpreted as False.
Example: Python if Statement
# If the number is positive, we print an appropriate message
num = 3 -----------
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
Output:
3 is a positive number.
This is always printed.
If-else Statement
• The if-else statement evaluates test expression and will execute
body of if only when test condition is True.
• If the condition is False, body of else is executed. Indentation is
used to separate the blocks.
Example of if...else
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
if num >= 0:
print("Positive Number")
else:
print("Negative number")
Output:
Positive Number
• In the above example, when num is equal to 3, the test expression is true and body of if is executed and body of
else is skipped.
• If num is equal to -5, the test expression is false and body of else is executed and body of if is skipped.
• If num is equal to 0, the test expression is true and body of if is executed and body of else is skipped.
Python if- elif -else Statement
• The elif is short for else if. It allows us to check for multiple expressions.
• If the condition for if is False, it checks the condition of the next elif block
and so on.
• If all the conditions are False, body of else is executed.
• Only one block among the several if...elif...else blocks is executed
according to the condition.
• The if block can have only one else block. But it can have multiple elif
blocks.
Example of if...elif...else
# In this program,
# we check if the number is positive or
# negative or zero and
# display an appropriate message
num = -3
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Output:
Positive number
When variable num is positive, Positive number is printed.
If num is equal to 0, Zero is printed.
If num is negative, Negative number is printed
Looping in Python:
For Loop:
The for loop in Python is used to iterate over a sequence (list,
tuple, string) or other iterable objects. Iterating over a
sequence is called traversal.
• Here, val is the variable that takes the value of the item
inside the sequence on each iteration.
• Loop continues until we reach the last item in the sequence.
The body of for loop is separated from the rest of the code
using indentation.
Example: Python for Loop
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)
Output:
The sum is 48
while loop:
• The while loop in Python is used to iterate over a block of code as long as the
test expression (condition) is true.
• We generally use this loop when we don't know beforehand, the number of
times to iterate.
• In while loop, test expression is checked first. The body of the loop is entered
only if the test-expression evaluates to True. After one iteration, the test
expression is checked again.
• This process continues until the test-expression evaluates to False. In Python,
the body of the while loop is determined through indentation.
• Body starts with indentation and the first unindented line marks the end.
• Python interprets any non-zero value as True. None and 0 are interpreted as
False.
Example: Python while Loop
# Program to add natural numbers
# sum = 1+2+3+...+n
n = 10
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
Output:
Enter n: 10
The sum is 55
Python break statement:
• The break statement terminates the loop containing it. Control of the
program flows to the statement immediately after the body of the
loop.
• If break statement is inside a nested loop (loop inside another loop),
break will terminate the innermost loop.
Syntax of break:
Break
The working of break statement in for loop and while loop is shown
below.
The working of break statement in for loop and while loop is shown
below:
Example:
# Use of break statement inside loop
for val in "string":
if val == “i":
break
print(val)
print("The end")
Output:
s
t
r
The end
Python continue statement:
The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not
terminate but continues on with the next iteration.
Syntax of Continue:
continue
The working of continue statement in for and while loop is shown below.
Example:
# Program to show the use of continue statement inside loops
for val in "string":
if val == "i":
continue
print(val)
print("The end")
Output:
s
t
r
n
g
The end
pass statement:
In Python programming, pass is a null statement. The difference between a comment and pass statement in Python is
that, while the interpreter ignores a comment entirely, pass is not ignored.
However, nothing happens when pass is executed. It results into no operation (NOP).
Syntax of pass:
pass
Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They
cannot have an empty body. The interpreter would complain. So, we use the pass statement to construct a body that
does nothing.
Example:
# pass is just a placeholder for
# functionality to be added later.
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass
We can do the same thing in an empty function or class as well:
Data Structures:
• Data structure is a method of organizing large amount of data more efficiently so that any operation on that data
becomes easy.
• Python language supports 4 types of data structures. They are:
1. Lists.
2. Tuples.
3. Sets.
4. Dictionary.
Lists:
• A list is similar to an array that consists of a group of elements or items. Just like an array, a list can store elements.
• But, there is one major difference between an array and a list. An array can store only one type of elements
whereas a list can store different types of elements. Hence lists are more flexible and useful than an array.
Creating a List:
Creating a list is as simple as putting different comma-separated values between square brackets.
list=[ ]
We can create empty list without any elements by simply writing empty square brackets as
We can create a list by embedding the elements inside a pair of square braces [ ]. The elements in the list should be
separated by a comma (,).
Accessing Values in list: print list[1:3]
Creating list using range () function:
We can use range () function to generate a sequence of integers which can be stored in a list. To store numbers from 0
to 10 in a list as follows.
To store even numbers from 0 to 10 in a list as follows.
Looping on lists:
We can also display list by using for loop (or) while loop. The len () function useful to know the number of elements in
the list. While loop retrieves starting from 0th to the last element i.e. n-1.
Updating and deleting lists:
• Lists are mutable. It means we can modify the contents of a list. We can append, update or delete the elements of a
list depending upon our requirements.
• Appending elements means adding an element at the end of the list. To, append a new element to the list, we should
use the append() method.
Updating an element means changing the values of the element in the list. This can be done by accessing the specific
element using indexing or slicing and assigning a new value.
0 1 2 3 4 5
list = [4 , 7 , 6, 8 , 9 , 3 ]
• Deleting an element from the list can be done using ‘del’ statement. The del statement takes the position number of
the element to be deleted.
• Concatenation of two lists: We can simply use ’+’ operator on two lists to join them. For example, ‘x’ and ‘y’ are two
lists. If we write x + y, the list ‘y’ is joined at the end of the list ‘x’.
• Repetition of Lists: we can repeat the elements of a list ‘n’ number of times using ‘*’ operator.
Unit - 2 CAP.pptx
Tuple:
• A Tuple is a python sequence which stores a group of elements or items. Tuples are similar to lists but the main
difference is tuples are immutable whereas lists are mutable.
• Once we create a tuple we cannot modify its elements. Hence we cannot perform operations like append(),
extend(), insert(), remove(), pop() and clear() on tuples. Tuples are generally used to store data which should not
be modified and retrieve that data on demand.
Creating Tuples:
Tup= ()
• To create a tuple with only one element, we can, mention that element in parenthesis and after that a comma is
needed. In the absence of comma, python treats the element as an ordinary data type.
• To create a tuple with different types of elements:
Accessing the tuple elements:
Accessing the elements from a tuple can be done using indexing or slicing. This is same as that of a list. Indexing
represents the position number of the element in the tuple. The position starts from 0.
Updating and deleting elements:
Tuples are immutable which means you cannot update, change or delete the values of tuple elements.
Unit - 2 CAP.pptx
Unit - 2 CAP.pptx
Dictionary:
• A dictionary represents a group of elements arranged in the form of Key-value pairs.
• The first element is considered as ‘Key’ and the immediate next element is taken as its ‘value’. The key and its value
are separated by a colon (:). All the key-value pairs in a dictionary are inserted in curly braces { }.
Here, the name of dictionary is ‘dict’. The first element in the dictionary is a string ‘Regd.No’. so, this is called ‘key’. The
second element is 123 which are taken as its ‘value’.
If we want to know how many key-value pairs are there in a dictionary, we can use the len() function, as shown
1 de 50

Recomendados

unit1 python.pptx por
unit1 python.pptxunit1 python.pptx
unit1 python.pptxTKSanthoshRao
5 visualizações65 slides
Python_Module_2.pdf por
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdfR.K.College of engg & Tech
13 visualizações25 slides
Introduction to Python Part-1 por
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1Devashish Kumar
632 visualizações33 slides
Py-Slides-2.ppt por
Py-Slides-2.pptPy-Slides-2.ppt
Py-Slides-2.pptAllanGuevarra1
9 visualizações21 slides
Py-Slides-2 (1).ppt por
Py-Slides-2 (1).pptPy-Slides-2 (1).ppt
Py-Slides-2 (1).pptKalaiVani395886
3 visualizações21 slides
Py-Slides-2.ppt por
Py-Slides-2.pptPy-Slides-2.ppt
Py-Slides-2.pptTejaValmiki
4 visualizações21 slides

Mais conteúdo relacionado

Similar a Unit - 2 CAP.pptx

Review Python por
Review PythonReview Python
Review PythonManishTiwari326
247 visualizações43 slides
modul-python-all.pptx por
modul-python-all.pptxmodul-python-all.pptx
modul-python-all.pptxYusuf Ayuba
6 visualizações99 slides
parts_of_python_programming_language.pptx por
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxKoteswari Kasireddy
5 visualizações34 slides
TOPIC-2-Expression Variable Assignment Statement.pdf por
TOPIC-2-Expression Variable Assignment Statement.pdfTOPIC-2-Expression Variable Assignment Statement.pdf
TOPIC-2-Expression Variable Assignment Statement.pdfEjazAlam23
10 visualizações55 slides
Python Decision Making And Loops.pdf por
Python Decision Making And Loops.pdfPython Decision Making And Loops.pdf
Python Decision Making And Loops.pdfNehaSpillai1
266 visualizações28 slides
What is c por
What is cWhat is c
What is cpacatarpit
506 visualizações56 slides

Similar a Unit - 2 CAP.pptx(20)

Review Python por ManishTiwari326
Review PythonReview Python
Review Python
ManishTiwari326247 visualizações
modul-python-all.pptx por Yusuf Ayuba
modul-python-all.pptxmodul-python-all.pptx
modul-python-all.pptx
Yusuf Ayuba6 visualizações
parts_of_python_programming_language.pptx por Koteswari Kasireddy
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptx
Koteswari Kasireddy5 visualizações
TOPIC-2-Expression Variable Assignment Statement.pdf por EjazAlam23
TOPIC-2-Expression Variable Assignment Statement.pdfTOPIC-2-Expression Variable Assignment Statement.pdf
TOPIC-2-Expression Variable Assignment Statement.pdf
EjazAlam2310 visualizações
Python Decision Making And Loops.pdf por NehaSpillai1
Python Decision Making And Loops.pdfPython Decision Making And Loops.pdf
Python Decision Making And Loops.pdf
NehaSpillai1266 visualizações
What is c por pacatarpit
What is cWhat is c
What is c
pacatarpit506 visualizações
Python basics por Hoang Nguyen
Python basicsPython basics
Python basics
Hoang Nguyen2K visualizações
Python basics por Luis Goldster
Python basicsPython basics
Python basics
Luis Goldster110 visualizações
Python basics por Harry Potter
Python basicsPython basics
Python basics
Harry Potter610 visualizações
Python basics por Tony Nguyen
Python basicsPython basics
Python basics
Tony Nguyen89 visualizações
Python basics por James Wong
Python basicsPython basics
Python basics
James Wong50 visualizações
Python basics por Young Alista
Python basicsPython basics
Python basics
Young Alista187 visualizações
Python basics por Fraboni Ec
Python basicsPython basics
Python basics
Fraboni Ec59 visualizações
The Awesome Python Class Part-3 por Binay Kumar Ray
The Awesome Python Class Part-3The Awesome Python Class Part-3
The Awesome Python Class Part-3
Binay Kumar Ray556 visualizações
C program por AJAL A J
C programC program
C program
AJAL A J4.4K visualizações
Python Unit 3 - Control Flow and Functions por DhivyaSubramaniyam
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
DhivyaSubramaniyam1.8K visualizações
c_programming.pdf por Home
c_programming.pdfc_programming.pdf
c_programming.pdf
Home22 visualizações
PE1 Module 2.ppt por balewayalew
PE1 Module 2.pptPE1 Module 2.ppt
PE1 Module 2.ppt
balewayalew16 visualizações
Python Session - 4 por AnirudhaGaikwad4
Python Session - 4Python Session - 4
Python Session - 4
AnirudhaGaikwad4377 visualizações

Último

When Sex Gets Complicated: Porn, Affairs, & Cybersex por
When Sex Gets Complicated: Porn, Affairs, & CybersexWhen Sex Gets Complicated: Porn, Affairs, & Cybersex
When Sex Gets Complicated: Porn, Affairs, & CybersexMarlene Maheu
99 visualizações73 slides
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE... por
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...Nguyen Thanh Tu Collection
51 visualizações91 slides
Class 9 lesson plans por
Class 9 lesson plansClass 9 lesson plans
Class 9 lesson plansTARIQ KHAN
53 visualizações34 slides
A Guide to Applying for the Wells Mountain Initiative Scholarship 2023 por
A Guide to Applying for the Wells Mountain Initiative Scholarship 2023A Guide to Applying for the Wells Mountain Initiative Scholarship 2023
A Guide to Applying for the Wells Mountain Initiative Scholarship 2023Excellence Foundation for South Sudan
69 visualizações26 slides
12.5.23 Poverty and Precarity.pptx por
12.5.23 Poverty and Precarity.pptx12.5.23 Poverty and Precarity.pptx
12.5.23 Poverty and Precarity.pptxmary850239
123 visualizações30 slides
Volf work.pdf por
Volf work.pdfVolf work.pdf
Volf work.pdfMariaKenney3
66 visualizações43 slides

Último(20)

When Sex Gets Complicated: Porn, Affairs, & Cybersex por Marlene Maheu
When Sex Gets Complicated: Porn, Affairs, & CybersexWhen Sex Gets Complicated: Porn, Affairs, & Cybersex
When Sex Gets Complicated: Porn, Affairs, & Cybersex
Marlene Maheu99 visualizações
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE... por Nguyen Thanh Tu Collection
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
Nguyen Thanh Tu Collection51 visualizações
Class 9 lesson plans por TARIQ KHAN
Class 9 lesson plansClass 9 lesson plans
Class 9 lesson plans
TARIQ KHAN53 visualizações
12.5.23 Poverty and Precarity.pptx por mary850239
12.5.23 Poverty and Precarity.pptx12.5.23 Poverty and Precarity.pptx
12.5.23 Poverty and Precarity.pptx
mary850239123 visualizações
Volf work.pdf por MariaKenney3
Volf work.pdfVolf work.pdf
Volf work.pdf
MariaKenney366 visualizações
MIXING OF PHARMACEUTICALS.pptx por Anupkumar Sharma
MIXING OF PHARMACEUTICALS.pptxMIXING OF PHARMACEUTICALS.pptx
MIXING OF PHARMACEUTICALS.pptx
Anupkumar Sharma107 visualizações
CUNY IT Picciano.pptx por apicciano
CUNY IT Picciano.pptxCUNY IT Picciano.pptx
CUNY IT Picciano.pptx
apicciano56 visualizações
Parts of Speech (1).pptx por mhkpreet001
Parts of Speech (1).pptxParts of Speech (1).pptx
Parts of Speech (1).pptx
mhkpreet00143 visualizações
Guess Papers ADC 1, Karachi University por Khalid Aziz
Guess Papers ADC 1, Karachi UniversityGuess Papers ADC 1, Karachi University
Guess Papers ADC 1, Karachi University
Khalid Aziz69 visualizações
Monthly Information Session for MV Asterix (November) por Esquimalt MFRC
Monthly Information Session for MV Asterix (November)Monthly Information Session for MV Asterix (November)
Monthly Information Session for MV Asterix (November)
Esquimalt MFRC91 visualizações
NodeJS and ExpressJS.pdf por ArthyR3
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
ArthyR346 visualizações
EILO EXCURSION PROGRAMME 2023 por info33492
EILO EXCURSION PROGRAMME 2023EILO EXCURSION PROGRAMME 2023
EILO EXCURSION PROGRAMME 2023
info33492124 visualizações
Create a Structure in VBNet.pptx por Breach_P
Create a Structure in VBNet.pptxCreate a Structure in VBNet.pptx
Create a Structure in VBNet.pptx
Breach_P80 visualizações
STRATEGIC MANAGEMENT MODULE 1_UNIT1 _UNIT2.pdf por Dr Vijay Vishwakarma
STRATEGIC MANAGEMENT MODULE 1_UNIT1 _UNIT2.pdfSTRATEGIC MANAGEMENT MODULE 1_UNIT1 _UNIT2.pdf
STRATEGIC MANAGEMENT MODULE 1_UNIT1 _UNIT2.pdf
Dr Vijay Vishwakarma87 visualizações
Nelson_RecordStore.pdf por BrynNelson5
Nelson_RecordStore.pdfNelson_RecordStore.pdf
Nelson_RecordStore.pdf
BrynNelson544 visualizações
JQUERY.pdf por ArthyR3
JQUERY.pdfJQUERY.pdf
JQUERY.pdf
ArthyR396 visualizações
Papal.pdf por MariaKenney3
Papal.pdfPapal.pdf
Papal.pdf
MariaKenney350 visualizações
Guidelines & Identification of Early Sepsis DR. NN CHAVAN 02122023.pptx por Niranjan Chavan
Guidelines & Identification of Early Sepsis DR. NN CHAVAN 02122023.pptxGuidelines & Identification of Early Sepsis DR. NN CHAVAN 02122023.pptx
Guidelines & Identification of Early Sepsis DR. NN CHAVAN 02122023.pptx
Niranjan Chavan38 visualizações

Unit - 2 CAP.pptx

  • 1. COMPUTING APPLICATIONS WITH PYTHON UNIT – II Operators and expressions
  • 2. Operators: The operator can be defined as a symbol which is responsible for a particular operation between two operands. Operators are the pillars of a program on which the logic is built in a specific programming language. Python provides a variety of operators, which are described as follows. • Arithmetic operators • Comparison operators • Assignment Operators • Logical Operators • Bitwise Operators • Membership Operators • Identity Operators
  • 3. 1. Arithmetic Operators: Assume variable a holds 10 and variable b holds 20, then:
  • 7. 4. Bitwise Operators: Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13; Now In binary format they will be as follows: 1. Compliment operator 2. And (&) 3. Or (|) 4. Xor (^)
  • 10. 6. Membership Operators: In addition to the operators discussed previously, Python has membership operators, which test for membership in a sequence, such as string s, lists, or tuples. There are two membership operators explained below:
  • 11. 7. Identity Operators: Identity operators compare the memory locations of two objects. There are two Identity operators explained below:
  • 12. Expressions • An expression is a combination of operators and operands that is interpreted to produce some other value. • An expression is evaluated as per the precedence of its operators. So that if there is more than one operator in an expression, their precedence decides which operation will be performed first. 1. Constant Expressions: These are the expressions that have constant values only. example: x = 15 + 1.3 print(x) output: 16.3 2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators, and sometimes parenthesis. The result of this type of expression is also a numeric value. The operators used in these expressions are arithmetic operators like addition, subtraction, etc. Here are some arithmetic operators in Python:
  • 13. Example: Arithmetic Expressions x = 40 y = 12 add = x + y sub = x - y pro = x * y div = x / y print(add) print(sub) print(pro) print(div)
  • 14. 3. Integral Expressions: These are the kind of expressions that produce only integer results after all computations and type conversions. Example: a = 13 b = 12.0 c = a + int(b) print(c) Output: 25 4. Floating Expressions: These are the kind of expressions which produce floating point numbers as result after all computations and type conversions. Example: a = 13 b = 5 c = a / b print(c) Output: 2.6
  • 15. 5. Relational Expressions: In these types of expressions, arithmetic expressions are written on both sides of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated first, and then compared as per relational operator and produce a Boolean output in the end. These expressions are also called Boolean expressions. Example : a = 21 b = 13 c = 40 d = 37 p = (a + b) >= (c - d) print(p) Output: True 6. Logical Expressions: These are kinds of expressions that result in either True or False. It basically specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it is not correct, so it will return False. Studying logical expressions, we also come across some logical operators which can be seen in logical expressions most often. Here are some logical operators in Python:
  • 16. Example: P = (10 == 9) Q = (7 > 5) R = P and Q S = P or Q T = not P print(R) print(S) print(T)
  • 17. 7. Bitwise Expressions: These are the kind of expressions in which computations are performed at bit level. Example: a = 12 x = a >> 2 y = a << 1 print(x, y) 8. Combinational Expressions: We can also use different types of expressions in a single expression, and that will be termed as combinational expressions. Example: a = 16 b = 12 c = a + (b >> 1) print(c)
  • 18. Multiple operators in expression (Operator Precedence) Operator Precedence simply defines the priority of operators that which operator is to be executed first. Here we see the operator precedence in Python, where the operator higher in the list has more precedence or priority:
  • 20. # Multi-operator expression (operator precedence). Examples: a = 10 + 3 * 4 = print(a) b = (10 + 3) * 4 print(b) c = 10 + (3 * 4) print(c)
  • 21. Control Flow:- If Statement: • Here, the program evaluates the test expression and will execute statement(s) only if the text expression is True. • If the text expression is False, the statement(s) is not executed. • In Python, the body of the if statement is indicated by the indentation. Body starts with an indentation and the first un-indented line marks the end. • Python interprets non-zero values as True. None and 0 are interpreted as False.
  • 22. Example: Python if Statement # If the number is positive, we print an appropriate message num = 3 ----------- if num > 0: print(num, "is a positive number.") print("This is always printed.") Output: 3 is a positive number. This is always printed.
  • 23. If-else Statement • The if-else statement evaluates test expression and will execute body of if only when test condition is True. • If the condition is False, body of else is executed. Indentation is used to separate the blocks.
  • 24. Example of if...else # Program checks if the number is positive or negative # And displays an appropriate message num = 3 if num >= 0: print("Positive Number") else: print("Negative number") Output: Positive Number • In the above example, when num is equal to 3, the test expression is true and body of if is executed and body of else is skipped. • If num is equal to -5, the test expression is false and body of else is executed and body of if is skipped. • If num is equal to 0, the test expression is true and body of if is executed and body of else is skipped.
  • 25. Python if- elif -else Statement • The elif is short for else if. It allows us to check for multiple expressions. • If the condition for if is False, it checks the condition of the next elif block and so on. • If all the conditions are False, body of else is executed. • Only one block among the several if...elif...else blocks is executed according to the condition. • The if block can have only one else block. But it can have multiple elif blocks.
  • 26. Example of if...elif...else # In this program, # we check if the number is positive or # negative or zero and # display an appropriate message num = -3 if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") Output: Positive number When variable num is positive, Positive number is printed. If num is equal to 0, Zero is printed. If num is negative, Negative number is printed
  • 27. Looping in Python: For Loop: The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal. • Here, val is the variable that takes the value of the item inside the sequence on each iteration. • Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.
  • 28. Example: Python for Loop # Program to find the sum of all numbers stored in a list # List of numbers numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] # variable to store the sum sum = 0 # iterate over the list for val in numbers: sum = sum+val print("The sum is", sum) Output: The sum is 48
  • 29. while loop: • The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. • We generally use this loop when we don't know beforehand, the number of times to iterate. • In while loop, test expression is checked first. The body of the loop is entered only if the test-expression evaluates to True. After one iteration, the test expression is checked again. • This process continues until the test-expression evaluates to False. In Python, the body of the while loop is determined through indentation. • Body starts with indentation and the first unindented line marks the end. • Python interprets any non-zero value as True. None and 0 are interpreted as False.
  • 30. Example: Python while Loop # Program to add natural numbers # sum = 1+2+3+...+n n = 10 # initialize sum and counter sum = 0 i = 1 while i <= n: sum = sum + i i = i+1 # update counter # print the sum print("The sum is", sum) Output: Enter n: 10 The sum is 55
  • 31. Python break statement: • The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. • If break statement is inside a nested loop (loop inside another loop), break will terminate the innermost loop. Syntax of break: Break The working of break statement in for loop and while loop is shown below.
  • 32. The working of break statement in for loop and while loop is shown below: Example: # Use of break statement inside loop for val in "string": if val == “i": break print(val) print("The end") Output: s t r The end
  • 33. Python continue statement: The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration. Syntax of Continue: continue
  • 34. The working of continue statement in for and while loop is shown below. Example: # Program to show the use of continue statement inside loops for val in "string": if val == "i": continue print(val) print("The end") Output: s t r n g The end
  • 35. pass statement: In Python programming, pass is a null statement. The difference between a comment and pass statement in Python is that, while the interpreter ignores a comment entirely, pass is not ignored. However, nothing happens when pass is executed. It results into no operation (NOP). Syntax of pass: pass Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. The interpreter would complain. So, we use the pass statement to construct a body that does nothing. Example: # pass is just a placeholder for # functionality to be added later. sequence = {'p', 'a', 's', 's'} for val in sequence: pass
  • 36. We can do the same thing in an empty function or class as well:
  • 37. Data Structures: • Data structure is a method of organizing large amount of data more efficiently so that any operation on that data becomes easy. • Python language supports 4 types of data structures. They are: 1. Lists. 2. Tuples. 3. Sets. 4. Dictionary. Lists: • A list is similar to an array that consists of a group of elements or items. Just like an array, a list can store elements. • But, there is one major difference between an array and a list. An array can store only one type of elements whereas a list can store different types of elements. Hence lists are more flexible and useful than an array. Creating a List: Creating a list is as simple as putting different comma-separated values between square brackets. list=[ ]
  • 38. We can create empty list without any elements by simply writing empty square brackets as We can create a list by embedding the elements inside a pair of square braces [ ]. The elements in the list should be separated by a comma (,). Accessing Values in list: print list[1:3]
  • 39. Creating list using range () function: We can use range () function to generate a sequence of integers which can be stored in a list. To store numbers from 0 to 10 in a list as follows. To store even numbers from 0 to 10 in a list as follows.
  • 40. Looping on lists: We can also display list by using for loop (or) while loop. The len () function useful to know the number of elements in the list. While loop retrieves starting from 0th to the last element i.e. n-1.
  • 41. Updating and deleting lists: • Lists are mutable. It means we can modify the contents of a list. We can append, update or delete the elements of a list depending upon our requirements. • Appending elements means adding an element at the end of the list. To, append a new element to the list, we should use the append() method.
  • 42. Updating an element means changing the values of the element in the list. This can be done by accessing the specific element using indexing or slicing and assigning a new value. 0 1 2 3 4 5 list = [4 , 7 , 6, 8 , 9 , 3 ] • Deleting an element from the list can be done using ‘del’ statement. The del statement takes the position number of the element to be deleted.
  • 43. • Concatenation of two lists: We can simply use ’+’ operator on two lists to join them. For example, ‘x’ and ‘y’ are two lists. If we write x + y, the list ‘y’ is joined at the end of the list ‘x’. • Repetition of Lists: we can repeat the elements of a list ‘n’ number of times using ‘*’ operator.
  • 45. Tuple: • A Tuple is a python sequence which stores a group of elements or items. Tuples are similar to lists but the main difference is tuples are immutable whereas lists are mutable. • Once we create a tuple we cannot modify its elements. Hence we cannot perform operations like append(), extend(), insert(), remove(), pop() and clear() on tuples. Tuples are generally used to store data which should not be modified and retrieve that data on demand. Creating Tuples: Tup= () • To create a tuple with only one element, we can, mention that element in parenthesis and after that a comma is needed. In the absence of comma, python treats the element as an ordinary data type. • To create a tuple with different types of elements:
  • 46. Accessing the tuple elements: Accessing the elements from a tuple can be done using indexing or slicing. This is same as that of a list. Indexing represents the position number of the element in the tuple. The position starts from 0. Updating and deleting elements: Tuples are immutable which means you cannot update, change or delete the values of tuple elements.
  • 49. Dictionary: • A dictionary represents a group of elements arranged in the form of Key-value pairs. • The first element is considered as ‘Key’ and the immediate next element is taken as its ‘value’. The key and its value are separated by a colon (:). All the key-value pairs in a dictionary are inserted in curly braces { }. Here, the name of dictionary is ‘dict’. The first element in the dictionary is a string ‘Regd.No’. so, this is called ‘key’. The second element is 123 which are taken as its ‘value’.
  • 50. If we want to know how many key-value pairs are there in a dictionary, we can use the len() function, as shown