Python 3 If Statement - With complete source code
Applications rarely follow one flow during execution. Applications usually have to make decisions based on which path to take based on some conditions. for example, let's say a user wants to login to the application. The application will have to determine if the authentication is valid then grant access or deny access if the authentication fails.
This is where control structures come in. In this lesson, we will look at how the if statement works in python
Topics to be covered
We will cover the following topics in this lesson.
- If statement pseudocode
- If statement syntax
- Logical operators
- Simple console application that allows user to select an option then take appropriate action.
If statement pseudocode
The pseudocode for the simplest if statement is as follows
if condition is true thenexecute codeend if
- The above statement only executes the code within the if statement if the condition is true.
Sometimes, we want to execute some code regardless of the condition. This is where the
else part comes in.
The following is the pseudocode for the if... else statement.
if condition is true thenexecute code for the true pathelseexecute code for the false pathend if
conditionis an expression that evaluates to either
false. The code that comes immediately after the condition is executed if the expression for the
conditionevaluates to true
elsethe code for the
falsepath is executed.
If statements can also evaluate multiple conditions to decide on the code to execute.
The following is the pseudocode for multiple conditions that need to be evaluated.
if condition_1 is true thenexecute code for condition_1else if condition_2 is true thenexecute code for condition_2elseexecute default code if everything else failsend if
If statement syntax
In this section, we will look at how to implement the
if statement in python.
The syntax is as follows
condition_1 = Trueif condition_1:print('if condition is true')
condition_1 = Truewe define a variable called
condition_1and set its value to
True. Remember to always capitalize the letter
Truebecause python is case sensitive.
if condition_1:is a standard python syntax for defining if conditions. We start with the
ifkeyword followed by a condition that must evaluate to either
Falsethen we end with a full colon
print('if condition is true')represents the code that is within the if statement. The code must always be indented under the
if condition:block. To end the if statement block, you simply remove the indenting.
Let's now look at the syntax for if... else
condition_1 = Falseif condition_1: print('condition_1 is true')else: print('condition_1 is false')
condition_1 = Falsewe define a variable
condition_1and we assign a value of
if condition_1:evaluates our condition.
else:we use the
elsekeyword followed by the full colon
:to define the else block. The code under
elseis also indented just like we did if the condition is true. The
elsekeyword is aligned along the same vertical as the
Let's now look at the syntax for the
if statement with multiple conditions.
condition_1 = Truecondition_2 = Trueif condition_1: print('condition_1 is true')elif condition_2: print('condition_2 is true')else: print('all conditions are false')
if condition_1:evaluates the first condition to see if it is true.
elif condition_2:defines the else if condition. We use the keyword
eliffor else if statement then we end with the full colon ':'.
else:defines the block of code that must be executed if all of the conditions evaluate to false.
Executing the above code gives the following results.
condition_1 is true
Notice only one line has been printed even if both conditions are true. This is because once the first condition evaluates to true, python stops evaluating the other condition(s) that we define below the condition that evaluates to true.
Logical and comparison operators
Logical operators allow us to work with multiple conditions in the same expression. Let's suppose that we are working on a loan approval system. We can check the customer's earning potential and credit score to determine whether they qualify or not.
The following are the logical operators that we will deal with
- and - this logical operator evaluates to true if both conditions are true. if any of the conditions is false then it will evaluate to false. Using our above example, good credit score with no earning potential is bad, good earning potential but bad credit score is also bad. we only need to approval for customers who have both good credit score and earning potential.
- or - this logical operator evaluates to true if one of the conditions or both are true. for example, let's say we want to reset the password for the user. we can ask them for either the username or email address to determine that the user is legit.
Let's now look at a practical example.
condition_1 = Truecondition_2 = Trueif condition_1 and condition_2: print('duff beer')
condition_1 = True; condition_2 = Truedefines two conditions whose values have been set to true.
if condition_1 and condition_2:uses the
andlogical operator to evaluate both conditions at the same time.
Running the above code produces the following results.
Let's now modify the code to the following
condition_1 = Truecondition_2 = Falseif condition_1 and condition_2: print('duff beer')
The above code does not print
duff beer because one of our conditions is false.
Let's now look at comparison operators, just like the name suggests, they compare things. We will explore the following operators
==this operator is used to compared two items like
if condition == True. Note: the single equal sign
=is used to assign values while the double
==is used to compare them.
!=this is the not equal to operator. We can use it to compare two items and if they are not equal then
Trueis return else
The following examples show you how to
Console menu application using if statement
Our application will print out a simple heading and a couple of options with index numbers. The application will then ask the user to enter a number that corrects to the option index then use an if statement to print out the option that the user has selected.
The code is as follows
title = 'Database CRUD Application'print('*' * len(title))print(title)print('*' * len(title))print('')print('Select an option by entering the option number\n')options = """1. List all records2. Search for a record3. Create new record4. Update record5. Delete record6. Quit"""print(options)selection = input('Enter your selection: ')if selection == '1': print('You selected "List all records"')elif selection == '2': print('You selected "Search for record"')elif selection == '3': print('You selected "Create new record"')elif selection == '4': print('You selected "Update record"')elif selection == '5': print('You selected "Delete record"')elif selection == '6': print('You selected "Quit Application"')
Running the above code produces the following results
Let's look at another example that uses the
We will create a list of numbers from 0 to 10 then we will only print out even numbers from the list.
numbers = list(range(11))for number in numbers: if number % 2 == 0: print(number)
numbers = list(range(11))generates a list of numbers from
rangefunction and then uses the
listfunction to convert the results to a list.
for number in numbers:loops through each number in the list and assigns the value to a local for loop variable
if number % 2 == 0:the
ifstatement divides the number by 2 and sees if the remainder is
0indicating that it is an even number. Notice how we are using the comparison operator
expressionwhich is the condition. As you can see, conditions can be simple or complex expressions
Modify the above program to print only odd numbers and share your answer in the comments section. You can share even if other students have already shared.
If statements allow us to control the execution flow of the program. The simplest form of the
if statement has only a single block of code which is executed if the statement is true. The next simplest form has an
else part that is executed if the condition is false. The
elif statement is used to set a condition if the first condition is false.
If you enjoyed this lesson then show us your appreciation by creating a free accounts on our site. As always we appreciate your comments down below.