0% found this document useful (0 votes)
5 views56 pages

Python Module 4-1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views56 pages

Python Module 4-1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Module 4

Conditional Statements in Python


Outline
4.1 Introduction to the if Statement
4.2 Relational Operators In Python
4.3 Grouping Statements: Indentation and Blocks
4.4 Python: It’s All About the Indentation
4.5 What Do Other Languages Do?
4.6 Which Is Better?
4.7 Python If Else Statement
4.8 Python Nested If Statement
4.9 Python Elif
Outline
4.10 Python Elif with AND Operator
4.11 One-Line if Statements
4.12 Conditional Expressions (Python’s Ternary Operator)
4.13 The Python pass Statement
4.14 Conclusion
4.15 Recommended Articles
Introduction to the if Statement
• From the previous tutorials in this series, you now have quite a bit of Python
code under your belt.
• Everything you have seen so far has consisted of sequential execution, in which
statements are always performed one after the next, in exactly the order
specified.
• But the world is often more complicated than that. Frequently, a program needs
to skip over some statements, execute a series of statements repetitively, or
choose between alternate sets of statements to execute.
• That is where control structures come in. A control structure directs the order of
execution of the statements in a program (referred to as the program’s control
flow).
• Here’s what you’ll learn in this module: You’ll encounter your first Python control
structure, the if statement.
Introduction to the if Statement
• In the real world, we commonly must evaluate information around us and then
choose one course of action or another based on what we observe:
 If the weather is nice, then I’ll go for a walk. (It’s implied that if the weather
isn’t nice, then I won’t go for a walk.)
• In a Python program, the if statement is how you perform this sort of decision-
making.
• It allows for conditional execution of a statement or group of statements based
on the value of an expression.
Introduction to the if Statement
• We’ll start by looking at the most basic type of if statement. In its simplest form,
it looks like this:
if <expr>:
<statement>
• In the form shown above:
 <expr> is an expression evaluated in a Boolean context, as discussed in the
section on Logical Operators.
 <statement> is a valid Python statement, which must be indented. (You will
see why very soon.)
• If <expr> is true (evaluates to a value that is “truthy”), then <statement> is
executed. If <expr> is false, then <statement> is skipped over and not executed.
• Note that the colon (:) following <expr> is required. Some programming languages
require <expr> to be enclosed in parentheses, but Python does not.
Introduction to the if Statement
• Here are several examples of this type of if statement:
x=0
y=5
if x < y: # Truthy
print('yes')
yes
if y < x: # Falsy
print('yes')
if x: # Falsy
print('yes')
if y: # Truthy
print('yes')
yes
Introduction to the if Statement
if x or y: # Truthy
print('yes')
yes
if x and y: # Falsy
print('yes')
if 'aul' in 'grault': # Truthy
print('yes')
yes
if 'quux' in ['foo', 'bar', 'baz']: # Falsy
print('yes')
Relational Operators In Python
Relational Operators In Python
• Relational operators in Python programming are also known as comparison
operators.
• They serve the basic purpose of conducting relational operations, i.e.,
comparisons between two operands.
• They hence facilitate the decision-making process in a program.
• Other uses of relational operators include controlling the program flow, filtering
data, etc.
• These operators can be used with numerical values, strings, and objects.
Relational Operators In Python
• Relational operators are used to compare the value of operands (expressions)
to produce a logical value. A logical value is either True or False.
Grouping Statements: Indentation and Blocks
• So far, so good. But let’s say you want to evaluate a condition and then do more than
one thing if it is true:
• If the weather is nice, then I will:
 Go for a walk
 Mow the lawn
 Weed the garden
