SlideShare a Scribd company logo
1 of 50
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:
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 (^)
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:
# 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.
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.
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

More Related Content

Similar to Unit - 2 CAP.pptx

Python if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_StatementPython if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_StatementAbhishekGupta692777
 
modul-python-all.pptx
modul-python-all.pptxmodul-python-all.pptx
modul-python-all.pptxYusuf Ayuba
 
UNIT II_python Programming_aditya College
UNIT II_python Programming_aditya CollegeUNIT II_python Programming_aditya College
UNIT II_python Programming_aditya CollegeRamanamurthy Banda
 
parts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxKoteswari Kasireddy
 
TOPIC-2-Expression Variable Assignment Statement.pdf
TOPIC-2-Expression Variable Assignment Statement.pdfTOPIC-2-Expression Variable Assignment Statement.pdf
TOPIC-2-Expression Variable Assignment Statement.pdfEjazAlam23
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unitmichaelaaron25322
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.supriyasarkar38
 
Python Decision Making And Loops.pdf
Python Decision Making And Loops.pdfPython Decision Making And Loops.pdf
Python Decision Making And Loops.pdfNehaSpillai1
 
The Awesome Python Class Part-3
The Awesome Python Class Part-3The Awesome Python Class Part-3
The Awesome Python Class Part-3Binay Kumar Ray
 

Similar to Unit - 2 CAP.pptx (20)

Python if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_StatementPython if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_Statement
 
Review Python
Review PythonReview Python
Review Python
 
modul-python-all.pptx
modul-python-all.pptxmodul-python-all.pptx
modul-python-all.pptx
 
UNIT II_python Programming_aditya College
UNIT II_python Programming_aditya CollegeUNIT II_python Programming_aditya College
UNIT II_python Programming_aditya College
 
parts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptx
 
TOPIC-2-Expression Variable Assignment Statement.pdf
TOPIC-2-Expression Variable Assignment Statement.pdfTOPIC-2-Expression Variable Assignment Statement.pdf
TOPIC-2-Expression Variable Assignment Statement.pdf
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unit
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Python Decision Making And Loops.pdf
Python Decision Making And Loops.pdfPython Decision Making And Loops.pdf
Python Decision Making And Loops.pdf
 
What is c
What is cWhat is c
What is c
 
Chapter - 3.pptx
Chapter - 3.pptxChapter - 3.pptx
Chapter - 3.pptx
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
The Awesome Python Class Part-3
The Awesome Python Class Part-3The Awesome Python Class Part-3
The Awesome Python Class Part-3
 
C program
C programC program
C program
 

Recently uploaded

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 

Recently uploaded (20)

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

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:
  • 6.
  • 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 (^)
  • 8.
  • 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:
  • 19.
  • 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.
  • 44.
  • 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.
  • 47.
  • 48.
  • 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