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

CONDITIONAL STATEMENTS 25

CONDITIONAL STATEMENT

LESSON - ONE Syntax for if statement:


if (condition):
INTRODUCTION TO CONDITIONAL
STATEMENTS if block statement

Decision Making in programming is similar to next line of code


decision making in real life. In programming, a
certain block of code needs to be executed when
some condition is fulfilled.

What is Conditional Statement?


Conditional /decision making/ Statements are
statements executed based on the condition.
Python Interpreter execute sequentially when there is
no condition around the statements. If you put some
condition for a block of statements, the execution
flow may change based on the result evaluated by the
condition.
Why do we have these much space before if-
There are four types of conditional statements in block statement?
python. They are as follows:
In Python, indentation is used to separate the if-block
1. if statement statement from other block. If two statements are at
2. if else statement the same indentation level, then they are the part of
3. Nested if statement the same block.
4. if elif else statement
Generally, four spaces are given to indent the
LESSON - TWO statements which are a typical amount of indentation.

if STATEMENT What is Indentation?


The if statement is used to test a specific condition. Indentation is the spaces at the beginning of a code
If the condition is true, if-block statement will be line to indicate a block of code.
executed.
Note: if statement contains an expression/condition.
The condition of if statement can be any valid logical As per the syntax colon (:) is mandatory otherwise it
expression which can be either evaluated to True or throws syntax error.
False.
CONDITIONAL STATEMENTS 26

Condition gives the result as a bool type, either True Syntax for if else statement:
or False. If the condition result is True, then if block
if (condition):
statements will be executed. If the condition result is
False, then next line of code execute. if block statement

Suppose you want hire employees for your else:


company and your main condition is employee’s age else block statement
should be above 18 because hiring under age is
prohibited. let us develop a code to filter job next line of code
applicants.
Ex 7.1 ( if statement )

a = int(input("Enter your age\n"))


if a > 17:
print("Pass for interview.")

Enter your age


27
Pass for interview.
Ex 7.2 ( Indentation Error )
Ex 7.3 ( if else statement )
a = int(input("Enter your age\n"))
if a > 17: a = int(input("Enter your age\n"))

print("Pass for interview.") if a > 17:


print("Pass for interview.")
IndentationError: Expected an indented
block else:

EXERCISE 7.1 print("Application Denied.")


Create a variable "age" and take input from user Enter your age
then check vote eligibility (age > 18)?
17

What if you want to reject applicants who could Application Denied.


not fulfill the age condition?
EXERCISE 7.2
PS. Clear rejection is better than ignorance. Create a variable "username" and its value is your
LESSON - THREE name then create log in conditional statement
based on username?
if else STATEMENT Hint: Output looks like below
If the condition result is True, then if block Enter your username
statements will be executed. If the condition result is
john
False, then else block statements will be executed.
Welcome to facebook.
CONDITIONAL STATEMENTS 27

Here is a problem, What if a 90 years old man II Pause the next operators for a
applied for the job, will you accept him? Hell No while
Therefore we need to add additional condition to Ex 7.5 ( if else statement with compound condition)
specify required age range.
a = int(input("Enter your age\n"))
► Resume the next operators for a if a > 17 and a < 45:
while
print("Pass for interview.")
What if we want to combine two relational else:
operators. How? Let us see…
print("Application Denied.")
In such scenarios, we use Logical Operators
Enter your age
What are Logical Operators?
90
Logical Operators are operators which do some
logical operation on the operands and return True or Application Denied.
False are called logical operators. EXERCISE 7.3
In python, there are three types of logical operators. Create two variable and "nationality" and "cgpa"
They are and, or, not. These operators are used to and store values is your name and nationality, then
construct compound conditions, combinations of create scholarship conditional statement based on
more than one simple condition. Each simple nationality and cgpa?
condition gives a boolean value which is evaluated,
Hint: Output looks like below
to return final boolean value.
Enter your nationality
Note: In logical operators, False indicates 0(zero)
and True indicates non-zero value. Logical operators Indian
on boolean types Enter your cgpa
 and : If both the arguments are True then 8.7
only the result is True Congratulations, you won.
 or : If at least one argument is True then the
result is True
 not : complement of the boolean value What if you have more additional condition like (
Applicant should have GPA above than 9 else he/she
Ex 7.4 ( Logical operators on boolean types ) will be in waiting list ) ?
a,b = True,False PS. Quality is determined by accuracy and
completeness.
print(a and b) #and
print(a or b) #or LESSON - FOUR

print(not a) #not NESTED if STATEMENT


False Nested if statement is an if statement inside another
if statement. Here, a user can decide among multiple
True options based on multiple conditions.
False
CONDITIONAL STATEMENTS 28

Syntax for Nested if statement: Enter your age


