MY Programming

Python Basics Tutorial 3 if elif else conditions

Python Icon

Python checks the Conditions from Top to Botom

As soon as one Condition is true, it runs that Block and skips the rest

The else is optional and runs only if none of the previous Conditions were true

 

How Conditions work:

A Condition is any Expression that evaluates to true or false

 

Comparison Operators: 

 

Operator                   Meaning                            Example

==                            Equal to                              x == 5

!=                              Not equal to                      x != 5

>                               Greater                               x >  5

>                               Less than                            x  <  5

>=                             Greater than or equal        x >= 5

<=                             Less than equal                  x <= 5

 

Example:

x = input('Age')

 

if  x  >= 90:

     print('Grade: A')

elif x >= 80:

     print('Grade: B')

else:

      print('Grade: F')

 

Common Mistakes:

1. Forgetting the colon    -> SyntaxError

2. Wrong intentation       -> IntetntationError or unexpected behavior

3. Using = instead of ==  -> This assingns a Value instead of comparing

4. Mixing tabs and spaces -> Can cause IntentationError

 

How do you rate this article?

2


Slash13
Slash13

I like making music, programming, gaming, blogging.


MY Programming
MY Programming

In this blog i post my programms.

Publish0x

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.

Page not displaying correctly?