Saturday, June 30, 2018

If / If Else / While in Python



If / If-Else / If-Elif-Else Statement:

Syntax:
  if <condition statement> :
       <block of code>
  elif:
       <block of code>
  else:
       <block of code> 

Will understand this loop directly with examples.

>>> a=20
>>> if a== 20:
...     print a
...
20
>>>


But above code won't print anything if  I changed value of a to 10.

>>> a=10
>>> if a== 20:
...     print a
...
>>>

To handle this, we can add else statement.

>>> a=10
>>> if a== 20:
...     print("a is 20")
... else:
...     print("a is not 20")
...
a is not 20
>>>

Now let us consider i want to check number is even or odd and print accordingly.

Problem statement:
if number is even print EVEN
if number is odd print ODD
if number is 0 print NEITHER EVEN NOR ODD


let's consider, if I use if-else statement, i can print any two statements from above.
Hence to achieve such thing, we can use elif statement.

>>> a = 2;
>>> if a==0:
...     print("NEITHER EVEN NOR ODD")
... elif a % 2 == 0:
...     print("EVEN")
... else:
...     print("ODD")
...
EVEN
>>>



While Statement:

Syntax:

while <condition>:
   <block of code>


Block of code run unless and until condition is true.
Let's consider I want  to print 0 to 10. Then our code will like:

>>> i = 1
>>> while(i<=10):
...     print(i)
...     i = i+1
...
1
2
3
4
5
6
7
8
9
10
>>>

Don't forget to write i = i+1. Otherwise your screen get full of 11111111. At that time you need to press ctrl+c to interrupt the loop

Note that while using WHILE statement in code, make sure that at-least once the condition written in while bracket should return a false otherwise loop will run infinite times.

No comments:

Post a Comment