Professional Documents
Culture Documents
เอกสารประกอบการสอน 6 Loops
เอกสารประกอบการสอน 6 Loops
ด้วยกัน คือ
1. for loop
2. while loop
for loop
วนในข้อมูลประเภท sequence เช่น list, dictionary, string, tuple หรือ array
for x in sequence:
do something with x
mytuple = (1,2,3,4,5)
print(text)
This is it!1
This is it!2
This is it!3
This is it!4
This is it!5
print(i)
print(i)
stop = 13
print(i)
11
13
print(i)
10
แบบฝึกหัด
จงใช้คำสั่ง for ในการ print อักขระที่ปรากฎดังต่อไปนี้
In [ ]:
@@
@@@
@@@@
@@@@@
@@@@@@
@@@@@@@
@@@@@@@@
@@@@@@@@@
@@@@@@@@@@
@@@@@@@@@@
@@@@@@@@@
@@@@@@@@
@@@@@@@
@@@@@@
@@@@@
@@@@
@@@
@@
print("@"*i)
for i in range(10,0,-1):
print("@"*i)
@@
@@@
@@@@
@@@@@
@@@@@@
@@@@@@@
@@@@@@@@
@@@@@@@@@
@@@@@@@@@@
@@@@@@@@@@
@@@@@@@@@
@@@@@@@@
@@@@@@@
@@@@@@
@@@@@
@@@@
@@@
@@
continue = ข้ามการวนปัจจุบันไปลูปในรอบถัดไป
if i == 7 or i == 3:
continue
print(i)
if i == 15:
break
if i == 12:
continue
if i%2 == 0:
if i%2 != 0:
0 even number
1 odd number
2 even number
3 odd number
4 even number
5 odd number
6 even number
7 odd number
8 even number
9 odd number
10 even number
11 odd number
13 odd number
14 even number
Nested loop
In [ ]: for i in range(5):
for j in range(3):
pass
i = 0, j = 2
i = 1, j = 2
i = 2, j = 2
i = 3, j = 2
i = 4, j = 2
for i in range(1,5):
print(char + str(i))
A1
A2
A3
A4
B1
B2
B3
B4
C1
C2
C3
C4
D1
D2
D3
D4
While loop
วนลูปไปเรื่อย ๆ ในขณะที่ condition ยังเป็ นจริง
In [8]: i = 1
while i<10:
print(i)
i += 1
else:
train_model()
แบบฝึกหัด
จงเขียนเกมส์ทายตัวเลข ให้บอกใบ้ได้แค่ว่าเลขที่ทายมาน้อยกว่าหรือมากกว่าคำตอบ
In [10]: num = 0
answer = 21
print("Try higher")
print("Try lower")
else:
print("Congratulations!")
Try higher
Try lower
Congratulations!