• (If the weather isn’t nice, then I won’t do any of these things.)
• In all the examples shown before, each if <expr>: has been followed by only a single
<statement>. There needs to be some way to say “If <expr> is true, do all of the
following things.”
• The usual approach taken by most programming languages is to define a syntactic
device that groups multiple statements into one compound statement or block.
• A block is regarded syntactically as a single entity. When it is the target of an if
statement, and <expr> is true, then all the statements in the block are executed. If
<expr> is false, then none of them are.
Python: It’s All About the Indentation
• Virtually all programming languages provide the capability to define blocks, but they don’t
all provide it in the same way. Let’s see how Python does it.
• Python follows a convention known as the off-side rule, a term coined by British
computer scientist Peter J. Landin. (The term is taken from the offside law in
association football.)
• Languages that adhere to the off-side rule define blocks by indentation
(whitespace at the beginning of a line).
• Python is one of a relatively small set of off-side rule languages.
• Recall from the previous tutorial on Python program structure that indentation
has special significance in a Python program. Now you know why: indentation is
used to define compound statements or blocks.
• In a Python program, contiguous statements that are indented to the same level
are considered to be part of the same block.
Python: It’s All About the Indentation
• Thus, a compound if statement in Python looks like this:
1. if <expr>:
2. <statement>
3. <statement>
4. ...
5. <statement>
6. <following_statement>
• Here, all the statements at the matching indentation level (lines 2 to 5) are
considered part of the same block.
• The entire block is executed if <expr> is true, or skipped over if <expr> is false.
Either way, execution proceeds with <following_statement> (line 6) afterward.
Python: It’s All About the Indentation

• Notice that there is no token that denotes the end of the block. Rather, the end
of the block is indicated by a line that is indented less than the lines of the block
itself.
• Note: In the Python documentation, a group of statements defined by
indentation is often referred to as a suite. Here we use the terms block and suite
interchangeably.
Python: It’s All About the Indentation
• Consider this code:
if 'foo' in ['bar', 'baz', 'qux']:
print('Expression was true')
print('Executing statement in suite')
print('...')
print('Done.')
print('After conditional')
After conditional
• The four print() statements on lines 2 to 5 are indented to the same level as one
another. They constitute the block that would be executed if the condition were
true. But it is false, so all the statements in the block are skipped.
• After the end of the compound if statement has been reached (whether the
statements in the block on lines 2 to 5 are executed or not), execution proceeds to
the first statement having a lesser indentation level: the print() statement on line 6.
Python: It’s All About the Indentation
• Blocks can be nested to arbitrary depth. Each indent defines a new block, and each outdent
ends the preceding block. The resulting structure is straightforward, consistent, and intuitive.
• Here is a more complicated code:
# Does line execute? Yes No
# --- --
if 'foo' in ['foo', 'bar', 'baz']: # x
print('Outer condition is true')# x
if 10 > 20: # x
print('Inner condition 1') # x
print('Between inner conditions') # x
if 10 < 20: # x
print('Inner condition 2') # x
print('End of outer condition') # x
print('After outer condition') # x
Python: It’s All About the Indentation
Outer condition is true
Between inner conditions
Inner condition 2
End of outer condition
After outer condition
What Do Other Languages Do?
• Perhaps you’re curious what the alternatives are. How are blocks defined in languages
that don’t adhere to the off-side rule?
• The tactic used by most programming languages is to designate special tokens that mark
the start and end of a block. For example, in Perl blocks are defined with pairs of curly
braces ({}) like this:
What Do Other Languages Do?
• C/C++, Java, and a whole host of other languages use curly braces in this way.

• Other languages, such as Algol and Pascal, use keywords begin and end to enclose blocks.
Which Is Better?
• Better is in the eye of the beholder. On the whole, programmers tend to feel
rather strongly about how they do things. Debate about the merits of the off-
side rule can run pretty hot.
On the plus side:
 Python’s use of indentation is clean, concise, and consistent.
 In programming languages that do not use the off-side rule, indentation of code is
completely independent of block definition and code function. It’s possible to write
code that is indented in a manner that does not actually match how the code
executes, thus creating a mistaken impression when a person just glances at it. This
sort of mistake is virtually impossible to make in Python.
 Use of indentation to define blocks forces you to maintain code formatting
standards you probably should be using anyway.
Which Is Better?
On the negative side:
 Many programmers don’t like to be forced to do things a certain way. They tend to
have strong opinions about what looks good and what doesn’t, and they don’t like
to be shoehorned into a specific choice.
 Some editors insert a mix of space and tab characters to the left of indented lines,
