Trường ĐH Công nghệ – Đại học Quốc gia Hà Nội
Tài liệu đọc: Think Python (2nd ed.), 7.3 – 7.5
> python game.py
What number am I thinking of?
# game.py
the_num = random.randint(1, 100)
def play():
try:
guess = input('What number am I thinking of? ')
num = int(guess)
if num != the_num:
print('That is not correct.')
else: #num == the_num
print('Correct!')
except ValueError:
print('Sorry, you did not enter a number.')
# game.py
def play():
still_playing = True
for i in range(5): # 5 guesses
if still_playing:
try:
guess = input('What number am I thinking of?')
num = int(guess)
if num != the_num:
print('That is not correct.')
else: #num == the_num
print('Correct!')
still_playing = False
except ValueError:
print('Sorry, you did not enter a number.')
# game.py
def play():
still_playing = True
while still_playing:
try:
guess = input('What number am I thinking of?')
num = int(guess)
if num != the_num:
print('That is not correct.')
else: #num == the_num
print('Correct!')
still_playing = False
except ValueError:
print('Sorry, you did not enter a number.')
|
Cú pháp
|
Ví dụ
|
while <điều_kiện_lặp>:
<các_câu_lệnh>
| Kết quả điều_kiện_lặp | Hành động |
|---|---|
| True | Chạy body rồi kiểm tra lại |
| False | Thoát vòng lặp |
# loops.py
def infinite_loop():
x = 0
while True:
print(x)
x = x + 1
>>> import loops
>>> loops.infinite_loop()
0
1
2
...
^C
KeyboardInterrupt
a = 8
b = 12
while a != b:
if a > b:
a = a - b
else:
b = b - a
print(a)
Chọn đáp án:
A: Không in gì: vòng lặp vô hạn B: 8 C: 12 D: 4 E: 0
* “Quan hệ” giữa các biến còn gọi là loop invariant.
# game.py
def play():
still_playing = True
while still_playing:
try:
guess = input('What number am I thinking of?')
num = int(guess)
if num != the_num:
print('That is not correct.')
else: #num == the_num
print('Correct!')
still_playing = False
except ValueError:
print('Sorry, you did not enter a number.')
# loops.py
def snake_eyes():
"""Roll a pair of dice until they both come up 1s."""
snake_eyes = False
num_tries = 0
while not snake_eyes:
r1 = roll()
r2 = roll()
print('Rolled: ' + str(r1) + ' and ' + str(r2))
num_tries = num_tries + 1
if r1 == 1 and r2 == 1:
snake_eyes = True
print('Snake eyes!')
print('It took ' + str(num_tries) + ' tries.')
# loops.py
def print_growth(period, amount):
"""Print one line of table."""
# ...
def double_investment(initial, rate_pct):
"""Print table of investment growth until doubled."""
amount = initial
period = 0
print_growth(period, amount)
while amount < 2*initial:
amount = (1 + rate_pct/100) * amount
period = period + 1
print_growth(period, amount)
# loops.py
def syr(start):
"""Returns the Syracuse sequence."""
x = start
lst = []
while x != 1:
lst.append(x)
if x%2 == 0:
x = x//2
else:
x = 3*x + 1
lst.append(x)
return lst
| Định nghĩa | Quy tắc |
|---|---|
| f(n) = 1 | nếu n là 1 |
| f(n) = n/2 | nếu n chẵn |
| f(n) = 3n+1 | nếu n lẻ |
# loops.py
def syr(start):
"""Returns the Syracuse sequence."""
x = start
lst = []
while x != 1:
lst.append(x)
if x%2 == 0:
x = x//2
else:
x = 3*x + 1
lst.append(x)
return lst
* Đệ quy có thể biểu diễn lặp không bị chặn trước số lần, còn for thường
dựa vào dãy hữu hạn.
** while có thể mô phỏng các mẫu lặp tổng quát.
| Dùng biến cờ | Dùng break |
|---|---|
|
|
| Vòng lặp for | Tương đương bằng while ✅ |
|---|---|
|
|