លំហសិក្សាកម្ពុជា
V1.0
Python is a popular programming language known for its simple syntax and wide range of applications. This practice introduces the fundamental concepts of Python programming, including variables, data types, operators, conditional statements, loops, functions, and data structures. Each topic includes simple explanations, practical code examples, and exercises to help beginners develop their programming skills. Through consistent practice, learners can build a strong foundation in Python and prepare to apply it to real-world tasks, including data analysis, business applications, and financial technology (FinTech).
Python is a high-level programming language known for its simple syntax and readability. It is widely used in data analysis, artificial intelligence, automation, web development, and financial technology (FinTech).
Example:
print("Hello, World!")Output:
Hello, World!Explanation: The print() function displays information on the screen.
Practice: Write a program that displays your name and learning goal.
A variable is a name used to store a value that can be used later in a program.
Example:
name = "Alex"
age = 20
balance = 150.50
is_student = True
print(name)
print(age)
print(balance)
print(is_student)Output:
Alex
20
150.5
TrueCommon data types:
| Data Type | Description | Example |
|---|---|---|
str | Text | "Python" |
int | Whole number | 20 |
float | Decimal number | 15.5 |
bool | Boolean value | True |
Key point: The = operator assigns a value to a variable.
Practice: Create variables for your name, age, monthly expenses, and student status. Display their values using print().
Operators perform calculations and comparisons in Python.
Common arithmetic operators:
| Operator | Purpose | Example | Result |
|---|---|---|---|
+ | Addition | 10 + 5 | 15 |
- | Subtraction | 10 - 5 | 5 |
* | Multiplication | 10 * 5 | 50 |
/ | Division | 10 / 5 | 2.0 |
// | Floor division | 11 // 2 | 5 |
% | Remainder | 11 % 2 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
Example:
income = 500
expenses = 320
savings = income - expenses
print(savings)Output:
180Explanation: The program subtracts expenses from income to calculate the remaining savings.
Practice: Calculate your total expenses by adding food, transportation, and study costs. Subtract the total from your monthly budget.
Conditional statements allow a program to make decisions based on specific conditions. Python uses if, elif, and else.
Example:
balance = 100
if balance >= 200:
print("Sufficient balance")
elif balance >= 100:
print("Minimum balance reached")
else:
print("Low balance")Output:
Minimum balance reachedExplanation:
if checks the first condition.
elif checks another condition if the previous condition is false.
else executes when none of the previous conditions is true.
Practice: Write a program that checks whether a student's score is at least 50. Display "Pass" if the score is 50 or higher and "Fail" otherwise.
Loops repeat instructions without requiring the same code to be written multiple times. Python provides two commonly used loops: for and while.
A for loop iterates over a sequence or a range of values.
Example:
for number in range(1, 6):
print(number)Output:
1
2
3
4
5Explanation:
for starts the loop.
number is the variable that stores the current value in each iteration.
range(1, 6) generates numbers from 1 to 5. The ending value, 6, is excluded.
print(number) displays each number on a separate line.
Practice: Write a for loop that displays numbers from 1 to 10.
A while loop repeats instructions as long as its condition remains true.
Example:
count = 1
while count <= 3:
print(count)
count += 1Output:
1
2
3Explanation:
count = 1 initializes the counter.
while count <= 3 checks whether the condition is true.
print(count) displays the current number.
count += 1 increases the counter by one after each iteration.
Key point: A while loop needs a condition that eventually becomes false to prevent an infinite loop.
Practice: Write a while loop that displays numbers from 1 to 5.
Lists and dictionaries are data structures used to store and organize information.
A list stores multiple items in a single variable.
Example:
expenses = [20, 35, 15, 40]
print(expenses[0])
print(sum(expenses))Output:
20
110Explanation:
expenses stores four numerical values.
expenses[0] accesses the first item because Python indexing starts at zero.
sum(expenses) calculates the total of all numerical values.
Practice: Create a list containing five expenses and calculate their total.
A dictionary stores information as key-value pairs.
Example:
student = {
"name": "Alex",
"age": 20,
"major": "FinTech"
}
print(student["name"])
print(student["major"])Output:
Alex
FinTechExplanation:
name, age, and major are keys.
"Alex", 20, and "FinTech" are their corresponding values.
student["name"] retrieves the value associated with the "name" key.
Key difference:
Lists organize collections of items.
Dictionaries organize information using keys associated with values.
Practice: Create a dictionary containing your name, major, and university year. Display each value.
A function is a reusable block of code designed to perform a specific task. Functions improve code organization and reduce repetition.
Example:
def calculate_savings(income, expenses):
return income - expenses
result = calculate_savings(500, 320)
print(result)Output:
180Explanation:
def defines a function.
income and expenses are parameters.
return sends the calculated result back to the caller.
calculate_savings(500, 320) calls the function using two arguments.
print(result) displays the returned value.
Practice: Create a function named calculate_total() that accepts three numbers and returns their sum.
This project combines variables, dictionaries, built-in functions, arithmetic operators, and conditional statements to create a simple expense tracker.
Objective: Calculate total monthly expenses and determine the remaining budget.
Code:
budget = 500
expenses = {
"Food": 120,
"Transport": 50,
"Study": 80,
"Entertainment": 40
}
total_expenses = sum(expenses.values())
remaining_balance = budget - total_expenses
print("Monthly Budget:", budget)
print("Total Expenses:", total_expenses)
print("Remaining Balance:", remaining_balance)
if remaining_balance >= 0:
print("You are within your budget.")
else:
print("You have exceeded your budget.")Output:
Monthly Budget: 500
Total Expenses: 290
Remaining Balance: 210
You are within your budget.Explanation:
budget stores the available monthly budget.
The expenses dictionary organizes spending by category.
expenses.values() retrieves the expense amounts.
sum() calculates the total expenses.
Arithmetic subtraction calculates the remaining balance.
The if-else statement checks whether the budget has been exceeded.
print() displays the results.
Extension exercises:
Add a new expense category.
Change the budget and expense amounts.
Calculate the average expense.
Display each expense category and its amount.
Display a warning when expenses exceed 80% of the budget.
Complete the following tasks independently to test your understanding of Python fundamentals.
Create variables for monthly income and expenses.
Calculate total expenses from a list of five items.
Use an if statement to check whether your savings are positive.
Write a function that calculates savings.
Extend the expense tracker by adding a new expense category.
Display each expense category and its amount.
Success criteria: The program should run without errors, produce correct calculations, and display understandable results.
Python programming begins with understanding fundamental concepts and applying them through regular practice. Variables, data types, operators, conditional statements, loops, data structures, and functions form the foundation of Python development. By combining these concepts in practical projects such as a monthly expense tracker, learners can develop problem-solving skills and prepare for more advanced applications in data analysis, automation, business analytics, and financial technology (FinTech).
មតិយោបល់ 0