Logo

04 Operator, Input และ Output

Operator, Input และ Output

โปรแกรมส่วนใหญ่ต้องรับข้อมูล ประมวลผล และแสดงผลลัพธ์ บทนี้จะรวมพื้นฐานที่ใช้บ่อย

Arithmetic Operators

a = 10
b = 3

print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)

ความหมาย:

  • / หารแบบได้ทศนิยม
  • // หารเอาจำนวนเต็ม
  • % เอาเศษจากการหาร
  • ** ยกกำลัง

Comparison Operators

ใช้เปรียบเทียบค่า ผลลัพธ์เป็น boolean

score = 75

print(score >= 50)
print(score == 100)
print(score != 0)

Logical Operators

age = 20
has_ticket = True

can_enter = age >= 18 and has_ticket
print(can_enter)

ตัวที่ใช้บ่อย:

  • and ต้องจริงทั้งสองฝั่ง
  • or จริงอย่างน้อยหนึ่งฝั่ง
  • not กลับค่าจริงเป็นเท็จ

รับข้อมูลจากผู้ใช้

name = input("กรอกชื่อ: ")
print(f"สวัสดี {name}")

ค่าจาก input() จะเป็น string เสมอ

age = int(input("กรอกอายุ: "))
print(age + 1)

แสดงผลหลายค่า

name = "Ann"
score = 92

print("Name:", name, "Score:", score)
print(f"Name: {name}, Score: {score}")

ตัวอย่างโปรแกรมคำนวณ VAT

price = float(input("ราคาสินค้า: "))
vat_rate = 0.07
vat = price * vat_rate
total = price + vat

print(f"VAT: {vat:.2f}")
print(f"Total: {total:.2f}")

แบบฝึกหัด

  1. รับราคาสินค้าและจำนวนสินค้า
  2. คำนวณราคารวม
  3. ถ้าต้องการคิดส่วนลด 10% ให้คำนวณราคาหลังลด
  4. แสดงผลทศนิยม 2 ตำแหน่ง