if (condition 1): 28
if(condition 2): Enter your GPA
if block statement of 8.5
condition 2 Waiting List...
else:
EXERCISE 7.4
else block statement
Create two variable "username" and "password"
of condition 2 and store values is your name and password, then
create log in conditional statement based on
else:
username and password?
else block statement of Hint: Output looks like below
condition 1 Enter your username
next line of code john
Enter your password
12345
Welcome to facebook.

Now, you couldn’t get a person who have GPA


more than 9, and the job vacancy is urgent, so you
need to reduce GPA criteria to lower range.

LESSON - FIVE

if elif else STATEMENT


Ex 7.6 ( Nested if statement )
The conditions are evaluated in the written order. If
a = int(input("Enter your age\n")) one condition becomes True then the set of
statements associated with that particular condition
c=float(input("Enter your GPA\n")) are executed and the execution comes out without
if a > 17 and a < 45: checking other conditions.

if c > 9: Syntax for if elif else statement:

print("Accepted.") if (condition):
else: if block statement
print("Waiting List...") elif:
else: elif block statement
print("Application Denied.") else:
else block statement
next line of code
CONDITIONAL STATEMENTS 29

LESSON - SIX

MORE EXAMPLES ON CONDITIONAL


STATEMENTS
Ex 7.8 ( if else statement )

a=float(input("Enter 1st No:\n"))


b=float(input("Enter 2nd No:\n"))
if a > b:
print(a,"is the largest No.")
else:
print(b,"is the largest No.")
Ex 7.7 ( if elif else statement )
Enter 1st No
a = int(input("Enter your age\n"))
45
c=float(input("Enter your GPA\n")) Enter 2nd No
if a>17 and a>45 and c>9: 21
45 is largest number
print("Accepted.")
Recall Syntax for if else using Tertiary Operator:
elif a>17 and a>45 and c>9 and c<7:
[on_True] if (condition) else [on_False]
print("Pass for interview.")
Ex 7.9 ( if else statement using tertiary operator)
else:
a=float(input("Enter 1st No:\n"))
print("Application Denied.")
b=float(input("Enter 2nd No:\n"))
Enter your age
max = a if a > b else b:
21
print("Largest No.=",max)
Enter your GPA
Enter 1st No: 13
8.5 Enter 2nd no: 45
Pass for interview. Largest No.= 45

EXERCISE 7.5 Ex 7.10 ( if elif else statement )

Create a variable "score" and take input from user, a=float(input("Enter 1st No:\n"))
then classify them based on their score? b=float(input("Enter 2nd No:\n"))
Classification:
if a > b:
"A" – 90 to 100
print(a,"is the largest No.")
"B" – 80 to 90
elif a = b:
"C" – 70 to 80
print(a,"and",b,"are equal.")
"D" – 60 to 70
else:
"F" – below 60
print(b,"is the largest No.")
CONDITIONAL STATEMENTS 30

Enter 1st No: 45 largest = b


Enter 2nd No: 45 else:

45 and 45 are equal largest = c

Ex 7.11 ( Half Nested if statement ) print("The largest No is",largest)

a=float(input("Enter 1st no: \n")) Enter first number


21
b=float(input("Enter 2nd no: \n"))
Enter second number
c=float(input("Enter 3rd no: \n")) 21
if a > b: Enter third number
45
if a > c: The largest No is 45
print("largest no.= ",a)
► Resume the next operators for a
else: while
print("largest no.= ",c)
What if we want to swap two variables?
else:
Variable Swapping
print("largest no.= ",b)
 Using third variable
Enter 1st no: 21  Using Assignment operator
Enter 2nd no: 45  Using * and / operators
 Using ^ ( XOR ) operator
Enter 3rd no: 13
Ex 7.13 ( Using third variable )
largest no.= 45
a,b = 1,2
What if a and b are equal numbers. For print("Before Swap a=",a,"b=",b)
example: (1,1,2) or (1,2,2) or (2,1,2) (2,2,2)
temp = a
Ohh.. Hell no it is incorrect output, Here we go to
fix it because we are programmers. a = b

Ex 7.12 ( Full Nested if statement ) b = temp

a=float(input('Enter 1st No: ')) print("After Swap a=",a,"b=",b)

b=float(input('Enter 2nd No: ')) Before Swap a=1 b=2


c=float(input('Enter 3rd No: ')) After Swap a=2 b=1
if(a >= b): Ex 7.14 ( Using Assignment operator )
if(a >= c): a,b = 1,2
largest = a print("Before Swap a=",a,"b=",b)
else: a,b = b,a
largest = c print("After Swap a=",a,"b=",b)
else: Before Swap a=1 b=2
if(b >= c): After Swap a=2 b=1
CONDITIONAL STATEMENTS 31

Ex 7.15 ( Using + and – operators ) print("Previous bus stop is",p)


a,b = 1,2 print("Current bus stop is",c)

print("Before Swap a=",a,"b=",b) print("Next bus stop is",n)

a = a + b enter current stop 16


