Python Basics
Python Basics
Statements
Outline
Nested Conditionals
Multi-way Decision Statements
else-if statement vs if-ifStatement.
Conditional Expressions
Errors in Conditional Statements
Flow chart vs. Python code
input ()
print()
Expressions / statements
if else
3
Conditional processing
Python has several types of selection statements:
One-way if statements,
Two-way ifelse statements,
Nested if statements,
Multi-way if-elif-else statements and
Conditional expressions.
4
A one-way if statement
if Statements executes the statements if
the condition is true.
5
If-Statement Example
Two-Way if-else Statements
A one-way if statement takes an action if the specified condition is True.
If the condition is False, nothing is done.
But what if you want to take one or more alternative actions when the condition is
False?
You can use a two-way if-else statement.
The actions that a two-way if-else statement specifies differ based on
whether the condition is True or False.
Here is the syntax for a two-way if-else statement:
if boolean-expression:
statement(s)-for-the-true-case
else: A two-way if-else statement
decides which statements to
statement(s)-for-the-false-case execute based on whether the
condition is true or false.
7
If-else Statement
Nested if and Multi-Way if-elif-else
Statements
9
Nested if and Multi-Way if-elif-else
Statements
10
Nested if and Multi-Way if-elif-else
Statements
11
Multiway-if-elif-else: Example
Multiway-if-elif-else: Example
Nested if and Multi-Way if-elif-else
Example
Conditional Expressions
Conditional expressions are in a completely different style.
The syntax is:
expression1 if boolean-expression else expression2
Example: y = 1 if x > 0 else -1
▪ Same as
if x > 0:
y=1 A conditional
else: expression evaluates an
y = -1
expression based on a
condition.
15
Common Errors
Common Errors
Which is
correct and
equivalent?
Which
is
better?
Practice Example
Nested Conditionals
Multi-way Decision Statements
else-if statement vs if-ifStatement.
Conditional Expressions
Errors in Conditional Statements