which makes it difficult for the Python interpreter to determine indentation levels.
On the other hand, it is frequently possible to configure editors not to do this. It
generally isn’t considered desirable to have a mix of tabs and spaces in source
code anyhow, no matter the language.
• Like it or not, if you’re programming in Python, you’re stuck with the off-side
rule. All control structures in Python use it, as you will see in several future
tutorials.
• For what it’s worth, many programmers who have been used to languages with
more traditional means of block definition have initially recoiled at Python’s way
but have gotten comfortable with it and have even grown to prefer it.
Python If Else Statement
• Now you know how to use an if statement to conditionally execute a single statement or a
block of several statements. It’s time to find out what else you can do.
• Sometimes, you want to evaluate a condition and take one path if it is true but specify an
alternative path if it is not. This is accomplished with an else clause:
if <expr>:
<statement(s)>
else:
<statement(s)>
• If <expr> is true, the first suite is executed, and the second is skipped. If <expr> is false, the
first suite is skipped and the second is executed.
• Either way, execution then resumes after the second suite. Both suites are defined by
indentation, as described before.
Python If Else Statement
• In this example, x is less than 50, so the first suite (lines 4 to 5) are executed, and the second
suite (lines 7 to 8) are skipped:
x = 20
if x < 50:
print('first suite')
print('x is small')
else:
print('second suite')
print('x is large')
first suite
x is small
Python If Else Statement
• Here, on the other hand, x is greater than 50, so the first suite is passed over, and the second
suite executed:
x = 120
if x < 50:
print('first suite')
print('x is small')
else:
print('second suite')
print('x is large')
first suite
x is large
Python If Else Statement
• Here's an example of how to use an if-else statement to check if a number is positive or
negative:
x = int(input(‘Please enter an integer number’))
if num >= 0:
print("The number is positive.")
else:
print("The number is negative.")
Python If Else Statement
• Here's an example of how to use an if-else statement to check if a number is even or odd:
x = int(input(‘Please enter an integer number’))
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Simple Login Screen
• Here’s a very simple text-based login screen in Python that runs in the terminal:
# Predefined username and password
storedUser = "admin"
storedPass = "B@dgate"
userName = input("Enter username:")
passWord = input("Enter password:")
#Compare with predefined credentials
if userName == storedUser and passWord == storedPass:
print("Successful login! Welcome", userName )
else:
print("Invalid username or password")
Simple Login Screen V2 (Masking the password)
• We can use Python’s built-in getpass module to mask (hide) the password when the user types it.
import getpass
# Predefined username and password
storedUser = "admin"
storedPass = "B@dgate"
print("=" * 30)
print(" Welcome to Secure Login")
print("=" * 30)
userName = input("Enter username:")
passWord = [Link]("Enter password: ") # hides input
#Compare with predefined credentials
if userName == storedUser and passWord == storedPass:
print("Successful login! Welcome", userName )
else:
print("Invalid username or password")
Simple Login Screen V2 (Masking the password)
• [Link]() hides the password as you type (no * shown, just blank).
• Works in terminal/command prompt.
• May not work inside some IDE consoles (like Pycharm and IDLE), but works fine in cmd,
PowerShell, Linux terminal, or macOS terminal.
• In the following slides you will find how to adjust the run configurations to make it work as
expected.
Simple Login Screen V2 (Masking the password)
Right click on your source code screen as the following:
Simple Login Screen V2 (Masking the password)
Click on the (Modify Options) link which is located at the top right section in this screen
Simple Login Screen V2 (Masking the password)
Select the option (Emulate terminal in output console) as shown in the following screen:
Simple Login Screen V2 (Masking the password)
Click on the (OK) button to apply your run configurations changes as shown in the following
screen:
Simple Login Screen V3 (showing *)
• By default, getpass completely hides the input — it doesn’t support showing *.
• To get * while typing, the (pwinput) library is designed exactly for this (password input with
masking like *).
• You need to install (pwinput) module first by typing the following command into cmd or
PowerShell screen:
• pip install pwinput
Simple Login Screen V3 (showing *)
• By default, getpass completely hides the input — it doesn’t support showing *.
• To get * while typing, the pwinput library is designed exactly for this (password input with masking like *).
import pwinput
# Predefined username and password
storedUser = "admin"
storedPass = "B@dgate"
print("=" * 30)
print(" Welcome to Secure Login")
print("=" * 30)
userName = input("Enter username:")
passWord = [Link]("Enter password: ", mask="*") # shows * while typing
#Compare with predefined credentials
if userName == storedUser and passWord == storedPass:
print("Successful login! Welcome", userName )
else:
Python Nested If Statement
• A nested if is an if statement that is the target of another if statement. Nested if statements
mean an if statement inside another if statement.
• Yes, Python allows us to nest if statements within if statements. i.e., we can place an if
statement inside another if statement.
• Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Python Nested If Statement
• In this example, we use nested if statements to check if a year is a leap year.
• A year is a leap year if it is divisible by 4, except for century years (years ending with 00) that are
not divisible by 400.
year = int(input(‘Please enter a year’))
if year % 4 == 0:
if year % 100 == 0: # if the year is century
if year % 400 == 0:
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
else: # if the year is not century
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
Python Elif
• There is also syntax for branching execution based on several alternatives.
• For this, use one or more elif (short for else if) clauses.
• Python evaluates each <expr> in turn and executes the suite corresponding to the first that is
true.
• If none of the expressions are true, and an else clause is specified, then its suite is executed:
if <expr>:
<statement(s)>
elif <expr>:
<statement(s)>
elif <expr>:
<statement(s)>
...
else:
<statement(s)>
Flowchart of Elif Statement in Python
• Let’s look at the flow of control in if-elif-else ladder:
Python Elif
• An arbitrary number of elif clauses can be specified.
• The else clause is optional. If it is present, there can be only one, and it must be
specified last.
• An if statement with elif clauses uses short-circuit evaluation, analogous to what
you saw with the and and or operators. Once one of the expressions is found to
be true and its block is executed, none of the remaining expressions are tested.
Python Elif
• We can build an intelligent system by giving choice to the user and taking the user input to proceed with
the choice.
value1 = input("Please enter first integer:\n")
value2 = input("Please enter second integer:\n")
num1 = int(value1)
num2 = int(value2)
choice = input("Enter 1 for addition.\nEnter 2 for subtraction.\nEnter 3 for Multiplication.:\n")
choice = int(choice)
if choice == 1:
print(f'You entered {num1} and {num2} and their addition is {num1 + num2}')
elif choice == 2:
print(f'You entered {num1} and {num2} and their subtraction is {num1 - num2}')
elif choice == 3:
print(f'You entered {num1} and {num2} and their multiplication is {num1 * num2}')
else:
print("Wrong Choice, terminating the program.")
Python Elif
• In this example, we use an if-elif-else statement to assign a letter grade based on a numerical score.
score = int(input("Please enter the score of student:\n"))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print("Your grade is:", grade)
Python Elif with AND Operator
• Now say you want to make sure that two conditions are met—meaning that they’re
both true—before running a certain piece of code.
• To try this out, suppose you need to get the age of a user running your script, process
that information, and display to the user their current life stage.
age = int(input("Enter your age: "))
if age >= 0 and age <= 9:
print("You are a child!")
elif age > 9 and age <= 18:
print("You are an teenager!")
elif age > 18 and age <= 65:
print("You are an adult!")
elif age > 65:
print("Golden ages!")
One-Line if Statements
• It is customary to write if <expr> on one line and <statement> indented on the following
line like this:
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>
• There can even be more than one <statement> on the same line, separated by semicolons:
if <expr>: <statement_1>; <statement_2>; ...; <statement_n>
• If <expr> is true, execute all of <statement_1> ... <statement_n>. Otherwise, don’t execute
any of them.
• The semicolon separating the <statements> has higher precedence than the colon following
<expr>—in computer lingo, the semicolon is said to bind more tightly than the colon.
• Thus, the <statements> are treated as a suite, and either all of them are executed, or none of
them are
One-Line if Statements
if 'f' in 'foo': print('1'); print('2'); print('3')
1
2
3
if 'z' in 'foo': print('1'); print('2'); print('3')
• While all of this works, and the interpreter allows it, it is generally discouraged on the grounds that it leads to
poor readability, particularly for complex if statements. PEP 8 specifically recommends against it.
• As usual, it is somewhat a matter of taste. Most people would find the following more visually appealing and
easier to understand at first glance than the example above:
if 'f' in 'foo':
print('1')
print('2')
print('3')
if 'z' in 'foo':
print('1')
print('2')
print('3')
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.)
• Conditional expressions were proposed for addition to the language in PEP 308 and green-
lighted by Guido in 2005.
• In its simplest form, the syntax of the conditional expression is as follows:
<expr1> if <conditional_expr> else <expr2>
• This is different from the if statement forms listed above because it is not a control
structure that directs the flow of program execution. It acts more like an operator that
defines an expression.
• 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>.
• Notice the non-obvious order: the middle expression is evaluated first, and based on that
result, one of the expressions on the ends is returned. Here are some examples that will
hopefully help clarify:
Conditional Expressions (Python’s Ternary Operator)
• Here are some examples that will hopefully help clarify:
age = 12
s = 'minor' if age < 21 else 'adult'
Print(s)
minor
• The ternary operator in Python is simply a shorter way of writing an if and if...else
statements.
• You could use a standard if statement with an else clause:
user_score = 90
if user_score >= 50:
print("Success")
else:
print("Fail")
Success
Conditional Expressions (Python’s Ternary Operator)
• You can shorten the if...else statement using the ternary operator syntax.
user_score = 90
print("Success") if user_score >= 50 else print("Fail")
Success
• Conditional expressions also use short-circuit evaluation like compound logical expressions.
Portions of a conditional expression are not evaluated if they don’t need to be.
• In the expression <expr1> if <conditional_expr> else <expr2>:
 If <conditional_expr> is true, <expr1> is returned and <expr2> is not evaluated.
 If <conditional_expr> is false, <expr2> is returned and <expr1> is not evaluated.
