Showing posts with label while loop in pyrhon. Show all posts
Showing posts with label while loop in pyrhon. Show all posts

Saturday, July 4, 2015

Python loops and conditionals

Like many other programming language Python also has loop controlling and conditional operators, they are not renamed to something else. We can iterate through any list or anything which are close relative list.
For loop for tuple or list:
Suppose we have a list a=[1,3,5,7,6], we want to iterate through the list and do some operation, we can do it by -
for i in a:
   i=i+1
   print i

The above snippet will iterate through the list and add one to each element, then print it. See the use of for loop in the program. The temporary variable i  iterate through the list a. So we don't have to know the number of element  in the list. We can use the same method for tuple. Or not? See it yourself as the tuples are not modifiable.
The same can be done in while loop.
i=0
While i<len(a):
   print i
   i=i +1

for and while loop works in a same way, i.e. iterate through a range or until some conditions are met. while loop is particularly useful when you need to write an infinite loop. Just write -
 while 1:
     print "looping continuously"
you can also write while True, too. Python has a boolean True and False keyword, so True is a viable option.

See the video for a better understanding.

The other important thing in python is conditional operator. if-elif-else can be used to see if certain condition or met and execute some statement if the condition is true.
It works like this  - 
if somecondition==true:
   execute something
elif seeothercondition==true:
   execute other statement
else :
   do this statement
You can see here how if else works in python.Let's see it by an example -

    value=raw_input("Enter a value") #To have user input through console
    value=int(value) #converting the value to an integer
    if value<5:
       print "You entered less than five"
    elif value>=5 and  value<10:
       print "You enter between 5 to 10"
    else:
       print "You entered beyond 10"

     

In the program we are checking the value of variable value and executing print statement. see the use of <,>,and,= statement in the program. The raw_input is used for prompt user to enter a value.You can use while 1: to loop forever through the program.



Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...