-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths04_pfc_loops.py
More file actions
130 lines (97 loc) · 2.33 KB
/
s04_pfc_loops.py
File metadata and controls
130 lines (97 loc) · 2.33 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# -*- coding: utf-8 -*-
"""S04 - PFC - Loops.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Si4ITWlRxvZl0ryxPaq9PkjpA4Xx95qg
# Range
"""
my_range = range(0,10,2)
print(my_range)
list_from_range = list(my_range)
print(list_from_range)
# `range` can only have integer steps
# new_range = range(0,10,.5) # gives error
# to create sth like that, you will need `arange` from `numpy`
"""## Program Flow Control: Loops
`for` loop for a know number of iterations. A `for` loop is used for iterating over a sequence (that is either a `list`, a `tuple`, a `dict`ionary, a `set`, a `range` or a `str`ing).
`while` for unknown number of iterations (conditional)
"""
fruits = ["apple","banana","cherry"]
for f in fruits:
print(f)
# Print all numbers from 0 to 10 (not 10 itself)
for i in range(0,10):
print(i)
print(f)
print(i)
# count all 2-digit odd numbers
count = 0
for i in range(10,100):
if i % 2 == 1: # i % 2 != 0
count += 1
print(count)
# You can loop through characters of a string!
for c in "Hello World!":
print(c)
"""# `break` and `continue` """
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
"""`else` in `for` loop"""
for i in range(2,6):
print(i)
else:
print("done")
for i in range(1,20):
if i==10 :
break
print(i)
else:
print("done")
for i in range(1,20):
if i==10 :
continue
print(i)
else:
print("done")
name = "Majid"
print("My name is ",)
print(name)
name = "Majid"
print("My name is ", end='')
print(name)
# nested loops
for n in range(0,10):
for x in range(0,10):
print("*",end='')
print("")
for n in range(0,10):
for x in range(n, 10):
print("*",end='')
print("")
for n in range(0,10):
for x in range(0, n+1):
print("*",end='')
print("")
"""`while` loops"""
j = int(input())
s = ""
while j>0:
d = j % 2
print("this round j=",j,', j%2=',d," next round j=",j//2)
s = str(d) +s
j = j // 2
print(s)
"""`else`, `break` and `continue` work for `while` loops too."""