• As before, you can verify this by using terms that would raise an error:
'foo' if True else 1/0
foo
1/0 if False else 'bar'
bar
• In both cases, the 1/0 terms are not evaluated, so no exception is raised.
Conditional Expressions (Python’s Ternary Operator)
• Conditional expressions can also be chained together, as a sort of alternative if/elif/else structure,
as shown here:
x=3
s = ('foo' if (x == 1) else
'bar' if (x == 2) else
'baz' if (x == 3) else
'qux' if (x == 4) else
'quux'
)
Print(s)
baz
• It’s not clear that this has any significant advantage over the corresponding if/elif/else
statement, but it is syntactically correct Python.
The Python pass Statement
• Occasionally, you may find that you want to write what is called a code stub: a placeholder for
where you will eventually put a block of code that you haven’t implemented yet.
• In languages where token delimiters are used to define blocks, like the curly braces in Perl and
C, empty delimiters can be used to define a code stub.
• For example, the following is legitimate Perl or C code:

• Here, the empty curly braces define an empty block. Perl or C will evaluate the expression x,
and then even if it is true, quietly do nothing.
The Python pass Statement
• Because Python uses indentation instead of delimiters, it is not possible to specify an empty
block.
• If you introduce an if statement with if <expr>:, something has to come after it, either on the
same line or indented on the following line.
• Consider this script [Link]:

