-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcontrolflow.py
182 lines (160 loc) · 2.31 KB
/
controlflow.py
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# if, elif, else
# Example of if statement
x = 10
if x > 5:
print("x is greater than 5") # Output: x is greater than 5
# Example of if-else statement
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5") # Output: x is not greater than 5
# Example of if-elif-else statement
x = 7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but less than or equal to 10") # Output: x is greater than 5 but less than or equal to 10
else:
print("x is 5 or less")
# Nested if statements
x = 8
if x > 5:
if x % 2 == 0:
print("x is greater than 5 and even") # Output: x is greater than 5 and even
else:
print("x is greater than 5 and odd")
# for loop
# Iterating over a list
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
# Output:
# 1
# 2
# 3
# 4
# 5
# Iterating over a string
word = "hello"
for letter in word:
print(letter)
# Output:
# h
# e
# l
# l
# o
# Using range()
for i in range(5):
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4
# Using range() with start and end
for i in range(2, 6):
print(i)
# Output:
# 2
# 3
# 4
# 5
# Using range() with start, end, and step
for i in range(1, 10, 2):
print(i)
# Output:
# 1
# 3
# 5
# 7
# 9
# while loop
# Basic while loop
count = 0
while count < 5:
print(count)
count += 1
# Output:
# 0
# 1
# 2
# 3
# 4
# Using break
# Example with for loop
for i in range(10):
if i == 5:
break
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4
# Example with while loop
count = 0
while count < 10:
if count == 5:
break
print(count)
count += 1
# Output:
# 0
# 1
# 2
# 3
# 4
# Using continue
# Example with for loop
for i in range(10):
if i % 2 == 0:
continue
print(i)
# Output:
# 1
# 3
# 5
# 7
# 9
# Example with while loop
count = 0
while count < 10:
count += 1
if count % 2 == 0:
continue
print(count)
# Output:
# 1
# 3
# 5
# 7
# 9
# Using pass
# pass in if-else
x = 10
if x > 5:
pass # Do nothing
else:
print("x is not greater than 5")
# pass in for loop
for i in range(10):
if i % 2 == 0:
pass # Do nothing
else:
print(i)
# Output:
# 1
# 3
# 5
# 7
# 9
# pass in while loop
count = 0
while count < 5:
count += 1
pass # Do nothing
print("Loop finished") # Output: Loop finished