Schleifen

In [1]:
a = ["a","b","c","d"]
In [2]:
for schleifenvariable in a:
    print(schleifenvariable)
a
b
c
d
In [3]:
a = [[1,2,3],["a","b","c"],[0x1,0xa,0xf]]
In [4]:
for var in a:
    print(var)
[1, 2, 3]
['a', 'b', 'c']
[1, 10, 15]
In [5]:
for var in a:
    b = var * 3
    print(b)
[1, 2, 3, 1, 2, 3, 1, 2, 3]
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
[1, 10, 15, 1, 10, 15, 1, 10, 15]
In [6]:
i = 0
for var in a:
    print(i,var)
    i = i + 1
0 [1, 2, 3]
1 ['a', 'b', 'c']
2 [1, 10, 15]
In [7]:
i = 0
for var in a:
    print(i,var)
i = i + 1
0 [1, 2, 3]
0 ['a', 'b', 'c']
0 [1, 10, 15]
In [8]:
i
Out[8]:
1

while

In [9]:
i = 3
while i < 10:
    i = i + 1
    print(i)
4
5
6
7
8
9
10

range

In [10]:
for i in range(10):
    print(i)
0
1
2
3
4
5
6
7
8
9
In [11]:
for i in range(5,20,2):
    print(i)
5
7
9
11
13
15
17
19

break

In [12]:
for i in range(10):
    if i == 5:
        break
    print(i)
0
1
2
3
4

continue

In [13]:
for i in range(10):
    if i == 5:
        continue
    print(i)
0
1
2
3
4
6
7
8
9

Gauss'sche Summenformel

In [14]:
erg = 0
for i in range(1,51):
    erg += i
print(erg)
1275
In [15]:
(50+1)*50/2
Out[15]:
1275.0

else

In [16]:
n = 20
for i in range(n):
    if i == 15:
        break
    print(i)
else:
    print("fertig")
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
In [17]:
n = 10
for i in range(n):
    if i == 15:
        break
    print(i)
else:
    print("fertig")
0
1
2
3
4
5
6
7
8
9
fertig

pass

In [18]:
if i < 20:
    print("i < 20")
else:
    pass
i < 20
In [19]:
i
Out[19]:
9
In [20]:
i = 30
In [21]:
if i < 20:
    print("i < 20")
else:
    pass

unendliche Schleife

In [22]:
while True:
    pass
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-22-cccdd40a5a4c> in <module>()
      1 while True:
----> 2     pass

KeyboardInterrupt: