Conditionals - Creating Code That Uses 'If, Then' Logic...
The most fundamental aspect of coding is the ability to write code that performs a function if a criteria is met, else it does something different. At its simplest form, we need to be able to know how to operate these blocks of code that will get out program the way we need.
On Day 9, of the 30 Days of Python Course, we go over conditionals. A term that is used in programming to personify the if, then logic. I was already quite familiar with this framework, as I had spent some time during my studies on it. The best explanation that I can offer is to think about a reward system, if you do ‘x’, you get ‘y’; this is how we want to create programs.
We need our programs to mimic the human thought process as closely as possible, which enhances user experience. It also helps programmers code as the syntax or flow of writing code is made simple. When it comes to using conditional code blocks in our code, we have 2 methods that we can use:
- Conditional Execution - if condition ‘x’ is true, then run code ‘y’
- Recursive / Repetitive Execution - if condition ‘x’ is true, then run code ‘y’, ‘x’ times.
I brought to attention the concept of ‘loops’ in one of my earlier posts; however, while it is important to understand, I will disclose that topic in more depth on Day 10. Right now, we just need to know that a conditional execution is having one or more blocks of code be executed if a certain condition is made True, and repetitive/recursive execution is having a loop that begins when a certain expression is made true.
Creating An ‘If Statement’
I’ve included a complete example below, so that we can grasp the concept from the start. Once you begin to code in this style, you begin to see the nature of programming and it’ll start to entice you.
1
2
3
4
5
6
if condition1: # If this condition is true
code block # Do this one
elif condition2: # Else, if this condition is true,
code block # Do this
else: # If none are true,
code block # Do this
For a more comprehensive example:
1
2
3
4
5
6
7
8
9
10
11
user_input = input("Type input: ").capitalize()
if user_input == "Hi":
print("Hey there!")
elif user_input == "Bye":
print("Good bye!")
else:
print("Please type 'Hi' or 'Bye'")
#Type input: Hi
#Hey there!
I have used an input function to recognise user inputs, then I have introduced 3 different conditions. The last of which is almost like an escape clause, if both conditions aren’t satisfied then tell the user, please only type ‘x’ or ‘y’. You can think of it as an error prompt, though we have a full module on this later.
If we’d like a simpler program, one for True and one for False, we’d only use if, else.
1
2
3
4
5
6
7
8
user_input = input("Type input: ").capitalize()
if user_input == "Hi":
print("Hey there!")
else:
print("Goodbye!")
#Type input: Hi
#Hey there!
Note: Using the input function probably isn’t the best idea, as you can enter anything and it will just respond with ‘Goodbye’ other than ‘Hi’.
Something I did learn that is new from this topic, is that you can also write on one line. This becomes useful later on or if you end up doing the exercises.
1
2
3
user_input = input("Type input: ").capitalize()
print("Hello World") if user_input == "Hi" else print("Goodbye")
For this we just enter the initial code block to start with then our conditionals.
Nested Conditions
Using nested if statements is especially helpful when we have conditions that we then need to also have conditions on too. Sounds strange, I know. However, it gives us more control over how we code.
1
2
3
4
5
6
7
8
9
10
a = 0
if a > 0:
if a % 2 == 0:
print('A is a positive and even integer')
else:
print('A is a positive number')
elif a == 0:
print('A is zero')
else:
print('A is a negative number')
Taken from the course
Using Condition Operators on Conditions…
While having nested conditions is useful, we may want to avoid writing code like that. This helps with debugging and code refactoring, so it’s a good idea to incorporate as much programming syntax that we can use which will help with programming later.
Note: Keep in mind that sometimes you may still want to use nested loops as they may serve as a proper function later on.
1
2
3
4
5
6
if x == True and y == False:
code
elif x == True and y == "this":
code
else:
code
This is typically how we would write conditions using operators, think of having a program which selects a number between one and ten. You then want the program to say “It’s within these numbers” and so would use an operator in a condition to specify a range of numbers i.e if x is > y and x is < y: code.
Using the same analogy we can also use the ‘or’ operator.
1
2
3
4
if x == True or y == True:
code
else:
code
Summary
This concludes conditionals in Python, it’s an important concept that we’d need to take across. It helps deepen our understanding of the logic that is used throughout the Python program. Helping both the developers and users to be able to create and use the program.