Conditional Statement

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 7

BCA1111C03:

Introduction to Programming using Python

Priti Patel
Department of Computer Applications
Conditional Statements
In programming and scripting languages, conditional
statements or conditional constructs are used to perform
different computations or actions depending on whether
a condition evaluates to true or false. (Please note that
true and false are always written as True and False in
Python.)
The condition usually uses comparisons and arithmetic
expressions with variables.
These expressions are evaluated to the Boolean values
True or False.
The statements for the decision taking are called
conditional statements, alternatively they are also known
as conditional expressions or conditional constructs.
If statement
The general form of the if statement in Python looks like this:
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
If the condition "condition_1" is True, the statements in the
block statement_block_1 will be executed.
If not, condition_2 will be executed.
 If condition_2 evaluates to True, statement_block_2 will be
executed, if condition_2 is False, the statements in
statement_block_3 will be executed.
Indentation is Important
Python relies on indentation (whitespace at the
beginning of a line) to define scope in the code. Other
programming languages often use curly-brackets for
this purpose.
One-Line if Statements
if <expr>:
<statement>
But it is permissible to write an entire if statement on
one line. The following is functionally equivalent to
the example above:
if <expr>: <statement>
Conditional Expressions (Python’s Ternary
Operator)
Python supports one additional decision-making entity
called a conditional expression. (It is also referred to as a
conditional operator or ternary operator in various
places in the Python documentation.)
In its simplest form, the syntax of the conditional
expression is as follows:
<expr1> if <conditional_expr> else <expr2>
In the above example, <conditional_expr> is evaluated
first. If it is true, the expression evaluates to <expr1>. If it
is false, the expression evaluates to <expr2>.
Nested if
When there is if statement inside another if statement
then it is known as nested if.
if <expr>:
if <expr>:
if <expr>:
<statement>
else:
<statement>
else:
<statement>
else:
<statement>

You might also like