Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Lab-2_Conditional Statements

Topices:
❖ Operators
❖ input Function
❖ Indentation
❖ Conditional Statements
● If ,
● If- else,
● Nested if-else,
● Looping,
◆ For,
◆ While,
◆ Nested loops
Python - Basic Operators
❖ Python language supports following type of operators.
➢ Arithmetic Operators
➢ Comparision Operators
➢ Logical (or Relational) Operators
➢ Assignment Operators
➢ Bitwise Operators
➢ Conditional Operators

consider two variable a and b and its’ value are 10 and 20


respectively.
a=10
b=20
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.
#Expression and operators
''' +,-,*,**,/,//,%,....
=,==,+=,-=,we can do it
for all above operators
'''
a,b=4,6
Output:
print(a+b)
10
print(a-b)
-2
print(a*b) 24
print(a**b) 4096
print(a/b) 0.66666666666666
print(a//b) 66
print(a%b)
0
4
print(a==b)
False
a%=b 4
print(a)
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.
# Comparison Operators
a=5
b=7
c=7 Output:
print(a==b) False
print(b==c) True
print(a!=b) True
print(c!=b) False
print(a<b) True
print(b<=c) 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
# Assignment operators
a=5
b=7
c=a+b
print(c)
Output:
c+=a 12
print(c) 17
c-=a
12
print(c)
c*=a
60
print(c) 0
c%=a 5 7
print(c)
d,e=a,b
print(d,e)
Python Bitwise Operators:

Operat
Description Example
or
& 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 Bitwise Operators:
# &,|,^,~,<<,>>
a=5
b=6
c=a&b
d=a|b
e=a^b
f=~a
g=a<<1 Output:
h=a>>4
4
print(c)
print(d)
7
print(e) 3
print(f) -6
print(g) 10
print(h)
0
Python Logical Operators:

Operat
Description Example
or
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 Logical Operators
(and,or,not)
a=9
b=8
c=8
d=0 Output:
print((a>b) and (b==c)) True
print((a<b) and (b==c)) False
print((a<b) or (b==c)) True
print((a>b) and (b!=c))
False
print((a>b) and (not(b!=c)))
True
print(not (a))
print(not (d))
False
not (not (d)) True
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 membership Operators
(in,not in)
st="This is test string"
c= 'i' in st
print(c) Output:
d='i' not in st True
print(d)
False
st.find('i')
2
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
input Function

input : Reads a string from the user's keyboard.


–reads and returns an entire line of input *

# Input function in python


name=input("What is your name?")
print("Wellcome ",name)
Output:
What is your name?Rahul
Wellcome Rahul
read numbers

To read numbers, cast input result to an int or float


–If the user does not type a number, an error occurs.

–Example:
age = int(input("How old are you? "))
print("Your age is", age)
print(60 - age, "years to retirement")

Output:
How old are you? 46
Your age is 46
14 years to retirement
Indentation
Python uses indentation to define control and loop constructs. Indentation in Python
refers to the (spaces and tabs) that are used at the beginning of a statement. The
statements with the same indentation belong to the same group called a
suite.Python uses the colon symbol (:) and indentation for showing where blocks
of code begin and end. That is, blocks in Python, such as functions, loops, if clauses
and other constructs, have no ending identifiers. All blocks start with a colon and
then contain the indented lines below it.

Python - IF...ELIF...ELSE Statement

if expression: if expression:
statement-1 statement(s)
statement-2 else:
statement-3 statement(s)
Indentation and If statement in Python

#Indentation in Python
no=1
a=5
b=8

if no==1:
print("I will print one number")
print(a)
if no==2:
print("I will print two numbers")
print(a)
print(b)
print('end')
IF …. ELSE Statement

no=2
a=5
b=8

if no==1:
print("I will print one number")
print(a)
else:
print("I will print two numbers")
print(a)
print(b)
print('end')
OUTPUT:
I will print two numbers
5
8
end
if...elif...else Construct
Syntax of if...elif...else
num = 3
if expression:
Body of if
# Try these two variations as well:
elif expression: # num = 0
Body of elif # num = -2.5
else:
Body of else
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
# Nested IF
’’’test using positive/ negative number and zero’’’
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
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!") Output:


Expression value is less than 200
Which is 100
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:

expression=1
if ( expression == 1 ) : print('Value of expression is 1')
5. Python - 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:
i = 1
while i < 6:
print(i)
i += 1

output:
1
2
3
4
5
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.
• 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 as and when required.

Following loop will continue till you enter CTRL+C :


while var == 1 : # This constructs an infinite loop
num = int(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


Python - for Loop Statements
for loops iterate over a collection of items, such
as list or dict, and run a block of code with each
element from the collection.

for [iterating variable] in [sequence]:


[do something]

for i in [1, 2, 3, 4,5]:


print(i)

range is a function that returns a series of numbers under an


iterable form, thus it can be used in for loops:
for i in range(5):
print(i)
for i in range(1,6):
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:
i = 0
while i < 7: for i in (0, 1, 2, 3, 4):
print(i) print(i)
if i == 4:
print("Breaking from loop") if i == 2:
break
i += 1
break

Output:
0
1
2
3
4
Breaking from loop
The continue Statement:
• The continue statement in Python returns the control to the
beginning of the 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.

for i in (0, 1, 2, 3, 4, 5):


if i == 2 or i == 4:
continue
print(i)
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:
i=0
for i in
while i < 3:
range(3):
print(i)
print(i) i += 1
else: else:
print('done') print('done')

Output: Output:
0 0
1
1
2
2 done
done
The pass Statement:
• pass is a null statement for when a statement is required by
Python syntax (such as within the body of a for or
• while loop), but no action is required or desired by the
programmer. This can be useful as a placeholder for code
• that is yet to be written.

Example:
x=3
for x in range(10): y=5
pass
while x==y:
pass
Thanks for today

You might also like