2k4uDJTYDelcAF0bKUnVDU

Python Basics Lesson 1: Conditionals

article featured image

Conditional Statements in Python perform different computations or actions depending on whether a specific Boolean constraint evaluates to TRUE or FALSE. Conditional statements are handled by IF statements in Python.

An IF statement is written like this: if : elif : else:

We see here that this will evaluate the expressions in order from the if, to the elif, then to the else, stopping at the first expression that evaluates to TRUE and will then execute the statements in that branch. If no expressions evaluate to TRUE it will execute the statement in the else branch.

For example: if (x < y): st = "x is less than y" elif (x > y): st = "x is greater than y" else: st = "x is equal to y" print(st)

In this example, if we consider x = 2 and y = 8 we see that the first branch of the if statement evaluates to TRUE. This sets the st variable to "x is less than y" then prints that to the console. Now if we consider x = 8 and y = 2 we see that the first branch evaluates to FALSE. This means that it will now look at the next branch. This next branch(x > y) evaluates to TRUE, therefore the st variable will be set to "x is greater than y". Likewise if we consider the case where x = 2 and y = 2 we see that neither the first nor second branch evaluate to TRUE and we run the statement in the else branch.

There are many ways to both simplify and complicate these conditional statements, such as nesting IF statements, and using single line conditionals. A nested IF statement simply is an IF statement inside another IF statement. You can nest as many IF statements together as you want and need with the caveat that it will hinder readability and possibly, to a lesser extent, performance depending on the level of complexity. For example:

 if <expression>:

if : elif : else: elif : else:

On the other hand you can create single line conditionals, which can shorten your code and possibly slightly increase performance, at the cost of readability. For example:

st = "x is less than y" if (x < y) else "x is greater than or equal to y"

Tags:

Comments

Leave a comment