0% found this document useful (0 votes)
23 views105 pages

Python 2 - Basic Operators

This document discusses the different types of operators in Python including arithmetic, comparison, assignment, logical, bitwise, and membership operators. It provides examples of each operator and explains their functions such as adding, subtracting, comparing, assigning values, performing logical and bitwise operations, and checking for membership in sequences.

Uploaded by

Alassan saine
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
23 views105 pages

Python 2 - Basic Operators

This document discusses the different types of operators in Python including arithmetic, comparison, assignment, logical, bitwise, and membership operators. It provides examples of each operator and explains their functions such as adding, subtracting, comparing, assigning values, performing logical and bitwise operations, and checking for membership in sequences.

Uploaded by

Alassan saine
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 105

Python - Basic Operators

Basic Operators

 Operators are the constructs which can


manipulate the value of operands.
 4 + 5 = 9. 4 and 5 are called operands and + is
called operator.
Types of Operators in Python

 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
Python Arithmetic Operators

 Assume variable a holds 10 and variable b holds


20, then −
Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

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

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

/ Division Divides left hand operand by right hand operand b/a=2

Divides left hand operand by right hand operand and returns


% Modulus b%a=0
remainder
Performs exponential (power)
** Exponent a**b =10 to the power 20
calculation on operators

 
 
Floor Division - The division of operands
where the result is the quotient in which
9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -
// the digits after the decimal point are
11.0//3 = -4.0
removed. But if one of the operands is
negative, the result is floored, i.e.,
rounded away from zero (towards
negative infinity) −
Python Comparison Operators

 These operators compare the values on either


sides of them and decide the relation among
them.
 They are also called Relational operators.
 Assume variable a holds 10 and variable b holds
20, then −
Operator Description Example
If the values of two operands are equal, then
== (a == b) is not true.
the condition becomes true.

If values of two operands are not equal, then


!= (a!= b) is true.
condition becomes true.

If the value of left operand is greater than the


>  value of right operand, then condition (a > b) is not true.
becomes true.
If the value of left operand is less than the
<  value of right operand, then condition (a < b) is true.
becomes true.

If the value of left operand is greater than or


>= equal to the value of right operand, then (a >= b) is not true.
condition becomes true.

If the value of left operand is less than or equal


<= to the value of right operand, then condition (a <= b) is true.
becomes true.
Python Assignment Operators

 Assume variable a holds 10 and variable b holds


20, then
Operator Description Example

Assigns values from right side operands to left c = a + b assigns value of a +


=
side operand b into c

+= Add It adds right operand to the left operand and c += a is equivalent to c = c +


AND assign the result to left operand a

-= Subtract It subtracts right operand from the left operand c -= a is equivalent to c = c -


AND and assign the result to left operand a
It multiplies right operand with the left
*= Multiply AND c *= a is equivalent to c = c * a
operand and assign the result to left operand

It divides left operand with the right operand and


/= Divide AND c /= a is equivalent to c = c / a
assign the result to left operand

It takes modulus using two operands and assign


%= Modulus AND c %= a is equivalent to c = c % a
the result to left operand

Performs exponential (power) calculation on


**= Exponent AND c **= a is equivalent to c = c ** a
operators and assign value to the left operand

It performs floor division on operators and assign


//= Floor Division c //= a is equivalent to c = c // a
value to the left operand
Python Bitwise Operators

 Bitwise operator works on bits and performs bit


by bit operation. Assume if a = 60; and b = 13;
 in the binary format their values will be 0011
1100 and 0000 1101 respectively.
 a = 0011 1100
 b = 0000 1101
 -----------------
 a&b = 0000 1100
 a|b = 0011 1101
 a^b = 0011 0001
 ~a  = 1100 0011
Operator Description Example

Operator copies a bit to the result if it


& Binary AND (a & b) (means 0000 1100)
exists in both operands

| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means 0011 1101)

It copies the bit if it is set in one operand


