PowerPoint Presentation Algorithms Programming with Python Module 1 – Python basics – Lesson 7 Nguyễn Chí Thức gthuwhile loop 2 while some.PowerPoint Presentation Algorithms Programming with Python Module 1 – Python basics – Lesson 7 Nguyễn Chí Thức gthuwhile loop 2 while some.
Trang 1Algorithms & Programming with Python
Module 1 – Python basics – Lesson 7
Nguyễn Chí Thức gthuc.nguyen@gmail.com
0986636879
Trang 2while loop
2
while some_condition:
a block of statements
Trang 3while loop
3
i = 1
while i <= 10:
print(i ** 2)
i += 1
Trang 4while loop
4
n = int(input())
length = 0
while n > 0:
n //= 10 length += 1 print(length)
Trang 5while loop with else
5
i = 1
while i <= 10:
print(i)
i += 1 else:
print('Loop ended, i =', i)
Trang 6while loop with else - break
6
total_sum = 0
a = int(input())
while a != 0:
total_sum += a
if total_sum >= 21:
print('Total sum is', total_sum) break
a = int(input())
else:
print('Total sum is < 21 and is equal to', total_sum, '.')
Trang 7for loop with else
7
for i in range(5):
a = int(input())
if a < 0:
print('Met a negative number', a) break
else:
print('No negative numbers met')
Trang 8continue in loops
8
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num) continue
print("Found a number", num)
Trang 9break & continue with nested loop
9
for i in range(3):
for j in range(5):
if j > i:
# breaks only the inner for break
print(i, j)
Trang 101 line while loop
10
i = 1
while (i<10): print (i); i += 1