Bài 11: For và break,continure,else,pass

File lesson16.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
#!/usr/bin/
########### break ###########
print "Example of break:"
for letter in 'Johnny':    
   if letter == 'h':
      break
   print 'Current Letter :', letter
print "#################################"
########### continue ###########
print "Example of continue:"
for letter in 'Johnny':
   if letter == 'h':
      continue
   print 'Current Letter :', letter
print "#################################"
########### else Loop ###########
print "Example of else Loop:"
for num in range(10,20): 
   for i in range(2,num):
      if num%i == 0:     
         j=num/i
         print '%d equals %d * %d' % (num,i,j)
         break
   else:
      print num, 'is a prime number'
print "#################################"
########### pass ###########
print "Example of pass:"
for letter in 'Johhny':
   if letter == 'h':
      pass
      print 'This is pass block'
   print 'Current Letter :', letter

Kết quả:

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
Example of break:
Current Letter : J
Current Letter : o
#################################
Example of continue:
Current Letter : J
Current Letter : o
Current Letter : n
Current Letter : n
Current Letter : y
#################################
Example of else Loop:
10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number
#################################
Example of pass:
Current Letter : J
Current Letter : o
This is pass block
Current Letter : h
This is pass block
Current Letter : h
Current Letter : n
Current Letter : y
Bài 12: yield trong Python

File lesson17.py

1
2
3
4
5
6
7
#! /usr/bin/python
def binh_phuong():
    for i in range(0,6):
        yield i*i
for i in binh_phuong():
    print i

yield trả về dưới dạng 1 object chứa các kết quả tính toán trong for:

1
2
3
4
5
6
0
1
4
9
16
25
Bài 13: except trong Python

File lesson18.py

1
2
3
4
5
6
7
#! /usr/bin/python
while True:
    try:
        x = int(raw_input("Please enter a number: "))
        break
    except ValueError:
        print "Oops!  That was no valid number.  Try again..."

Khi điền đúng định dạng số thì break ra, còn không thì sẽ print except và lặp lại. Kết quả:

1
2
3
4
5
Please enter a number: a
Oops!  That was no valid number.  Try again...
Please enter a number: b
Oops!  That was no valid number.  Try again...
Please enter a number: 12
Bài 14: Class in Python

File lesson19.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#! /usr/bin/python
class Shape:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def dientich(self):
        return self.x * self.y
    def chuvi(self):
        return 2 * self.x + 2 * self.y
    def mota(self,text):
        self.mota = text
        return self.mota
    def scaleSize(self,scale):
        self.x = self.x * scale
        self.y = self.y * scale
        print "x:",self.x
        print "y:",self.y
shape=Shape(2,4)
print shape.dientich()
print shape.chuvi()
print shape.mota("This is a Python Class test")
shape.scaleSize(0.5)

Trong đó __init__ là constructor trong Python.

Kết quả:

1
2
3
4
5
8
12
This is a Python Class test
x: 1.0
y: 2.0
Bài 15: Dictionaries Python

File: lesson20.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
#! /usr/bin/python
cities = {'CA': 'San Francisco', 'MI': 'Detroit','FL': 'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
def find_city(themap, state):
    if state in themap:
        return themap[state]
    else:
        return "Not found."
# entry find_city vao map (bien cities)
cities['_find'] = find_city
while True:
    print "State? (ENTER to quit)",
    state = raw_input("> ")
    if not state: break
    # this line is the most important ever! study!
    city_found = cities['_find'](cities, state)
    print city_found

Ngoài ra ta còn có thể không gán entry find_city vào maps bằng cách:

1
2
3
4
5
6
7
8
9
10
11
12
13
# Dòng này bỏ
#cities['_find'] = find_city
while True:
    print "State? (ENTER to quit)",
    state = raw_input("> ")
    if not state: break
    #Dòng này thay bằng dòng dưới
    #city_found = cities['_find'](cities, state)
    city_found = find_city(cities, state)
    print city_found

Kết quả:

1
2
3
4
5
6
7
State? (ENTER to quit) > NY
New York
State? (ENTER to quit) > LG
Not found.
State? (ENTER to quit) > CA
San Francisco
State? (ENTER to quit) >
Bài 16: Modules Python

File lesson21.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#! /usr/bin/python
class Shape:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def dientich(self):
        return self.x * self.y
    def chuvi(self):
        return 2 * self.x + 2 * self.y
    def mota(self,text):
        self.mota = text
        return self.mota
    def scaleSize(self,scale):
        self.x = self.x * scale
        self.y = self.y * scale
        print "x:",self.x
        print "y:",self.y
        
def myapple():
    print "This is an "

File lesson22.py

1
2
3
4
5
6
7
#! /usr/bin/python
import lesson21
lesson21.myapple()
from lesson21 import Shape
shape=Shape(1,2)
shape.scaleSize(0.5)

Từ file lesson22.py ta có 2 cách gọi hàm, class từ file lesson21.py. Cách 1 là ta import lesson21 vào và gọi thẳng hàm bằng cách thêm dấu . gọi hàm. Cách 2 là ta import statement from lesson21 như trong code và gọi statement trực tiếp.

Kết quả:

1
2
3
This is an Apple
x: 0.5
y: 1.0
Print Friendly

Comments

comments

Bài viết liên quan