Previous bus stop is 8
b = a – b
Current bus stop is 16
print("After Swap a=",a,"b=",b) Next bus stop is 32
Before Swap a=1 b=2 We can also do the previous Bus Stop Problem
After Swap a=2 b=1 using another operator called Bitwise Operators. Let
us see…
Ex 7.16 ( Using * and / operators )
LESSON - SEVEN
a,b = 1,2
print("Before Swap a=",a,"b=",b) BITWISE OPERATORS
a = a * b What is Bitwise Operator?
b = a / b Bitwise Operators are operators used to perform
a = a / b bitwise calculations on integers.

print("After Swap a=",a,"b=",b) Note : Bitwise operators work only on integers.

Before Swap a=1 b=2 There are six bitwise operators, those are

After Swap a=2 b=1  Bitwise AND


 Bitwise OR
Case Study : Bus Stop Problem  Bitwise NOT
 Bitwise XOR
 Bitwise right shift
 Bitwise left shift
Ex 7.18 (Bus Stop Problem using bitwise operators)
There are bus stops in a road each bus stop have its c=int(input("Enter current stop"))
own number. Bus station (initial) number is 0. Each
bus stop number is double of previous bus stop p = c >> 1
number. Current bus stop number is 16, n = c << 1
 What is the bus stop number before the print("Previous bus stop is",p)
current bus stop?
 What is the bus stop number next to the print("Current bus stop is",c)
current bus stop? print("Next bus stop is",n)
Ohhh… that is so simple. Okay let us do with a code
Enter current stop 16
Ex 7.17 (Bus Stop Problem by Arithmetic operators)
Previous bus stop is 8
c=int(input("enter current stop"))
Current bus stop is 16
p = c / 2
Next bus stop is 32
p = int(p)
n = c * 2
CONDITIONAL STATEMENTS 32

Ex 7.19 ( Swapping Using ^ ( XOR ) operator ) Ex 7.20 ( Membership Operators )

a = 1 text = "Welcome"
b = 2 print("Well" in text)
print("Before Swap a=",a,"b=",b) print("wel" in text)
a = a ^ b print("Wel" in text)
b = a ^ b print("come" not in text)
a = a ^ b False
print("After Swap a=",a,"b=",b) False

Before Swap a=1 b=2 True

After Swap a=2 b=1 False

SUMMARY OF BITWISE (for binary numbers) What if you want to check a person whether
he/she is belong to class 10A or not?
Ex 7.21 ( Membership Operators )

class_10A = ["John","Eden","Bob"]
print("john" in class_10A)
print("Lucas" not in class_10A)

False
True
What if you want to search a keyword in a text?
What if a user just want to evaluate some
LESSON - EIGHT calculation without using variables?
MEMBERSHIP OPERATORS LESSON - NINE
What is Membership Operators?
eval() FUNCTION
Membership operators are operators which are used
This is an in-built function available in python,
to check whether an element is present in a sequence
which takes the strings as an input. The strings which
of elements or not. Here, the sequence means strings,
we pass to it should, generally, be expressions. The
list, tuple, set and dictionaries.
eval() function takes the expression in the form of
There are two membership operators. i.e. string and evaluates it and returns the result.

❶ in operator: The in operators returns True if Ex 7.22 ( eval() function /Arithmetic Operator/ )
element is found in the collection of sequences. eval(’10 + 10′)
returns False if not found.
20
❷ not in operator: The not in operator returns True
if the element is not found in the collection of EXERCISE 7.6
sequence. returns False in found.
Create two integer variables "a" and "b" take input
from a user, then calculate their average by using
eval() function?
CONDITIONAL STATEMENTS 33

What if we want to take input from user? Ex 7.31 ( eval() function /math() function/ )

Ex 7.23 ( eval() function /Take inputs from a user/ ) from math import *

eval(input("Enter expression: ")) print(eval('log(1)'))

Enter expression: 0.0

20 - 12 + 3 * 4 / 3 EXERCISE 7.7
Calculate
12.0
■ ln(e)
Ex 7.24 ( eval() function /Compound Operator/ )
■ cos(90°)
a = 1
■ 10 the power of 5
eval('a += 2')
■ Square root of 625
SyntaxError: invalid syntax ■ Ceil and Floor of 6.5
Ex 7.25 ( eval() function /Unary Minus Operator/ ) Using eval() function?
a = 5
eval('-a ')

-5
Ex 7.26 ( eval() function /Relational Operator/ )

eval('1 > 2')

False
Ex 7.27 ( eval() function /Logical Operator/ )

eval('0 and 1')

0
Ex 7.28 ( eval() function /Bitwise Operator/ )

eval('2 << 3')

16
Ex 7.29 ( eval() function /Membership Operator/ )

s = "John"
eval('"Jo" in s')

True
Ex 7.30 ( eval() function /Identity Operator/ )

eval('1 is 2')

False

You might also like