^ Binary XOR (a ^ b) = 49 (means 0011 0001)
but not both.
(~a ) = -61 (means 1100 0011
It is unary and has the effect
~ Binary Ones Complement in 2's complement form due
of 'flipping' bits.
to a signed binary number.

The left operands value is moved


a << 2 = 240 (means 1111
<< Binary Left Shift left by the number of bits
0000)
specified by the right operand.

The left operands value is moved


>> Binary Right Shift right by the number of bits a >> 2 = 15 (means 0000 1111)
specified by the right operand.
Python Logical Operators

 Assume variable a holds True and variable b


holds False then −
Operator Description Example

If both the operands are true then


and Logical AND (a and b) is False.
condition becomes true.

If any of the two operands are non-


or Logical OR (a or b) is True.
zero then condition becomes true.

Used to reverse the logical state of its


not Logical NOT Not(a and b) is True.
operand.
Python Membership Operators

 Python’s membership operators test for


membership in a sequence, such as strings, lists,
or tuples.
 There are two membership operators
Operator Description Example

Evaluates to true if it finds a


x in y, here in results in a 1 if x is a
in variable in the specified sequence
member of sequence y.
and false otherwise.

Evaluates to true if it does not finds


x not in y, here not in results in a 1 if x
not in a variable in the specified sequence
is not a member of sequence y.
and false otherwise.
Python Identity Operators

 Identity operators compare the memory locations


of two objects.
 There are two Identity operators

Operator Description Example

Evaluates to true if the variables on either side of


x is y, here is results in 1 if
is the operator point to the same object and false
id(x) equals id(y).
otherwise.

Evaluates to false if the variables on either side


x is not y, here is not results in
is not of the operator point to the same object and true
1 if id(x) is not equal to id(y).
otherwise.
Python Operators Precedence
Sr.No. Operator & Description
**
1
Exponentiation (raise to the power)

~+-
2 Complement, unary plus and minus (method names for the last
two are +@ and -@)

* / % //
3
Multiply, divide, modulo and floor division

+-
4
Addition and subtraction
>> <<
5
Right and left bitwise shift
&
6
Bitwise 'AND'
^|
7
Bitwise exclusive `OR' and regular `OR'
<= < > >=
8
Comparison operators
<> == !=
9
Equality operators
= %= /= //= -= += *= **=
10
Assignment operators
is is not
11
Identity operators
in not in
12
Membership operators
not or and
13
Logical operators
Python - Decision Making

 Decision-making is the anticipation of conditions


occurring during the execution of a program and
specified actions taken according to the
conditions.
 Decision structures evaluate multiple
expressions, which produce TRUE or FALSE as
the outcome.
 determine which action to take and which
statements to execute if the outcome is TRUE or
FALSE otherwise.
General decision making structure
 Python programming language assumes any non-
zero and non-null values as TRUE, and any zero
or null values as FALSE value.
Types of decision-making
statements.
Sr.No. Statement & Description
if statements
1 An if statement consists of a boolean expression followed by one or more
statements.

 if...else statements
2 An if statement can be followed by an optional else statement, which executes
when the boolean expression is FALSE.

nested if statements
3
You can use one if or else if statement inside another if or else if statement(s).
Python - IF Statement

 The IF statement is similar to that of other


languages.
 The if statement contains a logical expression
where the data is compared and a decision is
made based on the result of the comparison.
Syntax

 if expression:
statement(s)

 If the boolean expression evaluates to TRUE,


then the block of statement(s) inside the if
statement is executed.
 In Python, statements in a block are uniformly
indented after the : symbol.
 If boolean expression evaluates to FALSE, then
the first set of code after the end of block is
executed.
Flow Diagram
 Example
 var1 = 100
 if var1:
print ("1 - Got a true expression value")
print (var1)

 var2 = 0
 if var2:
print ("2 - Got a true expression value")
print (var2)

 print ("Good bye!")  


Output

 1 - Got a true expression value


 100
 Good bye!
Python - IF...ELIF...ELSE Statements

 An else statement can be combined with an if


statement.
 An else statement contains a block of code that
executes if the conditional expression in the if
statement resolves to 0 or a FALSE value.
 The else statement is an optional statement and
there could be at most only one else statement
following if.
Syntax

 The syntax of the if...else statement is −

 if expression:
statement(s)
 else:
statement(s)
Flow Diagram
The elif Statement

 The elif statement allows you to check multiple


expressions for TRUE and execute a block of
code as soon as one of the conditions evaluates to
TRUE.
 Similar to the else, the elif statement is optional.
 However, unlike else, for which there can be at
most one statement, there can be an arbitrary
number of elif statements following an if.
syntax

 if expression1:
statement(s)
 elif expression2:
statement(s)
 elif expression3:
statement(s)
 else:
statement(s)
 Core Python does not provide switch or case
statements as in other languages, but we can use
if..elif... statements to simulate switch case.
Python - Nested IF Statements

 There may be a situation when you want to check


for another condition after a condition resolves to
true then In such a situation, you can use the
nested if construct.
 In a nested if construct, you can have an
if...elif...else construct inside another
if...elif...else construct.
Syntax

 The syntax of the nested if...elif...else construct may be −

 if expression1:
statement(s)
 if expression2:

statement(s)
 elif expression3:

statement(s)
 else

statement(s)
 elif expression4:

statement(s)
 else:

statement(s)
Python - Loops

 In general, statements are executed sequentially −


The first statement in a function is executed first,
followed by the second, and so on.
 There may be a situation when you need to
execute a block of code several number of times.
 A loop statement allows us to execute a statement
or group of statements multiple times.
loop statement diagram
Types of loops in python
Sr.No. Loop Type & Description
while loop
1 Repeats a statement or group of statements while a given condition is TRUE. It
tests the condition before executing the loop body.

for loop
2 Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

nested loops
3
You can use one or more loop inside any another while, or for loop.
Python - while Loop Statements

 Repeats a statement or group of statements while


a given condition is TRUE. It tests the condition
before executing the loop body.
 A while loop statement in Python programming
language repeatedly executes a target statement
as long as a given condition is true.
Syntax

 The syntax of a while loop in Python


programming language is −

 while expression:
statement(s)
 statement(s) may be a single statement or a
block of statements with uniform indent.
 The condition may be any expression, and true is
any non-zero value.
 The loop iterates while the condition is true.
 When the condition becomes false, program
control passes to the line immediately following
the loop.
 In Python, all the statements indented by the
same number of character spaces after a
programming construct are considered to be part
of a single block of code.
 Python uses indentation as its method of
grouping statements.
Flow Diagram
 
 a key point of the while loop is that the loop
might not ever run.
 When the condition is tested and the result is
false, the loop body will be skipped and the first
statement after the while loop will be executed.
Example
 count = 0
 while (count < 9):
print ('The count is:', count)
count = count + 1
 print ("Good bye!")  
 Output
 The count is: 0
 The count is: 1
 The count is: 2
 The count is: 3
 The count is: 4
 The count is: 5
 The count is: 6
 The count is: 7
 The count is: 8

 Good bye!
 The block here, consisting of the print and
increment statements, is executed repeatedly until
count is no longer less than 9.
 With each iteration, the current value of the index
count is displayed and then increased by 1.
The Infinite Loop

 A loop becomes infinite loop if a condition never


becomes FALSE.
 Cautious must be taken when using while loops
because of the possibility that this condition may
never resolves to a FALSE value.
 This results in a loop that never ends and such a
loop is called an infinite loop.
 An infinite loop might be useful in client/server
programming where the server needs to run
continuously so that client programs can
communicate with it and when required.
 Example
 var = 1
 while var == 1 : # This constructs an infinite loop
 num = int(input("Enter a number :"))

 print ("You entered: ", num)


 print ("Good bye!")
 result /output

 Enter a number :20


 You entered: 20
 Enter a number :29
 You entered: 29
 Enter a number :3
 You entered: 3
 Enter a number :11
 You entered: 11
 The above example goes in an infinite loop and
you need to use CTRL+C to exit the program.
Using else Statement with Loops

 If the else statement is used with a for loop, the


else statement is executed when the loop has
exhausted iterating the list.
 If the else statement is used with a while loop,
the else statement is executed when the condition
becomes false.
 Example an else statement with a while
statement that prints a number as long as it is less
than 5, otherwise the else statement gets
executed.
 count = 0
 while count < 5:
print (count, " is less than 5")
count = count + 1
 else:
print (count, " is not less than 5")
 Output
 0 is less than 5
 1 is less than 5
 2 is less than 5
 3 is less than 5
 4 is less than 5
 5 is not less than 5
Single Statement Suites

 if a while clause consists only of a single


statement, it may be placed on the same line as
the while header.
 example of a one-line while clause

 flag = 1
 while (flag): print ('Given flag is really true!')
 print ("Good bye!")

 The above example goes into an infinite loop and you need
to press CTRL+C keys to exit.
Python - for Loop Statements

 Executes a sequence of statements multiple times


and abbreviates the code that manages the loop
variable.
 The for statement in Python has the ability to
iterate over the items of any sequence, such as a
list or a string.
Syntax

 for iterating_var in sequence:


statements(s)

 If a sequence contains an expression list, it is


evaluated first.
 Then, the first item in the sequence is assigned to
the iterating variable iterating_var.
 Next, the statements block is executed. Each item
in the list is assigned to iterating_var, and the
statement(s) block is executed until the entire
sequence is exhausted.
Flow Diagram
 
The range() function

 The built-in function range() is the right function


to iterate over a sequence of numbers.
 It generates an iterator of arithmetic progressions.
 Example
range(5)
 range(0, 5)
list(range(5))
 [0, 1, 2, 3, 4]
 Example
 range() generates an iterator to progress integers
starting with 0 up to n-1.
 To obtain a list object of the sequence, it is type
casted to list().
 Now this list can be iterated using the for
statement.
for var in list(range(5)):
 print (var)

Output
 0
 1
 2
 3
 4
 Example
 for letter in 'Python': # traversal of a string sequence
print ('Current Letter :', letter)
 print()

 fruits = ['banana', 'apple', 'mango']


 for fruit in fruits: # traversal of List sequence
print ('Current fruit :', fruit)
 print ("Good bye!")
 Output
 Current Letter : P
 Current Letter : y
 Current Letter : t
 Current Letter : h
 Current Letter : o
 Current Letter : n
 Current fruit : banana
 Current fruit : apple
 Current fruit : mango
 Good bye!
Iterating by Sequence Index

 An alternative way of iterating through each item


is by index offset into the sequence itself.
 example −

 fruits = ['banana', 'apple', 'mango']


 for index in range(len(fruits)):
print ('Current fruit :', fruits[index])
 print ("Good bye!")
 Output
 Current fruit : banana
 Current fruit : apple
 Current fruit : mango
 Good bye!
 the len() built-in function, provides the total
number of elements in the tuple as well as the
range() built-in function to give us the actual
sequence to iterate over. 
Using else Statement with Loops

 If the else statement is used with a for loop, the


else block is executed only if for loops
terminates normally (and not by encountering
break statement).
 If the else statement is used with a while loop,
the else statement is executed when the condition
becomes false.
Python - Nested loops

 one or more loops can be used inside any other


while, or for loop.
 Python allows the usage of one loop inside
another loop.
Syntax

 for iterating_var in sequence:


for iterating_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop
statement in Python
 while expression:
while expression:
statement(s)
statement(s)
 A final note on loop nesting is that you can put
any type of loop inside any other type of loop.
 For example a for loop can be inside a while
loop or vice versa.
Loop Control Statements

 The Loop control statements change the


execution from its normal sequence.
 When the execution leaves a scope, all automatic
objects that were created in that scope are
destroyed.
Python control statements.

 1. break statement
 2. continue statement
 3. pass statement
break statement

 Terminates the loop statement and transfers


execution to the statement immediately following
the loop.
 The break statement is used for premature
termination of the current loop. After abandoning
the loop, execution at the next statement is
resumed.
 The break statement can be used in both while
and for loops.
 When using nested loops, the break statement
stops the execution of the innermost loop and
starts executing the next line of the code after the
block.
Syntax

The syntax for a break statement in Python is as


follows −
 break
Flow Diagram
 Example
 for letter in 'Python': # First Example
if letter == 'h':
Break
print ('Current Letter :', letter)
 var = 10 # Second Example
 while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
Break
 print ("Good bye!")
 Output
 Current Letter : P
 Current Letter : y
 Current Letter : t
 Current variable value : 10
 Current variable value : 9
 Current variable value : 8
 Current variable value : 7
 Current variable value : 6
 Good bye!
Python - continue statement

 Causes the loop to skip the remainder of its body


and immediately retest its condition prior to
reiterating.
 The continue statement in Python returns the
control to the beginning of the current loop.
 When encountered, the loop starts next iteration
without executing the remaining statements in the
current iteration.
 The continue statement can be used in both while
and for loops.
Syntax

 Continue
Flow Diagram
 Example
 for letter in 'Python': # First Example
if letter == 'h':
Continue
print ('Current Letter :', letter)
 var = 10 # Second Example
 while var > 0:
var = var -1
if var == 5:
Continue
print ('Current variable value :', var)
 print ("Good bye!")
 Output
 Current Letter : P
 Current Letter : y
 Current Letter : t
 Current Letter : o
 Current Letter : n
 Current variable value : 9
 Current variable value : 8
 Current variable value : 7
 Current variable value : 6
 Current variable value : 4
 Current variable value : 3
 Current variable value : 2
 Current variable value : 1
 Current variable value : 0
 Good bye!
Python - pass Statement

 The pass statement in Python is used when a


statement is required syntactically but you do not
want any command or code to execute.
 The pass statement is a null operation; nothing
happens when it executes.
Syntax

 Pass

Example
 for letter in 'Python':
if letter == 'h':
Pass
print ('This is pass block')
print ('Current Letter :', letter)
 print ("Good bye!")
 Output

 Current Letter : P
 Current Letter : y
 Current Letter : t
 This is pass block
 Current Letter : h
 Current Letter : o
 Current Letter : n
 Good bye!

You might also like