Python Programming from Scratch

Python Programming from Scratch

Python is easy to read and widely used for data analysis, automation, web development and teaching programming. This article walks you through your first program, variables, lists, dictionaries, functions and reading files.

Testing note: the computer used to write this article does not have Python installed, so the code has not been run here yet. Run each example yourself and check the output. The article will show real output once it has been tested.

What you need

How it works

Diagram: a .py file is run by the Python interpreter, which produces output
Diagram: a .py file is run by the Python interpreter, which produces output

Your first program

Create `hello.py` and type:

print("สวัสดี Python")

Run it with `python hello.py`. You should see `สวัสดี Python`.

Variables and lists

name = "สมชาย"
scores = [85, 72, 45]
average = sum(scores) / len(scores)
print(name, "คะแนนเฉลี่ย", round(average, 2))

Python does not require declaring types. A list stores a changeable sequence of items, and `len` returns the number of items.

Dictionaries and conditions

students = {"สมชาย": 85, "สมหญิง": 72, "สมศักดิ์": 45}

def grade(score):
    if score >= 80:
        return "A"
    elif score >= 70:
        return "B"
    elif score >= 50:
        return "C"
    return "F"

for name, score in students.items():
    print(name, grade(score))

A dictionary stores key-value pairs. Functions are defined with `def`, and indentation marks the code block.

Reading and writing files

with open("scores.txt", "w", encoding="utf-8") as f:
    f.write("สมชาย,85\nสมหญิง,72\n")

with open("scores.txt", encoding="utf-8") as f:
    for line in f:
        name, score = line.strip().split(",")
        print(name, int(score))

`with` closes the file automatically, and `encoding="utf-8"` keeps Thai text correct.

Common mistakes

Next steps

Write a program that reads grades from `scores.txt` and writes the results to a new file, then learn standard modules such as `csv` and `datetime`.

Summary

Python uses readable structure. Lists and dictionaries store data, functions organise repeated work, and `with open` reads and writes files safely.