code = "ib-2027"
len(code) # 7
code[0] # "i"
code[3:7] # "2027": from index 3 up to, not including, 7
code.upper() # "IB-2027"
code.find("-") # 2; -1 if not found
"2027" in code # True
ลูป while ที่เงื่อนไขไม่เป็นเท็จเลยคือลูปอนันต์ การเลือกแบบซ้อนหรือลูปซ้อนคือการวางโครงสร้างหนึ่งไว้ภายในอีกโครงสร้างหนึ่ง การเยื้องแสดงว่าโครงสร้างใดอยู่ภายในโครงสร้างใด
def mean(values):
"""Return the mean of a non-empty list of numbers."""
total = 0
for v in values:
total = total + v
return total / len(values)
print(mean([4, 8, 9])) # 7.0
ตัวแปรในท้องถิ่น เช่น total มีอยู่เฉพาะภายในฟังก์ชันขณะกำลังทำงาน
def bubble_sort(a):
n = len(a)
for p in range(n - 1):
swapped = False
for i in range(n - 1 - p):
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
swapped = True
if not swapped:
break
flag swapped จะหยุดก่อนกำหนดเมื่อมีการวนรอบโดยไม่มีการสลับ: รายการมีลำดับอยู่แล้ว
def selection_sort(a):
for i in range(len(a) - 1):
smallest = i
for j in range(i + 1, len(a)):
if a[j] < a[smallest]:
smallest = j
a[i], a[smallest] = a[smallest], a[i]
with open("scores.txt", "a") as f:
f.write("Ada,91\n")
best_name, best = "", -1
with open("scores.txt", "r") as f:
for line in f:
name, score = line.strip().split(",")
if int(score) > best:
best_name, best = name, int(score)
print(best_name, best)
with ปิดไฟล์โดยอัตโนมัติ แม้จะมีข้อผิดพลาดเกิดขึ้นก็ตาม
ระบุชนิดข้อมูลที่เหมาะสมที่สุดสำหรับแต่ละข้อ: (a) จำนวนนักเรียนในห้อง; (b) whether a door is locked; (c) post code such as "SW1A 1AA"; (d) a temperature of 21.5 °C.
s = "Programming". ให้ (a) len(s); (b) s[3:7]; (c) s.find("g").
จัดประเภทข้อผิดพลาดแต่ละข้อว่าเป็น Syntax, Runtime หรือ Logic: (a) print("Hi"; (b) a loop that adds one item too few; (c) int("abc").
เติมตาราง Trace สำหรับ x = 1 แล้ว while x < 20: x = x * 3, และระบุค่าสุดท้ายของ x