• If you try to run [Link], you’ll get this:


The Python pass Statement
• The Python pass statement solves this problem. It doesn’t change program behavior at all.
• It is used as a placeholder to keep the interpreter happy in any situation where a
statement is syntactically required, but you don’t really want to do anything:

• Now [Link] runs without error:


Conclusion
• Conditional statements (if, else, and elif) are fundamental programming constructs
that allow you to control the flow of your program based on conditions that you
specify.
• They provide a way to make decisions in your program and execute different code
based on those decisions.
• In this module, we have seen several examples of how to use these statements in
Python, including checking if a number is even or odd, assigning a letter grade based
on a numerical score, and checking if a year is a leap year.
• By mastering these statements, you can create more powerful and versatile
programs that can handle a wider range of tasks and scenarios.
• It is important to keep in mind that proper indentation is crucial when using
conditional statements in Python, as it determines which code block is executed
based on the condition.
• With practice, you will become proficient in using these statements to create more
complex and effective Python programs.
Recommended Articles
• How to Use Conditional Statements in Python – Examples of i
f, else, and elif ([Link])
• [Link]
• [Link]
• [Link]
• [Link]
thon/
• [Link]
-statement-in-python/
Recommended Articles
• Relational Operators In Python | 6 Types & Examples // Unstop
• Python Tutorials: Relational/ Comparison Operators In Python - DevOpsSchool.
com

You might also like