Tuesday, December 12, 2017

If Statements in Python

If Statement is very simple in Python.Let me give you an example.

number = 5
if number == 5:
       print("Number is 5")
else:
       print("Number is NOT 5")

Remember one thing Python uses indentation rather than curly braces for any code blocks.notice that there is colon(:) at if and else both.this is required in python.we use == equal sign to check the  equality in Python.

in Python there is a concept of "Truthy and Falsy Values" for example.

number=5
if number:
 
     print("Number is defined and truthy")

text = "Python"
if text:
   
    print("Text is defined and truthy")

In many other programming language you have to check the length of the variable if it is value greater or less than zero but in Python you could just write like above.

okay in case of Boolean and None:it also has Truthy and Falsy Values.
eg:

pyhton_course = True

if python_course :

# Not python_course == True

    print("this will execute")

aliens_found = None

if aliens_found :
    print("This will NOT execute")

you can also set the same thing for None like I have done above.

               Not If

number = 5

if number !=5 :
      print("this will not execute")

python_course = True

if not python_course:

     print("this will also not excute")

Multiple If Conditions

number = 3

python_course = True

if number  == 3 and python_course:
   
    print("this will execute")

if number == 17 or python_course :

   print("this will also execute")

Note: in Python there is no && or || for and  and or like in other programming language.

           Ternary If Statements

a = 1
b = 2

"bigger" if a>b else "smaller"

This is called Ternary if Statement in Python.

No comments: