ezoic

Wednesday, July 27, 2016

How to pratically learn python from zero: chapter three loops

In programming, loops is used to complete a round of calculations etc.  through a list etc. Ppl use the framework/form to complete a sequence of  calculations etc. through a list etc.

You can loop through a list, a tuple, a sequence, a set etc.

Python has two types of loops, 1. While 2. For

Python does not have do until loop.

Here are the examples for 1.While and 2.For:


Python's while loop does not include 'do' statement:

count=0 
while (count<9):
    count=count+1    print count





For loop example:
a={1,2,3,4}
for i in range(len(list(a))):
    a=list(a)
    print a[i]
 
set does not support indexing, so convert the set to list.

b=[1,2,3,4]
for i in range(len(b)):
    print b[i]

d=(1,2,3,4)

for i in range(len(d)):
    print d[i]
 
We can loop through a dictionary:
 
kk={'a':1,'b':3,'r':8}

for key in kk.keys():
    print key, kk[key]
 
results:
a 1
b 3
r 8
 



And there are three control statements for Python loop: break, continue, pass

Break means the loop stops at where the condition meets:

count=0
while (count<9):
  count=count+1
  if count>5:
        break
  else:
     print count

output

1
2
3
4
5



Pass means we skip the step where the condition meets, it is a little bit similar to break.
 
count=0
 
while (count<9):
    count=count+1
    if count==5:
       pass
    else:
        print count
 
output
1
2
3
4
6
7
8
 

 

Continue returns the control to the beginning of the while loop.. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.

count=0
while (count<9):
   count=count+1
   if count>5:
       continue
   print count

output
1
2
3
4
5




No comments:

Post a Comment

looking for a man

 I am a mid aged woman. I live in southern california.  I was born in 1980. I do not have any kid. no compliacted dating.  I am looking for ...