Python control statements

The interesting thing about Boolean values (especially expressions that return Boolean values) is that we can make decisions and take different paths based on their differencesTrueorFalsevalue.

inPythonWe useifstatement:

condition = True

if condition == True: # do something

When the condition test is resolvedTrue, As in the above case, its code block will be executed.

What is a block? A block is a part that is indented one level (usually 4 spaces) on the right:

condition = True

if condition == True: print(“The condition”) print(“was true”)

The block can consist of a single line or multiple lines, and end when you move back to the previous indentation level:

condition = True

if condition == True: print(“The condition”) print(“was true”)

print(“Outside of the if”)

combine withifYou can have oneelseBlock if the condition is testedifResult toFalse:

condition = True

if condition == True: print(“The condition”) print(“was True”) else: print(“The condition”) print(“was False”)

And you can have different connectionsifAnd checkelif, If the previous check wasFalse:

condition = True
name = "Roger"

if condition == True: print(“The condition”) print(“was True”) elif name == “Roger”: print(“Hello Roger”) else: print(“The condition”) print(“was False”)

In this case, ifconditionYesFalsewithnameThe variable value is "Roger".

in aifDeclare that you can only have oneifwithelseCheck, but there are multiple serieselifan examination:

condition = True
name = "Roger"

if condition == True: print(“The condition”) print(“was True”) elif name == “Roger”: print(“Hello Roger”) elif name == “Syd”: print(“Hello Syd”) elif name == “Flavio”: print(“Hello Flavio”) else: print(“The condition”) print(“was False”)

ifwithelseIt can also be used in inline format, which allows us to return one value or another based on conditions.

example:

a = 2
result = 2 if a == 0 else 3
print(result) # 3

More python tutorials: