เราได้ฝึก if, for, while ไปแล้ว มาลองโจทย์ที่ต้องผสมทั้งสามอย่าง
โจทย์ 1: จำลองการตัดเกรด #
รับชื่อและคะแนนนักเรียน 5 คน ถ้าคะแนน ≥ 80 ให้แสดง “Pass”, ถ้า 60–79 แสดง “Border”, น้อยกว่านั้นแสดง “Fail” จากนั้นพิมพ์เป็นตาราง
Name Score Result
Alice 85 Pass
Bob 74 Border
...
records = []
for _ in range(5):
name = input("ชื่อ: ")
score = int(input("คะแนน: "))
if score >= 80:
result = "Pass"
elif score >= 60:
result = "Border"
else:
result = "Fail"
records.append((name, score, result))
print(“Name\tScore\tResult”)
for name, score, result in records:
print(f"{name}\t{score}\t{result}")
โจทย์ 2: บีบอัดสตริงอย่างง่าย #
นับตัวอักษรที่ซ้ำกันต่อเนื่อง แล้วแสดงผลแบบ aabcccccaaa -> a2b1c5a3
text = input("สตริง: ")
if not text:
print("สตริงว่าง")
else:
result = []
current = text[0]
count = 1
for ch in text[1:]:
if ch == current:
count += 1
else:
result.append(f"{current}{count}")
current = ch
count = 1
result.append(f"{current}{count}")
print("".join(result))โจทย์ 3: ประมาณค่า π ด้วยมอนติคาร์โล #
สุ่มจุดในสี่เหลี่ยม 0–1 แล้วนับว่าส่วนใดอยู่ในไตรมาสของวงกลม ใช้สูตร 4 × (จุดในวง) / (จำนวนทั้งหมด) ยิ่งทดลองมากยิ่งแม่น
import random
n = int(input("จำนวนครั้ง: "))
inside = 0
for _ in range(n):
x = random.random()
y = random.random()
if x * x + y * y <= 1.0:
inside += 1
pi_estimate = 4 * inside / n
print("ค่าประมาณ:", pi_estimate)