If else statements
In Python you can define conditional statements, known as if-statements.
A block of code is executed if certain conditions are met.
A block of code is executed if certain conditions are met.
If statements
Consider this application, it executes either the first or second code depending on the value of x.
If you set x to be larger than 10, it will execute the second code block. We use indentation (4 spaces) to define the blocks.
A little game:
A variable may not always be defined by the user, consider this little game:
A variable may not always be defined by the user, consider this little game:
Conditional operators
A word on conditional operators
Operator | Description |
!= | not equal |
== | equals |
> | greater than |
< | smaller than |
Do not confuse the assignment operator (=) with the equals operator (==).
Nesting
The most straightforward way to do multiple conditions is nesting:
This can quickly become difficult to read, consider combining 4 or 6 conditions. Luckily Python has a solution for this, we can combine conditions using the andkeyword.
Sometimes you may want to use the or operator.
Cool
ReplyDeletethanks
Delete