Python Module 4-1
Python Module 4-1
• 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]: