Python - Unit 2 Python Conditional Statements
Python - Unit 2 Python Conditional Statements
(Autonomous)
Department of Artificial Intelligence & Data Science
Year/Dept: I/AI&DS & I/AI&ML
Unit 2 Notes :
Topics: Conditional Statements, With Alternative Conditions, Conditional Statements
with Alternative Conditions, chained conditional and nested conditionals
Conditional statements checks for one condition before executing some code:
Example with syntax:
We can expand on this syntax to check for an alternative condition with an elif statement:
If the first condition provided with the if statement is not satisfied, then Python will check the
condition provided with the elif statement.
If the condition for elif is satisfied, then the code provided with it will execute.
However, if neither the if nor elif conditions are satisfied, then the code provided with else will
execute.
Syntax:
Chained Condition:
Chained conditional is a conditional that contains a series of alternative branches using if, elif
and else statements that are all indented at the same depth. There is no nesting in chained
conditional. On the other hand, nested conditional is where one conditional is nested within
another conditional.
Both conditions have to be satisfied in order for the code provided with the if statement to be
executed.
This means that if one condition is not satisfied, then the conditional statement executes the
code provided with else.
Syntax:
2. Check For At Least One Condition Using or
We can also write conditional statements that check whether at least one condition is true by
including or between two conditions.
Only one condition has to pass in order for the conditional statement to execute code provided
with if.
Example:
Chained Conditionals
The or keyword allows us to check if one of two conditions is true. If one or both of the
conditions are true then then entire condition will be true. If both of the conditions are false
then the entire condition is false.
The not keyword allows us to check if an entire condition is false. If the condition is false it
will result in a true value. If the condition is true it will give us a false value (you can think of
it as reversing the condition).
Nested Statements
Now that we learnt about some basic logic and control structures in python we can move on to
nesting. Nesting is simply putting code inside of other code. For example placing an if
statement inside of an already existing if statement.
Prepared by,
Rohini A,
AP / AI&DS