You are on page 1of 30

Python - Basic Operators

Python language supports following type of operators.


• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
Python Arithmetic Operators:

Operator Description Example


+ Addition - Adds values on either side of the a + b will give 30
operator
- Subtraction - Subtracts right hand operand a - b will give -10
from left hand operand
* Multiplication - Multiplies values on either a * b will give 200
side of the operator
/ Division - Divides left hand operand by b / a will give 2
right hand operand
% Modulus - Divides left hand operand by b % a will give 0
right hand operand and returns remainder
** Exponent - Performs exponential (power) a**b will give 10 to
calculation on operators the power 20
// Floor Division - The division of operands 9//2 is equal to 4 and
where the result is the quotient in which 9.0//2.0 is equal to 4.0
the digits after the decimal point are
removed.
Python Comparison Operators:

Operator Description Example


== Checks if the value of two operands are equal or not, (a == b) is not true.
if yes then condition becomes true.
!= Checks if the value of two operands are equal or not, (a != b) is true.
if values are not equal then condition becomes true.
<> Checks if the value of two operands are equal or not, (a <> b) is true. This is
if values are not equal then condition becomes true. similar to != operator.
> Checks if the value of left operand is greater than the (a > b) is not true.
value of right operand, if yes then condition becomes
true.
< Checks if the value of left operand is less than the (a < b) is true.
value of right operand, if yes then condition becomes
true.
>= Checks if the value of left operand is greater than or (a >= b) is not true.
equal to the value of right operand, if yes then
condition becomes true.
<= Checks if the value of left operand is less than or (a <= b) is true.
equal to the value of right operand, if yes then
condition becomes true.
Python Assignment Operators:
Operator Description Example
= Simple assignment operator, Assigns values from right c = a + b will
side operands to left side operand assigne value of a +
b into c
+= Add AND assignment operator, It adds right operand to c += a is equivalent
the left operand and assign the result to left operand to c = c + a
-= Subtract AND assignment operator, It subtracts right c -= a is equivalent
operand from the left operand and assign the result to left to c = c - a
operand
*= Multiply AND assignment operator, It multiplies right c *= a is equivalent
operand with the left operand and assign the result to left to c = c * a
operand
/= Divide AND assignment operator, It divides left operand c /= a is equivalent
with the right operand and assign the result to left to c = c / a
operand
%= Modulus AND assignment operator, It takes modulus c %= a is equivalent
using two operands and assign the result to left operand to c = c % a
**= Exponent AND assignment operator, Performs exponential c **= a is
(power) calculation on operators and assign value to the equivalent to c = c
left operand ** a
//= Floor Division and assigns a value, Performs floor division c //= a is equivalent
on operators and assign value to the left operand to c = c // a
Python Bitwise Operators:

Operator Description Example


& Binary AND Operator copies a bit to the (a & b) will give 12
result if it exists in both operands. which is 0000 1100
| Binary OR Operator copies a bit if it exists (a | b) will give 61
in either operand. which is 0011 1101
^ Binary XOR Operator copies the bit if it is (a ^ b) will give 49
set in one operand but not both. which is 0011 0001
~ Binary Ones Complement Operator is unary (~a ) will give -60
and has the effect of 'flipping' bits. which is 1100 0011
<< Binary Left Shift Operator. The left a << 2 will give 240
operands value is moved left by the which is 1111 0000
number of bits specified by the right
operand.
>> Binary Right Shift Operator. The left a >> 2 will give 15
operands value is moved right by the which is 0000 1111
number of bits specified by the right
operand.
Python Logical Operators:

Operator Description Example

and Called Logical AND operator. If both the (a and b) is true.


operands are true then then condition
becomes true.
or Called Logical OR Operator. If any of the (a or b) is true.
two operands are non zero then then
condition becomes true.
not Called Logical NOT Operator. Use to not(a and b) is false.
reverses the logical state of its operand. If a
condition is true then Logical NOT operator
will make false.
Python Membership Operators:
In addition to the operators discussed previously, Python has
membership operators, which test for membership in a
sequence, such as strings, lists, or tuples.

Operator Description Example

in Evaluates to true if it finds a variable in the x in y, here in results in a


specified sequence and false otherwise. 1 if x is a member of
sequence y.

not in Evaluates to true if it does not finds a x not in y, here not in


