The for loop: examples and possible errors

for , . , , .

for, while, . . .

python for :

  • for;
  • ;
  • ;
  • .

- , {}. “:” . tab .

continue, break, pass - , , . if-else.

for

.

for in :

Cycle diagram




foreach C++

foreach (type item in set) {};

for i in 'hello world':

print(i * 2, end='')

hheelllloo wwoorrlldd
      
      



for - . .





i . , . i .

list_of_lists = [['hammerhead', 'great white', 'dogfish'],[0, 1, 2],[9.9, 8.8, 7.7]]

for list in list_of_lists:

print(list)

['hammerhead', 'great white', 'dogfish']

[0, 1, 2]

[9.9, 8.8, 7.7]

      
      



, .

Continue

for . . Continue if, - .

number = 0

for number in range(10):

number = number + 1

if number == 5:

continue #   continue

print(str(number))

print('End')
      
      



number 0 10 number, . number 5, . :

1

2

3

4

6

7

8

9

10

End
      
      



Break

if. .

Loop abort statement




number = 0

for number in range(10):

number += 1

if number == 5:

break # break

print('Number = ' + str(number))

print('Out of loop')
      
      



if : number 5, . print()





Number = 5.

      
      



break, print().

.

for n in range(2, 10):
	for x in range(2, n):
		if n % x == 0:
		print(n, 'equals', x, '*', n//x)
		break
	else:
		# loop fell through without finding a factor
		print(n, 'is a prime number')
      
      



. 2 10 n. n 2 n. , 8 . x. if , n / x . true, , . n / x , .

Pass

.

number = 0
for number in range(10):
    number += 1
    if number == 5:
        pass  
    print(str(number))
    print('End')

      
      



, if number == 5 .

1

2

3

4

5

6

7

8

9

10

End
      
      



, pass . , . , , .

class MyClass(object):

    def meth_a(self):

        pass

    def meth_b(self):

        print "I'm meth_b"
      
      



meth_a . Python , if, except, def, class . .

IndentationError: expected an indented block.

      
      



pass.

class CompileError(Exception):

    pass
      
      



pass - .

for pass:

for t in range(25):

    do(t)

    if t == 20:

         pass
      
      



0 25. t. do(). , , pass. , do 24 t = 20.

for .

Arrays and Loop




:

for i in [0, 1, 2, 3, 4, 5]:

    print i**2
      
      



, .

array = [1, 2, 3, 4, 5, 6, 7, 8, 9]

for in array:

    print i
      
      



array = [1, 2, 3, 4, 5, 6, 7, 8, 9] 
      
      



, range(). range() : , , . . , range(5) , 0 5. , .

range(0, 10, 2)
      
      



:

0, 2, 4, 6, 8, 10
      
      



. ,

colors = ['red', 'green', 'blue', 'yellow']
      
      



, , .

for i in range(len(colors)): 
    print colors[i]
      
      



, for :

colors = ['red', 'green', 'blue', 'yellow']
for color in colors: 
    print color
      
      



Array creation




, reversed().

colors = ['red', 'green', 'blue', 'yellow']
for color in reversed(colors): 
    print color
      
      



. , .

enumerate() . python for.

Arrays and Index




. enumerate() :

for i in range(len(L)): 
item = L[i]
# ... compute some result based on item ...
      
      



len(). , , L. , range(). [0, … n].

L[i] L.

L[0], L[1], L[2]  ..
      
      



enumerate() b

for counter, value in enumerate(L): 
    print(“index : “counter, “value : “value)
      
      



Enumerate() -, for .

items() iteritems(), .

d.items()

d.iteritems()
      
      



, zip().

Array join




A B, zip-, . A B .

zip_object[1] = [A[1], B[1]];
      
      



zip() 4 , - 4 . . , -.

, , , zip_longest().

list(itertools.zip_longest((1,2,3), [4]))
#[(1, 4), (2, None), (3, None)]
      
      



, , keys().

Key is Value




.

for k in d.keys(): 
    if k.startswith('R'):
        del d[k]
      
      



d. keys(). k. startswith, .

startswith() , . : prefix, start, end.

str.startswith(prefix[, start[, end]]) -> bool
      
      



- prefix. .

my_str.startswith(‘value’)
      
      



my_str.startswith((‘value1’, ‘value2’))
      
      



, ().

start , . . start = -x, x . end , . . end = -x x .

startswith() endswith(). , . suffix, start, end, .

, - dict(izip( 1, 1)). , :

1:2
      
      



names = ['raymond', 'rachel', 'matthew']
colors = ['red', 'green', 'blue']
d = dict(zip(names, colors))
# {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}
      
      



dict() , - “:”. 2. , - 1.

d[‘raymond’]

# red
      
      



, , get().

d.get(key, default = None)
      
      



d key, key[index].

colors = ['red', 'green', 'red', 'blue', 'green', 'red']
d = {}
for color in colors:
    d[color] = d.get(color, 0) + 1
      
      



get() .

colors = ['red', 'green', 'red', 'blue', 'green', 'red']

d = {}

for color in colors:

    if color not in d:

    d[color] = 0

d[color] += 1
      
      



for.




All Articles