ตัวแปรและประเภทข้อมูล
Python เป็นภาษาโปรแกรมประเภทไดนามิก หมายความว่าคุณไม่จำเป็นต้องประกาศประเภทตัวแปรก่อนใช้งาน ด้านล่างนี้คือตัวอย่างการประกาศตัวแปรและประเภทข้อมูลทั่วไปบางประเภท:
การประกาศตัวแปร:
variable_name = value
ประเภทข้อมูลทั่วไป:
- จำนวนเต็ม(
int):age = 25 - เลขทศนิยม(
float):pi = 3.14 - สตริง(
str):name = "John" - บูลีน(
bool):is_true = True
งบเงื่อนไข
คำสั่งเงื่อนไข Python ใช้เพื่อตรวจสอบเงื่อนไขและดำเนินการคำสั่งตามผลการประเมิน มีการใช้ โครงสร้าง if, else, และ elif(else if) ดังนี้:
if คำแถลง:
if condition:
# Execute this block if condition is True
else คำแถลง:
else:
# Execute this block if no preceding if statement is True
elif (else if) คำแถลง:
elif condition:
# Execute this block if condition is True and no preceding if or else statement is True
ลูป
Python รองรับลูปที่ใช้กันทั่วไปสองประเภท: for ลูปและ while ลูป ทำให้สามารถเรียกใช้คำสั่งซ้ำได้
for วนซ้ำ:
for variable in sequence:
# Execute statements for each value in the sequence
while วนซ้ำ:
while condition:
# Execute statements while the condition is True
ตัวอย่างเฉพาะ:
# Variable declaration
age = 25
name = "John"
# Conditional statement
if age >= 18:
print("You are of legal age.")
else:
print("You are not of legal age.")
# Loop
for i in range(5):
print("Hello there!")
count = 0
while count < 5:
print("Loop number:", count)
count += 1
เมื่อดำเนินการ โค้ดข้างต้นจะตรวจสอบอายุและพิมพ์ข้อความที่เหมาะสม จากนั้นวนซ้ำข้อความ Hello there! ห้าครั้งโดยใช้ for การวนซ้ำ และสุดท้ายพิมพ์ค่าของ while การวนซ้ำ

