Python Programming
A to Z Guide
यो course नेपाली विद्यार्थीहरूको लागि बनाइएको छ। हामी एकदम सरल भाषामा Python सिक्नेछौं — basics देखि Flask web development सम्म। No previous coding experience needed!
What is Python?
Python एउटा high-level programming language हो। यसको syntax (लेख्ने तरिका) एकदम सरल र पढ्न सजिलो छ। Guido van Rossum ले 1991 मा बनाएका थिए।
Why Python?
World को सबैभन्दा popular language मध्ये एक। Web development, Data Science, AI/ML, Automation — सबैमा use हुन्छ।
Easy to Learn
English जस्तै पढिन्छ। Curly braces {} छैन — indentation (space) use गर्छ। Beginners को लागि perfect!
Job Opportunities
Nepal र abroad दुवैमा Python developers को माग धेरै छ। Web developer, Data Analyst, AI Engineer — सबै Python बाट सुरु हुन्छ।
Python को uses — Where is Python used?
| Field | Examples | Popular Libraries |
|---|---|---|
| 🌐 Web Development | Websites, APIs, E-commerce | Flask, Django, FastAPI |
| 📊 Data Science | Data analysis, Reports | Pandas, NumPy, Matplotlib |
| 🤖 AI / Machine Learning | Chatbots, Image recognition | TensorFlow, PyTorch, Scikit-learn |
| ⚙️ Automation | File tasks, Web scraping | Selenium, BeautifulSoup |
| 🎮 Game Development | Simple games | Pygame |
| 📱 Desktop Apps | GUI applications | Tkinter, PyQt |
Step 1: Python Download गर्नुहोस्
https://www.python.org/downloads/Latest stable version download गर्नुहोस्। Windows मा install गर्दा "Add Python to PATH" checkbox ✅ check गर्न नबिर्सनुहोस् — यो एकदम important छ!
Windows Installation Steps:
- python.org मा जानुहोस्
- "Download Python 3.x.x" click गर्नुहोस्
- Installer run गर्नुहोस्
- ✅ "Add to PATH" check गर्नुहोस्
- "Install Now" click गर्नुहोस्
Verify Installation:
# Version check गर्नुहोस् python --version # Output: Python 3.12.x
Step 2: IDE छान्नुहोस्
VS Code (Recommended)
Free, fast र lightweight। Python extension install गर्नुहोस्। Beginners को लागि best choice!
PyCharm
Python को लागि specially बनाइएको। Professional developers use गर्छन्। Community edition free छ।
Jupyter Notebook
Data Science को लागि best। Code run गर्दा real-time output देखिन्छ।
Online: Replit / Google Colab
कुनै install नचाहिने! Browser मा नै code लेख्न सकिन्छ। Internet भए पुग्छ।
पहिलो Program लेखौं — First Program!
# यो comment हो — Python ले यो line execute गर्दैन print("Hello, World!") print("Hello, World!") print("I am learning Python!")
नमस्ते दुनियाँ!
म Python सिक्दैछु!
.py हुनुपर्छ। जस्तै: hello.py, mero_program.py1. Indentation — Python को सबैभन्दा ठूलो नियम
अन्य languages मा {} use हुन्छ, तर Python मा spaces (indentation) use हुन्छ। यो rule नमान्दा error आउँछ!
if 5 > 3: print("5 is greater than 3") print("This is correct indentation")
if 5 > 3: print("Error will occur!") # ^ यहाँ space छैन = ERROR!
2. Comments — Code मा notes लेख्ने तरिका
# यो single-line comment हो # Python ले यो line लाई ignore गर्छ """ यो multi-line comment हो docstring पनि भनिन्छ कुनै पनि function वा class explain गर्न use गर्छौं """ print("This will print") # यो comment हो, print हुँदैन
3. Case Sensitivity — सानो-ठूलो अक्षर फरक हुन्छ
name = "Santosh" # यो अलग variable Name = "Suresh" # यो अर्कै variable — N ठूलो भएकोले NAME = "Manish" # यो तेस्रो variable — सबै ठूला print(name) # Santosh print(Name) # Suresh print(NAME) # Manish
4. PEP 8 — Python को Code Style Guide
Variable Names
snake_case use गर्नुहोस्: first_name, total_amount — words बीच underscore (_)
Spacing
Operators को वरिपरि space राख्नुहोस्: x = 5 (not x=5)
Line Length
एक line मा 79 characters भन्दा बढी नराख्नुहोस् — राम्रो practice हो।
Naming Convention
Variables: snake_case | Classes: PascalCase | Constants: UPPER_CASE
print() — Screen मा देखाउने function
# 1. Simple print print("Hello! I am learning Python.") # 2. Multiple values — comma से छुट्याउनुहोस् print("My name:", "Santosh", "Age:", 20) # 3. f-string (Python 3.6+) — सबैभन्दा राम्रो तरिका name = "Santosh" age = 20 print(f"My name is {name} and age is {age}.") # 4. format() method print("My name is {}.".format(name)) # 5. sep र end parameters print("Apple", "Mango", "Banana", sep=" | ") print("This line continues", end=" ← ") print("next line") # 6. Float precision — दशमलव control height = 5.87654 print(f"Height: {height:.2f} feet") # 2 decimal places # 7. Large numbers comma format salary = 1500000 print(f"Salary: Rs. {salary:,}")
मेरो नाम: Santosh उमेर: 20
मेरो नाम Santosh हो र उमेर 20 छ।
Apple | Mango | Banana
यो line शेष भएन ← अर्को line
उचाइ: 5.88 feet
तलब: Rs. 1,500,000
Variables — Data Store गर्ने container
Variable भनेको एउटा box जस्तै हो जसमा data राख्न सकिन्छ। = operator ले value assign गर्छ।
# Variable create गर्ने name = "Ramesh Shrestha" # string age = 22 # integer gpa = 3.75 # float is_student = True # boolean city = "Kathmandu" # string # Multiple assignment एकसाथ x, y, z = 10, 20, 30 # Same value multiple variables मा a = b = c = 0 # Variable को type check गर्ने print(type(name)) # <class 'str'> print(type(age)) # <class 'int'> print(type(gpa)) # <class 'float'> # Variable को value change गर्न सकिन्छ city = "Pokhara" # अब city = "Pokhara" भयो
Variable Naming Rules — नाम राख्ने नियमहरू
| Rule | ✅ Valid | ❌ Invalid |
|---|---|---|
| Letter वा _ ले सुरु हुनुपर्छ | name, _age, first_name | 1name, 123 |
| Numbers use हुन्छ तर पहिलो character मा होइन | user1, age2 | 1user, 2age |
| Reserved keywords use नगर्नुहोस् | my_for, class_name | for, class, if |
| Spaces allowed छैन | first_name | first name |
| Case-sensitive हो | Name र name अलग छन् | — |
user_count is better than n or count_of_all_users_in_database। Snake_case use गर्नुहोस्।| Type | Keyword | Example | Description |
|---|---|---|---|
| String | str | "Santosh" | Text / अक्षरहरू |
| Integer | int | 25 | पूर्ण संख्या (whole number) |
| Float | float | 5.9 | दशमलव संख्या |
| Boolean | bool | True / False | सत्य वा असत्य |
| None Type | NoneType | None | कुनै value छैन |
| List | list | [1, 2, 3] | Ordered, changeable collection |
| Tuple | tuple | (1, 2, 3) | Ordered, unchangeable collection |
| Dictionary | dict | {"name": "Ram"} | Key-value pairs |
| Set | set | {1, 2, 3} | Unique items, unordered |
# String — text data student_name = "Sita Rai" address = 'Pokhara, Nepal' bio = """I live in Pokhara. मलाई coding मन पर्छ।""" # multi-line string # Integer — whole numbers age = 19 marks = 450 year = 2025 # Float — decimal numbers gpa = 3.85 height_m = 1.68 temperature = 36.6 # Boolean — True वा False मात्र is_passed = True has_laptop = False # None — no value result = None # अझै value assign छैन # Type conversion (casting) x = "42" # यो string हो x_int = int(x) # अब integer भयो: 42 x_flt = float(x) # अब float भयो: 42.0 y = str(100) # integer बाट string: "100" # Falsy values — जो False जस्तै behave गर्छन् # 0, "", None, [], {}, (), False — सबै falsy हुन् print(bool(0)) # False print(bool("")) # False print(bool(5)) # True print(bool("Hi")) # True
name = "Nabin Karki" greeting = " Hello World! " # Case methods print(name.upper()) # NABIN KARKI print(name.lower()) # nabin karki print(name.title()) # Nabin Karki print(name.capitalize()) # Nabin karki print(name.swapcase()) # nABIN kARKI # Strip (space हटाउने) print(greeting.strip()) # "Hello, World!" print(greeting.lstrip()) # left side strip print(greeting.rstrip()) # right side strip # Find र Replace sentence = "I study in Kathmandu" print(sentence.find("Kathmandu")) # 2 (index) print(sentence.replace("Kathmandu", "Pokhara")) print(sentence.count("I")) # कति पटक आयो # Split र Join csv_data = "Santosh,Suresh,Manisha,Kamal" names = csv_data.split(",") print(names) # ['Santosh', 'Suresh', 'Manisha', 'Kamal'] print(" | ".join(names)) # Santosh | Suresh | Manisha | Kamal # Check methods print("Santosh".startswith("San")) # True print("Santosh".endswith("sh")) # True print("Nepal123".isalnum()) # True (letters+numbers) print("Santosh".isalpha()) # True (only letters) print("12345".isdigit()) # True (only digits) # String Slicing — substring निकाल्ने text = "Python Programming" print(text[0]) # P — पहिलो character print(text[-1]) # g — अन्तिम character print(text[0:6]) # Python print(text[7:]) # Programming print(text[::-1]) # gnimmargorP nohtyP (reverse) print(len(text)) # 18 (length) # String Repetition र Concatenation print("Ha" * 3) # HaHaHa print("Hello" + " " + "Nepal")
Escape Characters
| Escape | Meaning | Example |
|---|---|---|
\n | New line (नयाँ line) | "Line1\nLine2" |
\t | Tab space | "Name:\tSantosh" |
\\ | Backslash | "C:\\Users\\Desktop" |
\' | Single quote | 'It\'s Nepal' |
\" | Double quote | "He said \"Hi\"" |
\r | Carriage return | "Hello\rWorld" |
1. Arithmetic Operators — गणित
a = 17 b = 5 print(a + b) # 22 — Addition (जोड्ने) print(a - b) # 12 — Subtraction (घटाउने) print(a * b) # 85 — Multiplication (गुणन) print(a / b) # 3.4 — Division (भाग) → always float print(a // b) # 3 — Floor Division (पूर्णांक भाग) print(a % b) # 2 — Modulus (शेष / remainder) print(a ** b) # 1419857 — Exponentiation (घात) # Real-world example: Grade calculator obtained = 378 total = 500 percentage = (obtained / total) * 100 print(f"Percentage: {percentage:.2f}%") # 75.60%
2. Comparison Operators — तुलना
x = 10 y = 20 print(x == y) # False — बराबर छ? print(x != y) # True — बराबर छैन? print(x > y) # False — ठूलो छ? print(x < y) # True — सानो छ? print(x >= y) # False — ठूलो वा बराबर? print(x <= y) # True — सानो वा बराबर? # Note: = र == फरक हो! # = मतलब assign गर्नु: x = 10 # == मतलब compare गर्नु: x == 10 → True/False
3. Logical Operators — and, or, not
age = 20 has_id = True # and — दुवै True हुनुपर्छ print(age >= 18 and has_id) # True print(age >= 18 and not has_id) # False # or — कम से कम एउटा True भए पुग्छ print(age < 18 or has_id) # True (has_id True छ) print(age < 18 or not has_id) # False # not — reverse गर्छ print(not has_id) # False print(not False) # True # Real example: Eligibility check marks = 75 attendance = 85 eligible = marks >= 60 and attendance >= 80 print(f"Exam दिन योग्य: {eligible}") # True
4. Assignment Operators
x = 10 # Assign: x = 10 x += 5 # x = x + 5 → 15 x -= 3 # x = x - 3 → 12 x *= 2 # x = x * 2 → 24 x /= 4 # x = x / 4 → 6.0 x //= 2 # x = x // 2 → 3.0 x %= 2 # x = x % 2 → 1.0 x **= 3 # x = x ** 3 → 1.0
5. Identity र Membership Operators
# is / is not — same object हो? (memory) a = [1, 2, 3] b = a c = [1, 2, 3] print(a is b) # True — same memory location print(a is c) # False — different objects print(a == c) # True — same values # in / not in — element छ? fruits = ["apple", "mango", "banana"] print("mango" in fruits) # True print("grape" not in fruits) # True print("P" in "Python") # True
# Basic input — हमेशा string return गर्छ name = input("What is your name? ") print(f"Hello, {name}!") # Integer input age = int(input("Your age: ")) print(f"You are {age} years old.") # Float input gpa = float(input("Your GPA: ")) # Multiple values on one line x, y = input("Enter two numbers separated by space: ").split() x, y = int(x), int(y) print(f"Sum = {x + y}") # Input validation (checking user input) score_input = input("Enter score (0-100): ") if score_input.isdigit(): score = int(score_input) print(f"Score: {score}") else: print("Invalid input! Numbers only.") # Real world: Simple calculator num1 = float(input("First number: ")) num2 = float(input("Second number: ")) operation = input("Operation (+, -, *, /): ") print(f"Result: {num1} {operation} {num2} = ", end="") if operation == "+": print(num1 + num2) elif operation == "-": print(num1 - num2) elif operation == "*": print(num1 * num2) elif operation == "/": print(num1 / num2 if num2 != 0 else "Error: Cannot divide by zero!")
# List create गर्ने students = ["Santosh", "Suresh", "Manisha", "Kamal"] scores = [85, 92, 78, 96, 88] mixed = ["Santosh", 20, 3.5, True] # mixed types OK nested = [[1, 2], [3, 4], [5, 6]] # list inside list empty = [] # Indexing — 0 बाट सुरु हुन्छ print(students[0]) # Santosh (पहिलो) print(students[-1]) # Kamal (अन्तिम) print(students[1:3]) # ['Suresh', 'Manisha'] — slicing print(students[::-1]) # reversed list # ===== ADDING ELEMENTS ===== students.append("Priya") # end मा add students.insert(1, "Binod") # index 1 मा insert students.extend(["Gita", "Ram"]) # multiple add # ===== REMOVING ELEMENTS ===== students.remove("Suresh") # value ले remove students.pop(0) # index ले remove, returns value students.pop() # last element remove del students[0] # delete by index students.clear() # सबै हटाउने # ===== USEFUL METHODS ===== nums = [5, 2, 8, 1, 9, 3] print(len(nums)) # 6 — length print(sum(nums)) # 28 — sum print(max(nums)) # 9 — maximum print(min(nums)) # 1 — minimum nums.sort() # [1,2,3,5,8,9] — sort in place nums.sort(reverse=True) # [9,8,5,3,2,1] — descending nums.reverse() # reverse in place print(sorted(nums)) # returns new sorted list print(nums.index(8)) # index of element 8 print(nums.count(3)) # कति पटक 3 आयो nums2 = nums.copy() # copy बनाउने # Check membership print(5 in nums) # True
# Tuple create — () use गर्छ my_data = ("Santosh", 20, "Kathmandu") coordinates = (27.7, 85.3) # Kathmandu lat/long colors = ("red", "green", "blue") single = ("only one",) # single item को लागि comma चाहिन्छ! empty = () # Access — list जस्तै index use गर्छ print(my_data[0]) # Santosh print(my_data[-1]) # Kathmandu print(my_data[1:3]) # (20, 'Kathmandu') # Tuple Unpacking — एकैचोटि variables मा assign name, age, city = my_data print(f"{name} is {age} years old, lives in {city}.") # Swap variables (tuple trick!) a, b = 10, 20 a, b = b, a # swap! print(a, b) # 20 10 # Methods (only 2!) t = (1, 2, 3, 2, 1) print(t.count(2)) # 2 — 2 कति पटक आयो print(t.index(3)) # 2 — 3 कुन index मा छ # Built-in functions print(len(t)) # 5 print(max(t)) # 3 print(min(t)) # 1 print(sum(t)) # 9 print(sorted(t)) # [1,1,2,2,3] returns list # Convert between list and tuple my_list = list(t) # tuple → list my_tuple = tuple(my_list) # list → tuple
# Dict create गर्ने — {} use गर्छ student = { "name": "Laxmi Tamang", "age": 19, "grade": "A", "city": "Biratnagar", "subjects": ["Math", "Science", "CS"] # list as value } # ===== ACCESSING VALUES ===== print(student["name"]) # Laxmi Tamang print(student.get("grade")) # A print(student.get("phone", "N/A")) # N/A (key छैन भने default) # ===== MODIFYING ===== student["age"] = 20 # update single value student["phone"] = "9841XXXXXX" # नयाँ key add student.update({"age": 21, "grade": "A+"}) # multiple update # ===== REMOVING ===== student.pop("phone") # specific key remove student.popitem() # last item remove del student["grade"] # delete by key # ===== LOOPING ===== info = {"name": "Ram", "age": 25, "city": "Kathmandu"} for key in info: print(key, "→", info[key]) for key, value in info.items(): print(f"{key}: {value}") # ===== METHODS ===== print(info.keys()) # dict_keys(['name','age','city']) print(info.values()) # dict_values(['Ram', 25, 'Kathmandu']) print(info.items()) # key-value pairs print(len(info)) # 3 print("name" in info) # True — key exists? # Nested dict (real-world example) school = { "class10A": {"teacher": "Mr. Bist", "students": 32}, "class10B": {"teacher": "Ms. Rana", "students": 28} } print(school["class10A"]["teacher"]) # Mr. Bist
# Set create — {} use गर्छ (dict जस्तो देखिन्छ तर key:value छैन) fruits = {"apple", "mango", "banana", "apple"} print(fruits) # {'mango', 'banana', 'apple'} — duplicate apple हट्यो # List को duplicates हटाउन set use गर्छौं numbers = [1, 2, 2, 3, 3, 4] unique = list(set(numbers)) # [1, 2, 3, 4] # Add/Remove fruits.add("grape") fruits.remove("mango") # error अाउँछ if not exists fruits.discard("xyz") # no error if not exists # Set Operations (Math जस्तै!) set_a = {1, 2, 3, 4, 5} set_b = {4, 5, 6, 7, 8} print(set_a | set_b) # Union: {1,2,3,4,5,6,7,8} print(set_a & set_b) # Intersection: {4,5} print(set_a - set_b) # Difference: {1,2,3} print(set_a ^ set_b) # Symmetric diff: {1,2,3,6,7,8} # Real example: Common students in two classes class_A = {"Ram", "Sita", "Hari", "Gita"} class_B = {"Sita", "Gita", "Binod"} common = class_A & class_B print(f"In both classes: {common}") # {'Sita', 'Gita'}
# Simple if temperature = 35 if temperature > 30: print("It is hot! Drink water.") # if-else age = 16 if age >= 18: print("You can vote.") else: print("You cannot vote — not old enough.") # if-elif-else (Grade system) marks = 78 if marks >= 90: grade = "A+" elif marks >= 80: grade = "A" elif marks >= 70: grade = "B" elif marks >= 60: grade = "C" elif marks >= 40: grade = "D" else: grade = "F (Fail)" print(f"Marks: {marks} → Grade: {grade}") # Nested if username = "admin" password = "1234" if username == "admin": if password == "1234": print("Login successful!") else: print("Wrong password!") else: print("User not found!") # Ternary (one-line if-else) score = 75 result = "Pass" if score >= 40 else "Fail" print(result) # Pass # match-case (Python 3.10+) — switch जस्तो day = "Monday" match day: case "Monday" | "Tuesday" | "Wednesday": print("Office day") case "Saturday" | "Sunday": print("Weekend!") case _: print("Regular day")
# For loop — sequence iterate गर्छ # range(n) — 0 देखि n-1 सम्म for i in range(5): print(i, end=" ") # 0 1 2 3 4 # range(start, stop, step) for i in range(1, 11): # 1 to 10 print(f"Table of 5: 5 × {i} = {5*i}") for i in range(10, 0, -1): # countdown print(i, end=" ") # Iterating over list students = ["Ram", "Sita", "Hari"] for student in students: print(f"Hello, {student}!") # enumerate — index र value दुवै for i, student in enumerate(students, 1): print(f"{i}. {student}") # Iterating string for char in "Nepal": print(char) # Iterating dict info = {"name": "Santosh", "age": 20} for key, value in info.items(): print(f"{key}: {value}") # zip — दुई list एकसाथ iterate names = ["Santosh", "Suresh", "Manisha"] scores = [85, 92, 78] for name, score in zip(names, scores): print(f"{name}: {score}") # break, continue, pass for i in range(10): if i == 5: break # loop बन्द गर्छ if i % 2 == 0: continue # यो iteration skip गर्छ print(i) # for-else for i in range(5): print(i) else: print("Loop successfully completed!")
# Basic while loop count = 1 while count <= 5: print(f"Count: {count}") count += 1 # यो नभए infinite loop हुन्छ! # Login system (real-world example) correct_password = "python123" attempts = 0 while attempts < 3: password = input("Password: ") if password == correct_password: print("✅ Login successful!") break else: attempts += 1 print(f"❌ Wrong! {3-attempts} attempts left.") else: print("🔒 Account locked!") # Do-while simulation (Python मा do-while छैन) while True: answer = input("Continue? (yes/no): ") if answer.lower() == "no": break
# ===== LIST COMPREHENSION ===== # Syntax: [expression for item in iterable if condition] # Normal way (4 lines) squares = [] for i in range(1, 6): squares.append(i ** 2) # Comprehension way (1 line!) squares = [i ** 2 for i in range(1, 6)] print(squares) # [1, 4, 9, 16, 25] # With condition — even numbers only evens = [i for i in range(20) if i % 2 == 0] # Transform strings names = ["santosh", "suresh", "manisha"] upper_names = [name.upper() for name in names] # Filter passing students scores = {"Ram": 75, "Sita": 35, "Hari": 88, "Gita": 45} passed = [name for name, s in scores.items() if s >= 40] print(passed) # ['Ram', 'Hari', 'Gita'] # ===== DICT COMPREHENSION ===== # Syntax: {key: value for item in iterable} squared_dict = {x: x**2 for x in range(1, 6)} print(squared_dict) # {1:1, 2:4, 3:9, 4:16, 5:25} word_lengths = {word: len(word) for word in ["apple", "mango", "banana"]} # ===== SET COMPREHENSION ===== unique_squares = {x**2 for x in [1, -1, 2, -2, 3]} print(unique_squares) # {1, 4, 9}
# Basic function def greet(): """This function prints a greeting""" print("Hello!") greet() # Call गर्ने # Function with parameters def greet_person(name, city="Nepal"): # default value print(f"Hello {name}, from {city}!") greet_person("Santosh") # positional greet_person("Suresh", "Pokhara") # positional greet_person(city="Biratnagar", name="Gita") # keyword # Function with return def add(a, b): return a + b result = add(10, 20) print(result) # 30 # Multiple return values def min_max(numbers): return min(numbers), max(numbers) smallest, largest = min_max([3, 1, 8, 2]) print(f"Min: {smallest}, Max: {largest}") # *args — variable number of arguments def total(*numbers): return sum(numbers) print(total(1, 2, 3)) # 6 print(total(10, 20, 30, 40)) # 100 # **kwargs — keyword arguments as dict def student_info(**details): for key, value in details.items(): print(f" {key}: {value}") student_info(name="Ram", age=20, city="Kathmandu") # Real-world: Grade calculator function def calculate_grade(marks, total=100): """Calculate grade from marks""" percentage = (marks / total) * 100 if percentage >= 90: return "A+" elif percentage >= 80: return "A" elif percentage >= 70: return "B" elif percentage >= 60: return "C" elif percentage >= 40: return "D" else: return "F"
Lambda Functions — Anonymous Functions
# Lambda syntax: lambda arguments: expression square = lambda x: x ** 2 print(square(5)) # 25 add = lambda a, b: a + b print(add(3, 4)) # 7 # Lambda with sort students = [{"name": "Ram", "gpa": 3.5}, {"name": "Sita", "gpa": 3.9}, {"name": "Hari", "gpa": 3.2}] students.sort(key=lambda s: s["gpa"], reverse=True) # map() — list को हर element मा function apply nums = [1, 2, 3, 4, 5] doubled = list(map(lambda x: x * 2, nums)) print(doubled) # [2, 4, 6, 8, 10] # filter() — condition true भएकालाई मात्र राख्छ evens = list(filter(lambda x: x % 2 == 0, nums)) print(evens) # [2, 4] # reduce() — सबै elements combine गर्छ from functools import reduce product = reduce(lambda x, y: x * y, nums) print(product) # 120 (1*2*3*4*5)
Lambda Practice
A list of dicts (students with name, marks) लिनुहोस्। Lambda use गरेर marks अनुसार sort गर्नुहोस्। filter() use गरेर 60+ marks भएका मात्र छान्नुहोस्। map() use गरेर प्रत्येकको percentage calculate गर्नुहोस्।
Scope — Variable को Reach
# ===== SCOPE ===== x = 10 # global variable def my_func(): y = 20 # local variable — function बाहिर accessible छैन print(x) # global x access हुन्छ print(y) def modify_global(): global x # global variable modify गर्न x = 100 # ===== CLOSURES ===== def multiplier(factor): def multiply(number): return number * factor # outer variable access return multiply double = multiplier(2) triple = multiplier(3) print(double(5)) # 10 print(triple(5)) # 15
Closure Practice
एउटा counter() closure function बनाउनुहोस् जसले हरेक call मा count बढाओस् र return गरोस्। State बाहिर नदेखिने गरी!
Decorator — Function Wrapper
# ===== DECORATORS ===== # Function को behaviour change गर्छ बिना code modify गरी def my_decorator(func): def wrapper(*args, **kwargs): print("⬆️ Before function call") result = func(*args, **kwargs) print("⬇️ After function call") return result return wrapper @my_decorator def say_hello(name): print(f"Hello, {name}!") say_hello("Santosh") # Practical: Timer decorator import time def timer(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f"Time: {end-start:.4f} seconds") return result return wrapper
Decorator Practice
एउटा @log decorator बनाउनुहोस् जसले function को नाम, arguments र return value print गरोस्। त्यसपछि @timer decorator बनाउनुहोस् जसले execution time measure गरोस्।
# Generator function — yield use गर्छ def count_up(n): i = 1 while i <= n: yield i # return जस्तो, तर pause गर्छ i += 1 for num in count_up(5): print(num) # 1 2 3 4 5 # Generator expression (list comprehension जस्तो, () use गर्छ) gen = (x**2 for x in range(1000000)) # memory efficient! print(next(gen)) # 0 print(next(gen)) # 1 # Fibonacci generator def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b fib = fibonacci() for _ in range(10): print(next(fib), end=" ") # 0 1 1 2 3 5 8 13 21 34
# Basic try-except try: num = int(input("Enter a number: ")) result = 10 / num print(f"Result: {result}") except ValueError: print("❌ Error: Numbers only!") except ZeroDivisionError: print("❌ Error: Cannot divide by zero!") except Exception as e: print(f"❌ Unexpected error: {e}") else: print("✅ No error! Successfully executed.") finally: print("This always runs — with or without error") # Common Exceptions # ValueError — wrong type value # TypeError — wrong type operation # NameError — variable defined छैन # IndexError — index out of range # KeyError — dict key छैन # FileNotFoundError — file छैन # ZeroDivisionError — 0 ले भाग # Raising custom exceptions def validate_age(age): if age < 0: raise ValueError("Age cannot be less than 0!") if age > 150: raise ValueError("Abnormal age value!") return age # Custom Exception class class InsufficientFundsError(Exception): def __init__(self, amount, balance): self.message = f"Cannot withdraw Rs.{amount}. Balance: Rs.{balance}" super().__init__(self.message)
# File Modes: # "r" — read (default) # "w" — write (नयाँ file बनाउने वा existing overwrite) # "a" — append (existing file मा add गर्ने) # "r+" — read and write # "rb" — read binary (images, videos) # ===== WRITING ===== with open("students.txt", "w", encoding="utf-8") as f: f.write("Santosh Bist\n") f.write("Suresh Rai\n") f.writelines(["Manisha Tamang\n", "Kamal Shrestha\n"]) # ===== READING ===== with open("students.txt", "r", encoding="utf-8") as f: content = f.read() # सबै पढ्ने print(content) with open("students.txt", "r") as f: lines = f.readlines() # list of lines for line in lines: print(line.strip()) # ===== APPEND ===== with open("students.txt", "a") as f: f.write("Priya Gurung\n") # ===== os module — file operations ===== import os print(os.getcwd()) # current directory print(os.listdir(".")) # files in directory print(os.path.exists("students.txt")) # file exists? os.rename("students.txt", "class.txt") # rename os.remove("class.txt") # delete os.makedirs("new_folder") # folder create # CSV file handling import csv with open("data.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerow(["Name", "Age", "City"]) writer.writerow(["Santosh", 20, "Kathmandu"]) writer.writerow(["Sita", 19, "Pokhara"])
# Import ways import math import math as m # alias from math import sqrt, pi # specific from math import * # सबै (avoid गर्नुहोस्) # ===== MATH MODULE ===== import math print(math.pi) # 3.14159... print(math.sqrt(25)) # 5.0 print(math.ceil(4.3)) # 5 — माथि print(math.floor(4.9)) # 4 — तल print(math.pow(2, 10)) # 1024.0 print(math.factorial(5)) # 120 print(math.log(100, 10)) # 2.0 # ===== RANDOM MODULE ===== import random print(random.random()) # 0.0 to 1.0 print(random.randint(1, 100)) # 1-100 random int print(random.choice(["Heads", "Tails"])) # random choice names = ["Ram", "Sita", "Hari"] random.shuffle(names) # shuffle in place print(random.sample(names, 2)) # 2 random items # ===== DATETIME MODULE ===== from datetime import datetime, date, timedelta now = datetime.now() print(f"Current time: {now}") print(f"Date: {now.strftime('%Y-%m-%d')}") print(f"Time: {now.strftime('%H:%M:%S')}") birthday = date(2000, 5, 15) today = date.today() age_days = (today - birthday).days print(f"You have lived {age_days} days!") # ===== OWN MODULE बनाउने ===== # File: my_utils.py def greet(name): return f"Hello, {name}!" def add(a, b): return a + b # Main file: main.py import my_utils print(my_utils.greet("Santosh"))
Popular Third-Party Libraries
pandas
Data manipulation र analysis। Excel/CSV files read गर्न, data clean गर्न use हुन्छ।
numpy
Mathematical operations, arrays, matrix calculations। Data science को base।
matplotlib
Charts, graphs, plots बनाउने। Data visualization।
requests
Internet बाट data लिने। APIs call गर्ने। Web scraping को base।
BeautifulSoup
Websites बाट data scrape गर्ने। HTML parse गर्ने।
Flask / Django
Web applications बनाउने। हाम्रो final goal!
# ===== REGEX ===== import re text = "Email: [email protected], Phone: 9841234567" # Find email email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' emails = re.findall(email_pattern, text) print(emails) # ['[email protected]'] # Phone validation phone = "9841234567" if re.match(r'^98\d{8}$', phone): print("Valid Nepal phone number!") # Replace clean = re.sub(r'\s+', ' ', " extra spaces here ") # Common patterns # \d — digit (0-9) # \w — word character (a-z, A-Z, 0-9, _) # \s — whitespace # . — any character # * — 0 or more # + — 1 or more # ^ — start, $ — end
Regex Practice
एउटा function बनाउनुहोस् जसले Nepal को phone number (98XXXXXXXX or 97XXXXXXXX), email address, र URL validate गरोस् — regex use गरेर।
JSON — JavaScript Object Notation
# ===== JSON ===== import json # Python dict → JSON string student = {"name": "Santosh", "age": 20, "scores": [85, 92, 78]} json_string = json.dumps(student, indent=4) print(json_string) # JSON string → Python dict data = json.loads(json_string) print(data["name"]) # JSON file write/read with open("student.json", "w") as f: json.dump(student, f, indent=4) with open("student.json", "r") as f: loaded = json.load(f) # API call with requests import requests response = requests.get("https://api.github.com/users/octocat") if response.status_code == 200: data = response.json() print(data["name"]) # The Octocat
JSON & API Practice
Python requests library use गरेर https://jsonplaceholder.typicode.com/users API call गर्नुहोस्। JSON response लिएर users को name र email print गर्नुहोस्। Data लाई JSON file मा save गर्नुहोस्।
# ===== BASIC CLASS ===== class Student: """Student class — stores student data and behavior""" school_name = "SBIST" # class variable — सबैले share गर्छन् def __init__(self, name, age, grade): # constructor self.name = name # instance variables self.age = age self.grade = grade self._marks = [] # _ = "protected" def introduce(self): return f"I am {self.name}, {self.age} years old, Grade {self.grade}" def add_mark(self, mark): if 0 <= mark <= 100: self._marks.append(mark) else: print("Invalid mark!") def get_average(self): return sum(self._marks) / len(self._marks) if self._marks else 0 def __str__(self): # print() ले call गर्छ return f"Student({self.name}, {self.age})" def __repr__(self): # debugging को लागि return f"Student(name='{self.name}', age={self.age})" # Objects create गर्ने s1 = Student("Santosh", 20, "A") s2 = Student("Sita", 19, "B") print(s1.introduce()) s1.add_mark(85) s1.add_mark(92) print(f"Average: {s1.get_average()}") print(s1) # calls __str__ print(Student.school_name) # class variable
Classes Practice
एउटा Car class बनाउनुहोस् जसमा make, model, year, mileage हुन्छ। Methods: drive(km) mileage बढाउने, info() सबै details print गर्ने। Magic __str__ implement गर्नुहोस्।
Single Inheritance
# ===== INHERITANCE ===== class Person: # Parent/Base class def __init__(self, name, age): self.name = name self.age = age def greet(self): return f"Hello! I am {self.name}." class Teacher(Person): # Child class — Person inherit def __init__(self, name, age, subject): super().__init__(name, age) # parent constructor call self.subject = subject def teach(self): return f"I teach {self.subject}." def greet(self): # Override parent method return f"Hello! I am Sir {self.name}." teacher = Teacher("Santosh", 30, "Python") print(teacher.greet()) # overridden method print(teacher.teach()) print(isinstance(teacher, Person)) # True print(isinstance(teacher, Teacher)) # True
Multiple Inheritance & Method Resolution
# Multiple inheritance — दुई parents बाट inherit class Animal: def breathe(self): return "Breathing..." class Pet: def play(self): return "Playing!" class Dog(Animal, Pet): # दुवै inherit गर्छ def bark(self): return "Woof!" rex = Dog() print(rex.breathe()) # Animal बाट print(rex.play()) # Pet बाट print(rex.bark()) # Dog को आफ्नै # isinstance र issubclass check print(isinstance(rex, Animal)) # True print(issubclass(Dog, Animal)) # True print(Dog.__mro__) # Method Resolution Order
Inheritance Practice
Vehicle base class बनाउनुहोस् (make, model, speed)। त्यसबाट Car, Motorcycle, Truck inherit गर्नुहोस्। हरेकमा unique method र overridden describe() method राख्नुहोस्।
Encapsulation — Data Hiding
# ===== ENCAPSULATION ===== class BankAccount: def __init__(self, owner, balance): self.owner = owner self.__balance = balance # __ = private def deposit(self, amount): if amount > 0: self.__balance += amount print(f"Rs.{amount} deposited.") def withdraw(self, amount): if 0 < amount <= self.__balance: self.__balance -= amount print(f"Rs.{amount} withdrawn.") else: print("❌ Insufficient funds!") @property def balance(self): # getter return self.__balance acc = BankAccount("Santosh", 10000) acc.deposit(5000) acc.withdraw(2000) print(f"Balance: Rs.{acc.balance}")
Magic Methods (Dunder Methods)
| Method | कहिले call हुन्छ | Example |
|---|---|---|
__init__ | Object create हुँदा | Student("Ram") |
__str__ | print(obj) गर्दा | Human-readable string |
__len__ | len(obj) गर्दा | Object को length |
__add__ | obj1 + obj2 गर्दा | Custom addition |
__eq__ | obj1 == obj2 गर्दा | Equality check |
__del__ | Object delete हुँदा | Cleanup |
Polymorphism — एउटा Interface, धेरै रूप
# Polymorphism — same method name, different behaviour class Shape: def area(self): return 0 class Circle(Shape): def __init__(self, r): self.r = r def area(self): return 3.14 * self.r ** 2 class Rectangle(Shape): def __init__(self, w, h): self.w=w; self.h=h def area(self): return self.w * self.h # Polymorphism in action — एउटै function सबैलाई handle गर्छ shapes = [Circle(5), Rectangle(4, 6), Circle(3)] for shape in shapes: print(f"{shape.__class__.__name__}: area = {shape.area():.2f}")
OOP Full Project
एउटा Library system OOP मा बनाउनुहोस्: Book class (title, author, ISBN), Member class (name, id), Library class (add_book, borrow_book, return_book, list_books)। Encapsulation use गरेर balance र books protect गर्नुहोस्।
# ===== CONTEXT MANAGERS ===== class FileManager: def __init__(self, filename, mode): self.filename = filename self.mode = mode def __enter__(self): self.file = open(self.filename, self.mode) return self.file def __exit__(self, *args): self.file.close() with FileManager("test.txt", "w") as f: f.write("Hello!") # ===== DATACLASSES ===== from dataclasses import dataclass, field @dataclass class Product: name: str price: float quantity: int = 0 tags: list = field(default_factory=list) def total_value(self): return self.price * self.quantity laptop = Product("Laptop", 85000, 5) print(laptop) # Product(name='Laptop', price=85000, quantity=5) # ===== TYPE HINTS ===== def greet(name: str, times: int = 1) -> str: return (f"Hello, {name}! " ) * times # ===== WALRUS OPERATOR := (Python 3.8+) ===== numbers = [1, 2, 3, 4, 5] if (n := len(numbers)) > 3: print(f"List has {n} elements") # ===== UNPACKING ===== first, *rest = [1, 2, 3, 4, 5] print(first) # 1 print(rest) # [2, 3, 4, 5] *start, last = [1, 2, 3, 4, 5] print(last) # 5
# Virtual Environment किन चाहिन्छ? # हर project को आफ्नै dependencies हुन्छन् # Project A को Flask 2.0 र Project B को Flask 3.0 चाहिन सक्छ # Virtual Environment बनाउने python -m venv mero_project_env # Activate गर्ने # Windows: mero_project_env\Scripts\activate # Mac/Linux: source mero_project_env/bin/activate # Deactivate deactivate # pip — Python Package Installer pip install flask # install pip install flask==2.0.0 # specific version pip install requests pandas # multiple packages pip uninstall flask # uninstall pip list # installed packages pip show flask # package details pip freeze > requirements.txt # save all deps pip install -r requirements.txt # install from file pip install --upgrade pip # update pip
pip install flask
Flask App Structure
my_flask_app/ ├── app.py # Main application file ├── requirements.txt # pip freeze > requirements.txt ├── templates/ # HTML files (Jinja2) │ ├── base.html │ └── index.html └── static/ # CSS, JS, Images ├── css/style.css └── js/main.js
python app.py run गर्नुहोस्। Browser मा http://127.0.0.1:5000 खोल्नुहोस्। debug=True राख्नुहोस् — code save गर्दा auto-reload हुन्छ!from flask import Flask, render_template, request, redirect, url_for, jsonify app = Flask(__name__) # Flask app create गर्ने # ===== ROUTES ===== # Route = URL + function @app.route("/") # Home page def home(): return "<h1>🐍 Hello! This is my first Flask app!</h1>" @app.route("/about") def about(): return render_template("about.html") # URL parameters @app.route("/user/<name>") def user_profile(name): return f"<h2>Hello, {name}!</h2>" @app.route("/calculate/<int:num1>/<int:num2>") def calculate(num1, num2): return jsonify({"sum": num1 + num2, "product": num1 * num2}) # HTTP Methods (GET र POST) @app.route("/login", methods=["GET", "POST"]) def login(): if request.method == "POST": username = request.form["username"] password = request.form["password"] if username == "admin" and password == "1234": return redirect(url_for("home")) return "Invalid credentials!" return render_template("login.html") # JSON API endpoint students_db = [ {"id": 1, "name": "Santosh", "grade": "A"}, {"id": 2, "name": "Sita", "grade": "B"}, ] @app.route("/api/students") def get_students(): return jsonify(students_db) if __name__ == "__main__": app.run(debug=True) # development mode
Jinja2 Templates — HTML + Python
<!-- templates/base.html — Base template --> <!DOCTYPE html> <html> <head> <title>{% block title %}My App{% endblock %}</title> </head> <body> <!-- Navigation --> <nav> <a href="{{ url_for('home') }}">Home</a> <a href="{{ url_for('about') }}">About</a> </nav> {% block content %}{% endblock %} </body> </html> <!-- templates/students.html --> {% extends "base.html" %} {% block content %} <h1>Students List</h1> <!-- Variable --> <p>Welcome, {{ username }}!</p> <!-- For loop --> <ul> {% for student in students %} <li>{{ loop.index }}. {{ student.name }} — {{ student.grade }}</li> {% endfor %} </ul> <!-- If condition --> {% if students|length > 0 %} <p>Total: {{ students|length }} students</p> {% else %} <p>No students found.</p> {% endif %} {% endblock %}
Flask Forms — GET & POST
from flask import Flask, render_template, request, redirect, url_for import sqlite3 app = Flask(__name__) def get_db(): conn = sqlite3.connect("school.db") conn.row_factory = sqlite3.Row return conn def init_db(): conn = get_db() conn.execute(""" CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER, grade TEXT ) """) conn.commit() conn.close() @app.route("/students") def students(): conn = get_db() all_students = conn.execute("SELECT * FROM students").fetchall() conn.close() return render_template("students.html", students=all_students) @app.route("/add", methods=["GET", "POST"]) def add_student(): if request.method == "POST": name = request.form["name"] age = request.form["age"] grade = request.form["grade"] conn = get_db() conn.execute("INSERT INTO students (name,age,grade) VALUES (?,?,?)", (name, age, grade)) conn.commit() conn.close() return redirect(url_for("students")) return render_template("add.html") @app.route("/delete/<int:id>") def delete_student(id): conn = get_db() conn.execute("DELETE FROM students WHERE id=?", (id,)) conn.commit() conn.close() return redirect(url_for("students")) if __name__ == "__main__": init_db() app.run(debug=True)
Flask Project Structure — Best Practice
my_flask_project/ │ ├── app.py # Main application ├── requirements.txt # pip freeze > requirements.txt ├── .env # Secret keys (NEVER share!) │ ├── templates/ # HTML files │ ├── base.html # Base template │ ├── index.html │ ├── login.html │ └── students.html │ ├── static/ # CSS, JS, Images │ ├── css/ │ │ └── style.css │ ├── js/ │ │ └── main.js │ └── images/ │ ├── models.py # Database models ├── routes.py # Route definitions └── config.py # Configuration
Next Steps — What to learn after Flask?
Flask-SQLAlchemy
Database को लागि ORM। SQL लेख्नु नपर्ने — Python objects use गर्ने।
Flask-Login
User authentication — login, logout, session management।
Flask-WTF
Form handling र validation — secure forms बनाउन।
Django
Bigger framework। Full-featured — Admin panel, ORM, Auth सबै built-in।
FastAPI
Modern, fast API development। Automatic documentation। Async support।
Deployment
Heroku, Render, AWS, DigitalOcean मा website deploy गर्ने।
बधाई छ! Congratulations!
तपाईंले Python को A to Z complete गर्नुभयो — Introduction देखि Flask Web Development सम्म। अब practice गर्नुहोस् र आफ्नो project बनाउनुहोस्!
🇳🇵 Mr. Santosh Bist — SBIST | www.sbist.com.np
Jinja2 के हो? — What is Jinja2?
Jinja2 एउटा templating engine हो जुन Flask सँग built-in आउँछ। यसले HTML files भित्र Python-like logic (variables, loops, conditions) use गर्न दिन्छ। Server बाट data HTML मा inject गर्ने मुख्य तरिका यही हो।
Variables
Double curly braces भित्र Python variables राख्नुहोस्। Flask बाट pass भएको data HTML मा देखाउँछ।
Statements
Logic tags — if/else, for loops, block, extends सबै यसभित्र लेखिन्छन्।
Comments
HTML मा नदेखिने Jinja2 comments। Browser source मा पनि देखिँदैन।
Filters
Variables लाई transform गर्ने — upper, lower, length, default आदि।
Basic Syntax — मूल नियमहरू
{# यो Jinja2 comment हो — browser मा देखिँदैन #} {# 1. Variables — double curly braces #} <h1>{{ title }}</h1> <p>Welcome, {{ user.name }}!</p> <p>Price: Rs. {{ product.price }}</p> {# 2. Statements — percent tags #} {% if user.is_logged_in %} <p>Hello, {{ user.name }}!</p> {% else %} <p>Please login.</p> {% endif %} {# 3. For loop #} {% for item in items %} <li>{{ item }}</li> {% endfor %}
Variables — Flask बाट Data Pass गर्ने
app.py — Data पठाउने
@app.route("/") def home(): return render_template("home.html", name="Santosh", age=20, city="Kathmandu", skills=["Python", "Flask", "MySQL"], is_admin=True )
home.html — Data प्रयोग गर्ने
<h1>Hello, {{ name }}!</h1> <p>Age: {{ age }}</p> <p>City: {{ city }}</p> {# List loop #} <ul> {% for skill in skills %} <li>{{ skill }}</li> {% endfor %} </ul> {% if is_admin %} <span>🛡️ Admin</span> {% endif %}
Filters — Data Transform गर्ने
Filters variable को value लाई modify गर्छ। Pipe | sign use गरेर apply गरिन्छ।
{# String filters #} {{ name | upper }} {# SANTOSH #} {{ name | lower }} {# santosh #} {{ name | title }} {# Santosh Bist #} {{ name | capitalize }} {# Santosh #} {{ name | length }} {# 7 (character count) #} {{ name | reverse }} {# hsotnaS #} {{ bio | truncate(50) }} {# 50 characters मा काट्छ... #} {{ desc | striptags }} {# HTML tags हटाउँछ #} {# Number filters #} {{ price | round(2) }} {# 99.99 #} {{ amount | abs }} {# Absolute value #} {# Safety filter — HTML escape गर्छ (XSS बाट बचाउँछ) #} {{ user_input | e }} {{ user_input | escape }} {# Default value — variable None भए #} {{ nickname | default("No nickname") }} {# List filters #} {{ skills | join(", ") }} {# Python, Flask, MySQL #} {{ numbers | sort }} {{ numbers | first }} {{ numbers | last }} {{ numbers | max }} {{ numbers | min }} {{ numbers | sum }} {# Safe filter — HTML as-is render गर्छ (trusted content मा मात्र!) #} {{ html_content | safe }}
| safe सावधानीपूर्वक प्रयोग गर्नुहोस्! User-submitted content मा | safe कहिल्यै नगर्नुहोस् — XSS attack हुन्छ। Only trusted, server-generated HTML मा use गर्नुहोस्।Control Flow — if / elif / else
{# Basic if #} {% if score >= 90 %} <span class="grade-a">Grade: A+</span> {% elif score >= 80 %} <span class="grade-b">Grade: A</span> {% elif score >= 60 %} <span class="grade-c">Grade: B</span> {% else %} <span class="grade-f">Grade: F</span> {% endif %} {# Inline if (ternary) #} <p class="{{ 'active' if user.logged_in else 'inactive' }}">Status</p> {# Check if variable exists / is not None #} {% if user is defined and user is not none %} <p>{{ user.name }}</p> {% endif %} {# Check list is not empty #} {% if students %} {# Show table #} {% else %} <p>No students found.</p> {% endif %}
For Loops — List Data Display गर्ने
{# Basic for loop #} <ul> {% for student in students %} <li>{{ student.name }} — Grade: {{ student.grade }}</li> {% endfor %} </ul> {# loop.* special variables — Jinja2 को powerful feature #} <table> {% for s in students %} <tr class="{{ 'even' if loop.even else 'odd' }}"> <td>{{ loop.index }}</td> {# 1, 2, 3... (1 बाट सुरु) #} <td>{{ loop.index0 }}</td> {# 0, 1, 2... (0 बाट सुरु) #} <td>{{ loop.revindex }}</td> {# Reverse index #} <td>{{ s.name }}</td> <td>{{ s.grade }}</td> </tr> {% else %} {# List empty भएमा — for-else #} <tr><td colspan="5">No records found.</td></tr> {% endfor %} </table> {# loop.first र loop.last — पहिलो र अन्तिम item detect गर्ने #} {% for item in menu %} {% if loop.first %}<nav>{% endif %} <a href="{{ item.url }}">{{ item.label }}</a> {% if loop.last %}</nav>{% endif %} {% endfor %} {# Dictionary loop #} {% for key, value in student.items() %} <p>{{ key }}: {{ value }}</p> {% endfor %}
| loop.* Variable | के गर्छ | Example |
|---|---|---|
loop.index | Current index (1 बाट सुरु) | 1, 2, 3... |
loop.index0 | Current index (0 बाट सुरु) | 0, 1, 2... |
loop.revindex | Reverse index (1 बाट) | 5, 4, 3... |
loop.first | पहिलो item? True/False | True (1st only) |
loop.last | अन्तिम item? True/False | True (last only) |
loop.even | Even index? (2, 4, 6...) | True/False |
loop.odd | Odd index? (1, 3, 5...) | True/False |
loop.length | Total items count | 10 |
Template Inheritance — Base Template बनाउने
सबैभन्दा important Jinja2 feature। एउटा base.html बनाउनुहोस् — बाँकी सबै pages त्यसैलाई extend गर्छन्। Header, footer, nav एकपटक मात्र लेख्नुपर्छ।
templates/base.html — Parent Template
<!DOCTYPE html> <html> <head> <title>{% block title %}My Site{% endblock %}</title> <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}"> {% block extra_css %}{% endblock %} </head> <body> {# Navigation — सबै pages मा देखिन्छ #} <nav> <a href="{{ url_for('home') }}">Home</a> <a href="{{ url_for('about') }}">About</a> {% if current_user.is_authenticated %} <a href="{{ url_for('logout') }}">Logout</a> {% else %} <a href="{{ url_for('login') }}">Login</a> {% endif %} </nav> {# Flash messages — सबै pages मा देखाउन #} {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} <div class="alert {{ category }}">{{ message }}</div> {% endfor %} {% endif %} {% endwith %} {# Main content block — child pages यहाँ fill गर्छन् #} <main> {% block content %}{% endblock %} </main> <footer> <p>{% block footer %}© 2025 SBIST{% endblock %}</p> </footer> {% block extra_js %}{% endblock %} </body></html>
templates/index.html — Child Template
{# base.html extend गर्ने #} {% extends "base.html" %} {# Title block override गर्ने #} {% block title %}Home — Student Portal{% endblock %} {# Extra CSS थप्न सकिन्छ #} {% block extra_css %} <link rel="stylesheet" href="{{ url_for('static', filename='css/home.css') }}"> {% endblock %} {# Main content यहाँ लेख्ने #} {% block content %} <h1>Student List</h1> <table> {% for s in students %} <tr> <td>{{ loop.index }}</td> <td>{{ s.name }}</td> <td>{{ s.grade }}</td> </tr> {% else %} <tr><td>No students.</td></tr> {% endfor %} </table> {% endblock %} {# Extra JS — page-specific scripts #} {% block extra_js %} <script src="{{ url_for('static', filename='js/table.js') }}"></script> {% endblock %}
url_for() — Links बनाउने सही तरिका
href="/students" को सट्टा href="{{ url_for('students') }}" लेख्नुहोस् — app restructure गर्दा links automatically update हुन्छन्।{# Basic route link #} <a href="{{ url_for('home') }}">Home</a> <a href="{{ url_for('about') }}">About</a> {# Route with parameters — dynamic URL #} <a href="{{ url_for('student_detail', id=student.id) }}">View</a> <a href="{{ url_for('edit_student', id=s.id) }}">Edit</a> {# Static files — CSS, JS, Images #} <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}"> <script src="{{ url_for('static', filename='js/main.js') }}"></script> <img src="{{ url_for('static', filename='images/logo.png') }}" alt="Logo"> {# Form action — POST form को लागि #} <form method="POST" action="{{ url_for('add_student') }}"> ... </form>
Macros — Reusable Template Components
Macro भनेको Jinja2 को function हो। एकपटक define गर्नुहोस् — जतासुकै use गर्नुहोस्।
{# macros.html — यहाँ macro define गर्ने #} {% macro render_field(label, name, type="text", value="", required=false) %} <div class="form-group"> <label for="{{ name }}">{{ label }}</label> <input type="{{ type }}" id="{{ name }}" name="{{ name }}" value="{{ value }}" {{ 'required' if required }}> </div> {% endmacro %} {% macro student_card(student) %} <div class="card"> <h3>{{ student.name }}</h3> <p>Grade: {{ student.grade }}</p> <a href="{{ url_for('edit_student', id=student.id) }}">Edit</a> </div> {% endmacro %}
{% extends "base.html" %}
{% from "macros.html" import render_field, student_card %}
{% block content %}
<h1>Add Student</h1>
<form method="POST">
{# एकपटक macro define गर्यो — यसरी use गर्न सकिन्छ #}
{{ render_field("Full Name", "name", required=true) }}
{{ render_field("Age", "age", type="number") }}
{{ render_field("Email", "email", type="email", required=true) }}
<button type="submit">Save</button>
</form>
{# Cards loop मा macro use #}
{% for student in students %}
{{ student_card(student) }}
{% endfor %}
{% endblock %}include — Partial Templates
{# templates/_navbar.html, _footer.html जस्ता partials include गर्ने #} {% include "_navbar.html" %} {% include "_sidebar.html" %} {# File नभेटे error नआउन ignore=missing #} {% include "_ads.html" ignore missing %} {# with context — parent template को variables share गर्ने #} {% include "_card.html" with context %} {# without context — isolated include #} {% include "_widget.html" without context %}
Custom Filters — आफ्नो Filter बनाउने
# Custom filter define गर्ने — app.py मा @app.template_filter("nepali_price") def nepali_price(amount): """Format price with Rs. prefix and comma""" return f"Rs. {amount:,}" @app.template_filter("short_date") def short_date(dt): """Format datetime to readable date""" return dt.strftime("%d %b %Y") # 22 Apr 2025 @app.template_filter("grade_badge") def grade_badge(grade): """Return CSS class based on grade""" colors = {"A+": "green", "A": "blue", "B": "yellow", "F": "red"} return colors.get(grade, "gray")
<p>Price: {{ product.price | nepali_price }}</p> {# Output: Price: Rs. 1,500 #} <p>Date: {{ student.created_at | short_date }}</p> {# Output: Date: 22 Apr 2025 #} <span class="badge {{ student.grade | grade_badge }}">{{ student.grade }}</span> {# Output: <span class="badge green">A+</span> #}
Global Template Variables — Context Processors
from datetime import datetime @app.context_processor def inject_globals(): """Variables automatically available in all templates""" return { "current_year": datetime.now().year, "site_name": "SBIST Student Portal", "version": "1.0.0" }
<footer> {# current_year render_template() मा pass नगरी पनि available छ #} <p>© {{ current_year }} {{ site_name }} v{{ version }}</p> </footer>
Jinja2 Template Practice
एउटा Flask app बनाउनुहोस् जसमा: base.html (navbar + footer), index.html (student table with loop.index, loop.even/odd striping), add.html (form with macro), र एउटा custom nepali_price filter implement गर्नुहोस्।
MySQL के हो? — What is MySQL?
MySQL
World को सबैभन्दा popular open-source relational database। Data tables मा store हुन्छ — rows र columns को format मा।
mysql-connector-python
Official MySQL library for Python। Oracle ले बनाएको। pip install mysql-connector-python गरेर use गर्न सकिन्छ।
PyMySQL
Pure Python MySQL driver। mysql-connector को alternative। pip install PyMySQL। Flask-SQLAlchemy सँग राम्रो काम गर्छ।
Why MySQL over SQLite?
Production apps मा MySQL use हुन्छ। Multiple users, large data, server-based। SQLite सानो local projects का लागि मात्र।
Step 1: Installation — Install गर्ने
# Official MySQL connector install गर्नुहोस् pip install mysql-connector-python # वा PyMySQL (Flask-SQLAlchemy सँग राम्रो) pip install PyMySQL # MySQL server install गर्नुहोस् (XAMPP वा standalone) # Windows: Download XAMPP → https://www.apachefriends.org # XAMPP मा MySQL र Apache start गर्नुहोस्
Step 2: MySQL Server मा Connect गर्ने
import mysql.connector # MySQL server मा connect गर्ने conn = mysql.connector.connect( host="localhost", # MySQL server address user="root", # MySQL username (XAMPP मा default: root) password="", # XAMPP मा default password blank हुन्छ database="school_db" # Database नाम ) if conn.is_connected(): print("✅ Connected to MySQL!") # Cursor बनाउने — SQL queries execute गर्न cursor = conn.cursor() conn.close() print("Connection closed.")
Step 3: Database र Table Create गर्ने
import mysql.connector # पहिले database name बिना connect गर्ने conn = mysql.connector.connect(host="localhost", user="root", password="") cursor = conn.cursor() # Database create गर्ने cursor.execute("CREATE DATABASE IF NOT EXISTS school_db") print("Database created!") # Database select गर्ने cursor.execute("USE school_db") # Table create गर्ने cursor.execute(""" CREATE TABLE IF NOT EXISTS students ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, age INT, grade VARCHAR(10), email VARCHAR(150), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) print("Table created!") conn.commit() cursor.close() conn.close()
Step 4: CRUD Operations — Create, Read, Update, Delete
➕ INSERT — Data थप्ने
import mysql.connector conn = mysql.connector.connect(host="localhost", user="root", password="", database="school_db") cursor = conn.cursor() # ✅ Parameterized query — SQL injection बाट बचाउँछ sql = "INSERT INTO students (name, age, grade, email) VALUES (%s, %s, %s, %s)" # Single row insert val = ("Santosh Bist", 20, "A+", "[email protected]") cursor.execute(sql, val) # Multiple rows insert एकैचोटि students_list = [ ("Sita Sharma", 19, "A", "[email protected]"), ("Ram Thapa", 21, "B+", "[email protected]"), ("Gita Poudel", 18, "A-", "[email protected]"), ] cursor.executemany(sql, students_list) conn.commit() print(f"{cursor.rowcount} rows inserted!") cursor.close() conn.close()
f"INSERT ... VALUES ('{name}')" — यो dangerous हो! हमेशा %s placeholders use गर्नुहोस्।📖 SELECT — Data पढ्ने
import mysql.connector conn = mysql.connector.connect(host="localhost", user="root", password="", database="school_db") cursor = conn.cursor(dictionary=True) # dictionary=True → dict format मा data आउँछ # सबै students select गर्ने cursor.execute("SELECT * FROM students") students = cursor.fetchall() # सबै rows एकैचोटि for student in students: print(f"ID: {student['id']} | Name: {student['name']} | Grade: {student['grade']}") # एउटा मात्र row fetch गर्ने cursor.execute("SELECT * FROM students WHERE id = %s", (1,)) one = cursor.fetchone() print(f"Found: {one['name']}") # WHERE + ORDER BY + LIMIT cursor.execute("SELECT * FROM students WHERE grade = %s ORDER BY name LIMIT %s", ("A+", 5)) top_students = cursor.fetchall() cursor.close() conn.close()
✏️ UPDATE — Data परिवर्तन गर्ने
cursor.execute("UPDATE students SET grade = %s, age = %s WHERE id = %s", ("A++", 21, 1)) conn.commit() print(f"{cursor.rowcount} record updated!")
🗑️ DELETE — Data मेटाउने
cursor.execute("DELETE FROM students WHERE id = %s", (3,)) conn.commit() print(f"{cursor.rowcount} record deleted!")
Reusable Database Connection Function
import mysql.connector from mysql.connector import Error DB_CONFIG = { "host": "localhost", "user": "root", "password": "", # Environment variable use गर्नुहोस् production मा! "database": "school_db", "charset": "utf8mb4" # Unicode (Nepali text) support } def get_connection(): """Return a MySQL connection""" try: conn = mysql.connector.connect(**DB_CONFIG) return conn except Error as e: print(f"Database Error: {e}") return None def execute_query(query, params=None, fetch=False): """Helper function to execute a query""" conn = get_connection() if not conn: return None try: cursor = conn.cursor(dictionary=True) cursor.execute(query, params or ()) if fetch: result = cursor.fetchall() return result conn.commit() return cursor.rowcount except Error as e: print(f"Query Error: {e}") finally: cursor.close() conn.close()
MySQL CRUD Practice
एउटा library_db database बनाउनुहोस् जसमा books table होस् — id, title, author, price, quantity। सबै CRUD operations implement गर्नुहोस्।
Project Setup
flask_mysql_app/ │ ├── app.py # Main Flask application ├── requirements.txt # flask, mysql-connector-python, python-dotenv ├── .env # DB credentials (NEVER share!) │ ├── templates/ │ ├── base.html │ ├── index.html # Student list │ ├── add.html # Add student form │ └── edit.html # Edit student form │ └── static/ └── css/ └── style.css
pip install flask mysql-connector-python python-dotenv
.env File — Database Credentials
DB_HOST=localhost DB_USER=root DB_PASSWORD= DB_NAME=school_db SECRET_KEY=your-secret-key-here-change-this!
echo ".env" >> .gitignoreapp.py — Complete Flask + MySQL Application
from flask import Flask, render_template, request, redirect, url_for, flash import mysql.connector from mysql.connector import Error import os from dotenv import load_dotenv load_dotenv() # .env file बाट environment variables load गर्ने app = Flask(__name__) app.secret_key = os.getenv("SECRET_KEY", "dev-secret") # ── Database Connection ────────────────────────────── def get_db(): """Return a MySQL database connection""" return mysql.connector.connect( host=os.getenv("DB_HOST", "localhost"), user=os.getenv("DB_USER", "root"), password=os.getenv("DB_PASSWORD", ""), database=os.getenv("DB_NAME", "school_db"), charset="utf8mb4" ) def init_db(): """Create database and table if not exists""" conn = mysql.connector.connect( host=os.getenv("DB_HOST", "localhost"), user=os.getenv("DB_USER", "root"), password=os.getenv("DB_PASSWORD", "") ) cursor = conn.cursor() cursor.execute(f"CREATE DATABASE IF NOT EXISTS {os.getenv('DB_NAME', 'school_db')}") cursor.execute(f"USE {os.getenv('DB_NAME', 'school_db')}") cursor.execute(""" CREATE TABLE IF NOT EXISTS students ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, age INT, grade VARCHAR(10), email VARCHAR(150), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) conn.commit() cursor.close() conn.close() # ── Routes ─────────────────────────────────────────── @app.route("/") def index(): """List all students""" conn = get_db() cursor = conn.cursor(dictionary=True) cursor.execute("SELECT * FROM students ORDER BY id DESC") students = cursor.fetchall() cursor.close() conn.close() return render_template("index.html", students=students) @app.route("/add", methods=["GET", "POST"]) def add_student(): """Add a new student""" if request.method == "POST": name = request.form["name"] age = request.form["age"] grade = request.form["grade"] email = request.form["email"] conn = get_db() cursor = conn.cursor() cursor.execute( "INSERT INTO students (name, age, grade, email) VALUES (%s, %s, %s, %s)", (name, age, grade, email) ) conn.commit() cursor.close() conn.close() flash("✅ Student successfully added!", "success") return redirect(url_for("index")) return render_template("add.html") @app.route("/edit/<int:id>", methods=["GET", "POST"]) def edit_student(id): """Edit student data""" conn = get_db() cursor = conn.cursor(dictionary=True) if request.method == "POST": cursor.execute( "UPDATE students SET name=%s, age=%s, grade=%s, email=%s WHERE id=%s", (request.form["name"], request.form["age"], request.form["grade"], request.form["email"], id) ) conn.commit() cursor.close() conn.close() flash("✅ Student updated!", "success") return redirect(url_for("index")) cursor.execute("SELECT * FROM students WHERE id = %s", (id,)) student = cursor.fetchone() cursor.close() conn.close() return render_template("edit.html", student=student) @app.route("/delete/<int:id>") def delete_student(id): """Delete a student""" conn = get_db() cursor = conn.cursor() cursor.execute("DELETE FROM students WHERE id = %s", (id,)) conn.commit() cursor.close() conn.close() flash("🗑️ Student deleted.", "danger") return redirect(url_for("index")) if __name__ == "__main__": init_db() app.run(debug=True)
templates/base.html — Base Template
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}Student DB{% endblock %}</title> </head> <body> <!-- Flash Messages --> {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} <div class="alert alert-{{ category }}">{{ message }}</div> {% endfor %} {% endif %} {% endwith %} {% block content %}{% endblock %} </body> </html>
templates/index.html — Student List
{% extends "base.html" %}
{% block title %}All Students{% endblock %}
{% block content %}
<h1>Students List</h1>
<a href="{{ url_for('add_student') }}">+ Add New Student</a>
<table>
<tr><th>ID</th><th>Name</th><th>Age</th><th>Grade</th><th>Actions</th></tr>
{% for s in students %}
<tr>
<td>{{ s.id }}</td>
<td>{{ s.name }}</td>
<td>{{ s.age }}</td>
<td>{{ s.grade }}</td>
<td>
<a href="{{ url_for('edit_student', id=s.id) }}">Edit</a>
<a href="{{ url_for('delete_student', id=s.id) }}"
onclick="return confirm('Delete?')">Delete</a>
</td>
</tr>
{% else %}
<tr><td colspan="5">No students yet. Add one!</td></tr>
{% endfor %}
</table>
{% endblock %}python app.py command run गर्नुहोस् र browser मा http://localhost:5000 खोल्नुहोस्। पहिलो पटक run गर्दा database र table automatically create हुन्छ!Flask + MySQL Library System
माथिको student system को आधारमा एउटा Library Management System बनाउनुहोस्। Books add, edit, delete गर्न सकिने। Search by title र author feature थप्नुहोस्।
MySQL Useful Queries — काम लाग्ने SQL
# Search / LIKE — नाम खोज्ने cursor.execute("SELECT * FROM students WHERE name LIKE %s", ("%Santosh%",)) # COUNT — कति students छन् cursor.execute("SELECT COUNT(*) as total FROM students") result = cursor.fetchone() print(f"Total: {result['total']}") # JOIN — दुई tables जोड्ने cursor.execute(""" SELECT s.name, c.course_name FROM students s JOIN enrollments e ON s.id = e.student_id JOIN courses c ON e.course_id = c.id """) # Pagination — page by page data देखाउने page = 1 per_page = 10 offset = (page - 1) * per_page cursor.execute("SELECT * FROM students LIMIT %s OFFSET %s", (per_page, offset)) # GROUP BY — grade अनुसार count cursor.execute("SELECT grade, COUNT(*) as count FROM students GROUP BY grade")
Flask-SQLAlchemy — ORM (सजिलो तरिका)
SQLAlchemy use गर्दा SQL लेख्नु पर्दैन — Python objects बाट database handle गर्न सकिन्छ।
pip install flask-sqlalchemy pymysql
from flask import Flask, render_template, request, redirect, url_for from flask_sqlalchemy import SQLAlchemy import os app = Flask(__name__) # MySQL connection string # Format: mysql+pymysql://user:password@host/database app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:@localhost/school_db" app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db = SQLAlchemy(app) # ── Model (Table Definition) ────────────────────────── class Student(db.Model): __tablename__ = "students" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False) age = db.Column(db.Integer) grade = db.Column(db.String(10)) email = db.Column(db.String(150)) def __repr__(self): return f"<Student {self.name}>" # ── Routes ─────────────────────────────────────────── @app.route("/") def index(): students = Student.query.order_by(Student.id.desc()).all() return render_template("index.html", students=students) @app.route("/add", methods=["GET", "POST"]) def add(): if request.method == "POST": s = Student( name=request.form["name"], age=request.form["age"], grade=request.form["grade"], email=request.form["email"] ) db.session.add(s) db.session.commit() return redirect(url_for("index")) return render_template("add.html") @app.route("/delete/<int:id>") def delete(id): s = Student.query.get_or_404(id) db.session.delete(s) db.session.commit() return redirect(url_for("index")) with app.app_context(): db.create_all() # Tables automatically create हुन्छ if __name__ == "__main__": app.run(debug=True)
Comparison: Raw MySQL vs SQLAlchemy
| Feature | mysql-connector (Raw) | Flask-SQLAlchemy (ORM) |
|---|---|---|
| SQL Knowledge | SQL जान्नुपर्छ | Python objects use |
| Speed | ⚡ Faster (direct) | Slightly slower |
| Code Amount | Verbose (धेरै code) | Clean र concise |
| Database Switch | SQL rewrite गर्नुपर्छ | Config change मात्र |
| Best For | Complex queries, performance | Rapid development |
| Learning Curve | SQL + Python | Python objects मात्र |
mysql-connector (raw SQL) सिक्नुहोस् ताकि SQL राम्ररी बुझिन्छ। त्यसपछि Flask-SQLAlchemy use गर्नुहोस् real projects मा। दुवैको ज्ञान हुनु professional को लागि जरुरी छ।Flask-Login + MySQL
User login/logout system बनाउन Flask-Login use गर्नुहोस्। Passwords bcrypt दिएर hash गर्नुहोस् — plain text मा कहिल्यै store नगर्नुहोस्!
Flask-Migrate
Database schema changes manage गर्न। flask db migrate र flask db upgrade commands use गर्ने।
Connection Pooling
Production मा हरेक request मा नयाँ connection नखोल्नुहोस्। SQLAlchemy को built-in connection pool use गर्नुहोस्।
Security Rules
Parameterized queries use गर्नुहोस्। DB credentials .env मा राख्नुहोस्। Production मा debug=False गर्नुहोस्।
बधाई छ! Course Complete!
तपाईंले Python को A to Z — Introduction देखि Flask + MySQL Web Development सम्म सबै complete गर्नुभयो! अब projects बनाउनुहोस् र practice जारी राख्नुहोस्।
🇳🇵 Mr. Santosh Bist — SBIST | www.sbist.com.np