variable in the specified sequence and false results in a 1 if x is a
otherwise. member of sequence y.
Python Operators Precedence
Operator Description
** Exponentiation (raise to the power)
~+- Ccomplement, unary plus and minus (method names for
the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += Assignment operators
*= **=
is is not Identity operators
in not in Membership operators
not or and Logical operators
Python - IF...ELIF...ELSE Statement
• The syntax of the if statement is:
if expression: if expression:
statement(s) statement(s)
Example: else:
var1 = 100 statement(s)
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!"
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1

var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2
print "Good bye!"
The Nested if...elif...else Construct
Example:
var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
elif var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"

print "Good bye!"


Single Statement Suites:
If the suite of an if clause consists only of a single line, it may
go on the same line as the header statement:

if ( expression == 1 ) : print "Value of expression is 1"


Programming using Python

• Loops

Python Programming 13
Printing Multiplication Table

5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50

Jan-24 Python Programming


Program…

n = int(input('Enter a Too
number:
much '))
print (n, 'X', 1, '=', n*1)
repetition!
print (n, 'X', 2, '=', n*2)
Can I avoid
print (n, 'X', 3, '=', n*3)it?
print (n, 'X', 4, '=', n*4)
print (n, 'X', 5, '=', n*5)
print (n, 'X', 6, '=', n*6)
….

Jan-24 15
Python Programming
Printing Multiplication Table

Input n Loop Entry


i=1

Loop Exit
i <=10 FALSE
TRUE

Print n X i = n*i Stop


i = i+1

Loop
Jan-24 Python Programming
Printing Multiplication Table
Input n
i=1

TRUE
i <=10
FALSE n = int(input('n=? '))
i=1
Print n x i = ni Stop
i = i+1

while (i <= 10) :


print (n ,'X', i, '=', n*i)
i=i+1
print ('done‘)

Jan-24 Python Programming


17
while Loop Statements
• The while loop is one of the looping constructs available in
Python. The while loop continues until the expression becomes
false.
• The expression has to be a logical expression and must return
either a true or a false value
The syntax of the while loop is:
while expression:
statement(s)
Example: The count is: 0
count = 0 The count is: 1
The count is: 2
while (count < 9): The count is: 3
print ('The count is:', count) The count is: 4
The count is: 5
count = count + 1 The count is: 6
print ("Good bye!“) The count is: 7
The count is: 8
Good bye!
While Statement

while (expression):
S1 FALSE
expression
S2
TRUE
S1 S2

1. Evaluate expression
2. If TRUE then
a) execute statement1
b) goto step 1.
3. If FALSE then execute statement2.
19
Jan-24 Python Programming
While loop with List

# loop will run until there is an element present in list

5
a=[1,2,3,4,5]
4
while a: 3
print(a.pop()) 2
1
The Infinite Loops:
• You must use caution when using while loops because
of the possibility that this condition never resolves to
a false value. This results in a loop that never ends.
Such a loop is called an infinite loop.
•Traceback
An infinite
(most recent loop
call last): might be useful in client/server
programming
File where the server needs line
"C:/Users/SBJ/AppData/Local/Programs/Python/Python310/wh1.py", to1, in run
<module>
continuously
while var == 1 :
so that client programs can
communicate
NameError: name 'var' is with it as
not defined. Didand when
you mean: required.
'vars'?

Following loop will continue till you enter CTRL+C :


while var == 1 : # This constructs an infinite loop
num = raw_input("Enter a number :")
print ("You entered: ", num)
print ("Good bye!“)
Single Statement Suites:
• Similar to the if statement syntax, if your while clause
consists only of a single statement, it may be placed on the
same line as the while header.

• Here is the syntax of a one-line while clause:

while expression : statement

Example:
count=0
while (count<5):count+=1; print(“Hello, Everyone”)
Hello, Everyone
Hello, Everyone
Hello, Everyone
Hello, Everyone
Hello, Everyone
6. Python - for Loop Statements
• The for loop in Python has the ability to iterate over the items
of any sequence, such as a list or a string.
• The syntax of the loop look is:
for iterating_var in sequence: Current Letter : P
Current Letter : y
statements(s) Current Letter : t
Example: Current Letter : h
Current Letter : o
for letter in 'Python': Current Letter : n
print ('Current Letter :', letter)

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


for fruit in fruits: Current fruit : banana
print ('Current fruit :', fruit)
Current fruit : apple
print ("Good bye!“) 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!“)
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Function range() :

 we can also use a range() function in for loop to


iterate over numbers defined by range().
• range(n):
– generates a set of whole numbers starting from 0 to
(n-1).
• range(start, stop):
– generates a set of whole numbers starting from start
to stop-1
• range(start, stop, step_size):
– The default step_size is 1
– By specifying step_size we can generate numbers
having the difference of step_size.
for i in range(5)
square = i*i
print("The square of", i, "is", square)

sum = 0
for val in range(1, 6):
sum = sum + val
print(sum)

n=int(input("Enter the value of n: "))


for i in range(n,0,-1):
print(i)
7. Python break, continue and pass Statements

The break Statement:


• The break statement in Python terminates the current loop and
resumes execution at the next statement, just like the
traditional break found in C.
Example:
for letter in 'Python': # First Example
if letter == 'h': Current Letter : P
break Current Letter : y
print 'Current Letter :', letter Current Letter : t

var = 10 # Second Example


while var > 0: Current variable value : 9
print ('Current variable value :', var) Current variable value : 8
var = var -1 Current variable value : 7
if var == 5: Current variable value : 6
break Good bye!
print "Good bye!"
The continue Statement:
• The continue statement in Python returns the control to the
beginning of the while loop. The continue statement rejects all
the remaining statements in the current iteration of the loop
and moves the control back to the top of the loop.
Example:
for letter in 'Python': # First Example Current Letter : P
if letter == 'h': Current Letter : y
Current Letter : t
continue
Current Letter : o
print ('Current Letter :', letter) Current Letter : n
var = 10 # Second Example Current variable value : 9
while var > 0: Current variable value : 8
Current variable value : 7
var = var -1 Current variable value : 6
if var == 5: Current variable value : 4
continue Current variable value : 3
Current variable value : 2
print ('Current variable value :', var) Current variable value : 1
print ("Good bye!“) Current variable value : 0
Good bye!
The else Statement Used with Loops

Python supports to have an else statement associated with a loop


statements.
• 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:
10 equals 2 * 5
for num in range(10,20):
11 is a prime number
for i in range(2,num):
if num%i == 0:
12 equals 2 * 6
j=num/i 13 is a prime number
14 equals 2 * 7
print ('%d equals %d * %d' % (num,i,j))
break 15 equals 3 * 5
else: 16 equals 2 * 8
print(num, 'is a prime number‘) 17 is a prime number
18 equals 2 * 9
19 is a prime number
The 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. The pass is also useful in places where
your code will eventually go, but has not been written yet
(e.g., in stubs for example):
Example:
Current Letter : P
for letter in 'Python':
Current Letter : y
if letter == 'h': Current Letter : t
pass This is pass block
print ('This is pass block‘) Current Letter : h
print ('Current Letter :', letter) Current Letter : o
Current Letter : n
print ("Good bye!“)
Good bye!

You might also like