Variables, constants & data types
หน้านี้ต้องใช้เบราว์เซอร์ล่าสุด (รองรับ SharedArrayBuffer) กรุณาอัปเดต Chrome, Edge, Firefox หรือ Safari เป็นเวอร์ชันล่าสุด
ตัวแปรคือกล่องที่มีชื่อ
- ตัวแปร คือชื่อที่ใช้เก็บค่า
- คุณใส่ค่าเข้าไปด้วย
=— นี่คือสิ่งที่เรียกว่า assignment - ใช้ชื่อที่ชัดเจนเพื่อให้โปรแกรมอ่านง่าย
English
age = 15
price = 2.50
name = "Ada"
print(age, price, name)
สำรวจ
Variables as named boxes
แต่ละ = puts a value into a named box you can use later.
ประเภทข้อมูลทั้งห้า
- IGCSE ใช้ ประเภทข้อมูล พื้นฐาน 5 ชนิด:
- integer (จำนวนเต็ม) → Python
int; real (ทศนิยม) →float - char (ตัวอักษรเดียว), string (ข้อความ) →
str; Boolean (True/False) →bool
English
score = 42 # integer
height = 1.75 # real
grade = "A" # char
town = "Cairo" # string
passed = True # Boolean
ค่าคงที่ไม่เปลี่ยนแปลง
- ค่าคงที่ คือค่าที่ไม่เปลี่ยนแปลงตลอดช่วงที่โปรแกรมทำงาน
- Python ไม่มีคำสำคัญเฉพาะสำหรับค่าคงที่ เราจึงเขียนค่าคงที่ตาม
CAPITALS - สิ่งนี้จะเตือนผู้อ่านว่า: อย่าเปลี่ยนฉัน
English
PI = 3.14159
VAT_RATE = 0.20
print(PI)
การแปลงระหว่างประเภทข้อมูล
input()ให้เป็น string ดังนั้นต้องแปลงเมื่อต้องการตัวเลขint(x)สร้างจำนวนเต็ม;float(x)สร้างทศนิยม;str(x)สร้างข้อความ
English
n = int("5")
print(n + 1) # 6
print("Total: " + str(n)) # Total: 5
ในการสอบ: DECLARE และ CONSTANT
- Pseudocode กำหนดชนิดด้วย
DECLAREและกำหนดค่าด้วยCONSTANT
DECLARE Age : INTEGER
Age ← 15
CONSTANT Pi ← 3.14
ข้อผิดพลาดที่พบบ่อย
- กำหนดค่าให้ตัวแปรก่อนนำไปใช้
- ค่าคงที่เป็นค่าที่คุณไม่เปลี่ยน — ตั้งชื่อให้ชัดเจน
- รักษาประเภทข้อมูลให้ถูกต้อง: ใช้ตัวเลขสำหรับคณิตศาสตร์ และใช้สตริงสำหรับข้อความ
ลองดูเลย
- สร้างตัวแปรและคำนวณทางคณิตศาสตร์เล็กน้อยด้วยมัน
- กด Check answer เพื่อทดสอบโค้ดของคุณ
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
The variables width และ height are set for you. Work out the rectangle's พื้นที่ (width × height) and store it in a variable called area.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
price is a จริง number and quantity is an integer. Work out the total cost (price × quantity).
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Read a whole number with input(), convert it with int(...), then print the number plus 3. For input 7, the output should be 10.
คลิก Run เพื่อดูผลลัพธ์ที่นี่