-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path08_loops.py
More file actions
99 lines (84 loc) · 2.51 KB
/
08_loops.py
File metadata and controls
99 lines (84 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# We will test the loops in this file.
# Python also has for and while loop.
# For loop:
names = ["Ramesh", "Suresh", "Ganesh", "Jignesh"]
for name in names:
print name
# prints 0 to 4 using range function which returns a "list"
# passing a single argument works
list = range(5)
for x in list:
print x
print "---"
# print 5 to 10 using range function, which takes two arguments and returns a
# list
list = range(5, 11)
for x in list:
print x
print "---"
# prints 0 to 5, using xrange function, which accepts a single argument
# and returns an "iterator" over a list of
iterator = xrange(6)
for x in iterator:
print x
print "---"
# print 5 to 10 using xrange with two arguments
iterator = xrange(10,15)
for x in iterator:
print x
print "---"
# what happens when float argument is passed to range?
# an error will be returned at below line
#list = range(5.5)
# While loops are the same as in any other language:
print "Begin while loops demo..."
count = 0
while count < 5:
#count++ # count ++ doesn't work in python
count += 1
print count
print "---"
# break statement
print "Let's test the break statement..."
for name in names:
print name
if name == "Suresh":
print "Name found"
break
print "---"
# We'll skip continue, because we rarely use it
# Else can be used in the loops..
# The loop iterates over all the values in the iterable and then else clause
# is executed.
# We can take advantage of this behavior in search functionality.
# If the item we are searching for is not present in the iterable datastrcuture,
# we can raise an error or something in the else part.
for name in names:
# try to find a name that doesn't end with "sh"
if not(name.endswith("sh")):
# this will never be executed because all our names end with "sh"
break
else:
print "Found no names that don't end with sh... well, damn!"
print "---"
# Another simpler example:
# Here, if condition is satisfied. So break will be executed
# loop was never completely iterated over and therefore, else clause of the loop
# will never be executed
for x in range(10):
if x == 5:
print "breaking the loop at: " + str(x)
break;
else:
print "counting loop: " + str(x)
else:
# This will never be executed beause the loop was terminated before it
# could completely iterate over the list.
print "This will not be executed"
print "---"
# Else clause is available for while loop as well
count = 0
while count < 5 :
count += 1
else:
print "Count exceeded "