MPDA’22
October 21, 2021
Indentation refers to the placement of text farther to the right (or left), to separate it from it’s surrounding text.
Consider these two lines
This is a normal line
This line is indented.
This line has double indentation
Python is a programing language that is indentation aware.
This means that the indentation of each line has a specific meaning.
We use indentation to signal when a piece of code is inside another.
If you insert a random space before a line of code in Python, you will get an error
if
statements?‘if’ statements provide a way to run a portion of code only if a specific condition is met.
Conditions will always answer YES or NO questions. For example:
Is
x
smaller than3
?
Is
x
equals to5
?
Operator | Name | Example |
---|---|---|
== | Equals | (a == b) |
!= | Not Equals | (a != b) |
> | Bigger than | (a > b) |
< | Smaller than | (a < b) |
>= | Bigger or equals | (a >= b) |
<= | Smaller or equals | (a <= b) |
you can also specify a section of code that will run if the condition is not met, using the else
keyword:
concatenating several conditions is possible using the and
/or
keywords
and create even more complex conditions by concatenating them using parenthesis ()
:
The result of a condition is always a boolean bool
, so you can save it in a variable too.
first = (x< 3 and y < 4)
second = (x > 6 and y > 9)
if(first or second):
print("The result will be the same
as the previous example")
This will greatly simplify your code and make it more readable.
you can get the oposite of value of a given condition (or boolean) with the not()
keyword.
Finally, you can chain conditions together using the elif
keyword (short for else if
):
When you chain conditions using if
-> elif
-> else
, only ONE of those code blocks will run.
If several conditions are met, the first one will have preference.
if
statements can also be nested (notice the indentation):