Why Python?
Python is the world's most popular programming language for a reason. It reads almost like English, runs on everything, and is used everywhere from web servers to AI research to microcontrollers.
#1
Most Popular Language 2024
AI/ML
Dominates Data Science
Web
Django, Flask, FastAPI
Hardware
MicroPython, Pico
YOUR FIRST PYTHON PROGRAM
# This is a comment - Python ignores it
print("Hello, World!")
print("Welcome to Aawiskar e-Siksha!")
# Python does math too
print(2 + 2) # Output: 4
print(10 ** 2) # Output: 100 (exponent)
print(f"2 to the power 10 = {2**10}") # f-strings!
š Running Python: Download Python from python.org. Then open a terminal and type python filename.py to run your file. Or use an online editor like replit.com for instant testing ā no installation!
Variables & Data Types
Variables are containers that store values. Python automatically figures out the type ā no need to declare it like in C or Java!
ALL DATA TYPES WITH EXAMPLES
# INTEGER ā whole numbers
age = 16
score = -42
big_num = 1_000_000 # underscores allowed for readability
# FLOAT ā decimal numbers
pi = 3.14159
temperature = -12.5
# STRING ā text (single or double quotes)
name = "Aawiskar"
city = 'Kathmandu'
multiline = """This is
a multiline
string."""
# BOOLEAN ā True or False (capital T/F!)
is_student = True
has_wifi = False
# Check type of any variable
print(type(age)) # <class 'int'>
print(type(pi)) # <class 'float'>
print(type(name)) # <class 'str'>
# Type conversion
x = int("42") # string ā int
y = str(3.14) # float ā string
z = float("9.81") # string ā float
# String methods
greeting = "hello world"
print(greeting.upper()) # HELLO WORLD
print(greeting.title()) # Hello World
print(greeting.replace("world", "Nepal")) # hello Nepal
print(len(greeting)) # 11
Control Flow
Control flow decides WHICH code runs based on conditions. Python uses indentation (spaces) instead of curly braces ā this is mandatory, not optional!
# IF / ELIF / ELSE
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Grade: A+ ā Outstanding!")
elif marks >= 75:
print("Grade: A ā Excellent!")
elif marks >= 60:
print("Grade: B ā Good")
elif marks >= 40:
print("Grade: C ā Pass")
else:
print("Grade: F ā Fail. Study harder!")
# Multiple conditions
age = 18
has_id = True
if age >= 18 and has_id:
print("Access granted")
elif age >= 18 or has_id:
print("Partial access")
else:
print("Access denied")
# Ternary operator (one-liner)
status = "Adult" if age >= 18 else "Minor"
Loops & Iteration
Loops let you repeat code without rewriting it. Python has for loops (iterate over sequences) and while loops (repeat while a condition is true).
# FOR loop ā iterating ranges and lists
for i in range(5): # 0,1,2,3,4
print(f"Step {i}")
for i in range(1, 11, 2): # 1,3,5,7,9 (start,stop,step)
print(i)
# Looping over strings
for letter in "Python":
print(letter)
# WHILE loop ā runs as long as condition is True
count = 0
while count < 5:
print(f"Count: {count}")
count += 1
# break and continue
for i in range(10):
if i == 3:
continue # skip 3
if i == 7:
break # stop at 7
print(i) # prints 0,1,2,4,5,6
# Nested loops ā multiplication table
for i in range(1, 6):
for j in range(1, 6):
print(f"{i*j:4}", end="")
print()
Functions & Modules
Functions are reusable blocks of code. Instead of writing the same logic multiple times, define it once and call it whenever needed.
# Basic function
def greet(name):
return f"Namaste, {name}! Welcome to Aawiskar."
print(greet("Raju"))
# Default parameters
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25 (uses default exponent=2)
print(power(2, 10)) # 1024
# Multiple return values
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 9, 5, 2])
print(f"Min: {low}, Max: {high}") # Min: 1, Max: 9
# Lambda ā anonymous one-line function
square = lambda x: x ** 2
print(square(7)) # 49
# *args and **kwargs
def total(*numbers): # accepts any number of args
return sum(numbers)
print(total(1, 2, 3, 4, 5)) # 15
Lists, Tuples, Dicts & Sets
Python's built-in data structures are incredibly powerful. Master these four and you can represent almost any real-world data.
# LIST ā ordered, mutable, allows duplicates
fruits = ["mango", "apple", "banana", "mango"]
fruits.append("cherry")
fruits.remove("apple")
print(fruits[0]) # mango (indexing)
print(fruits[-1]) # cherry (last item)
print(fruits[1:3]) # slicing
# List comprehension ā Python's superpower!
squares = [x**2 for x in range(1, 11)]
evens = [x for x in range(20) if x % 2 == 0]
# DICTIONARY ā key:value pairs, unordered
student = {
"name": "Sita",
"age": 17,
"grades": [85, 92, 78],
"enrolled": True
}
print(student["name"]) # Sita
student["age"] = 18 # update value
student["school"] = "Aawiskar" # add new key
# Looping a dict
for key, value in student.items():
print(f"{key}: {value}")
# SET ā unique values, no duplicates
nums = {1, 2, 3, 2, 1}
print(nums) # {1, 2, 3}
Object-Oriented Programming
OOP organizes code around "objects" ā bundles of data (attributes) and behavior (methods). Everything in Python is already an object!
class Robot:
# Class variable (shared by all instances)
species = "Mechanical"
# Constructor ā called when object is created
def __init__(self, name, battery=100):
self.name = name # instance variable
self.battery = battery
self.is_on = False
def power_on(self):
self.is_on = True
print(f"{self.name} is now ON. Battery: {self.battery}%")
def move(self, direction):
if not self.is_on:
print("Robot is off!")
return
self.battery -= 5
print(f"{self.name} moved {direction}. Battery: {self.battery}%")
# String representation
def __str__(self):
return f"Robot({self.name}, battery={self.battery}%)"
# Create instances
r1 = Robot("Robo-1")
r2 = Robot("Robo-2", battery=80)
r1.power_on()
r1.move("forward")
r1.move("left")
print(r1) # Robot(Robo-1, battery=90%)
# INHERITANCE
class FlyingRobot(Robot): # inherits from Robot
def __init__(self, name):
super().__init__(name) # call parent constructor
self.altitude = 0
def fly(self, height):
self.altitude = height
self.battery -= 15
print(f"{self.name} flying at {height}m!")
File Handling & Exceptions
Read, write, and process files. And handle errors gracefully with try/except so your program doesn't crash on unexpected input.
# Writing to a file
with open("data.txt", "w") as f:
f.write("Aawiskar e-Siksha\n")
f.write("Line 2\nLine 3\n")
# Reading from a file
with open("data.txt", "r") as f:
content = f.read()
print(content)
# Read line by line
with open("data.txt") as f:
for line in f:
print(line.strip())
# TRY / EXCEPT ā handle errors gracefully
try:
num = int(input("Enter a number: "))
result = 100 / num
print(f"100 / {num} = {result}")
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Can't divide by zero!")
finally:
print("Program finished.") # always runs
# JSON ā common file format for APIs
import json
data = {"name": "Sita", "score": 95}
with open("student.json", "w") as f:
json.dump(data, f)
Project: Calculator App
Build a fully functional calculator in Python with a menu-driven interface. Combines everything: functions, loops, conditionals, and error handling.
def add(a, b): return a + b
def subtract(a, b): return a - b
def multiply(a, b): return a * b
def divide(a, b):
if b == 0: raise ValueError("Cannot divide by zero!")
return a / b
operations = {'+': add, '-': subtract, '*': multiply, '/': divide}
print("=== Aawiskar Calculator ===")
while True:
try:
a = float(input("\nEnter first number: "))
op = input("Operator (+, -, *, /): ")
b = float(input("Enter second number: "))
if op not in operations:
print("Invalid operator!")
continue
result = operations[op](a, b)
print(f"Result: {a} {op} {b} = {result}")
again = input("Calculate again? (y/n): ")
if again.lower() != 'y': break
except (ValueError, ZeroDivisionError) as e:
print(f"Error: {e}")
print("Thanks for using Aawiskar Calculator!")
Project: Quiz Game
Build an interactive quiz with score tracking, random question order, and timing ā all in under 50 lines of Python!
import random, time
questions = [
{"q": "What does CPU stand for?",
"options": ["A) Central Processing Unit", "B) Computer Power Unit", "C) Core Processing Universe"],
"answer": "A"},
{"q": "What voltage does Arduino Uno use?",
"options": ["A) 3.3V", "B) 5V", "C) 12V"],
"answer": "B"},
{"q": "Which language does Arduino use?",
"options": ["A) Python", "B) Java", "C) C++"],
"answer": "C"},
]
random.shuffle(questions)
score = 0
start = time.time()
for i, q in enumerate(questions, 1):
print(f"\nQ{i}: {q['q']}")
for opt in q["options"]: print(opt)
answer = input("Your answer (A/B/C): ").upper()
if answer == q["answer"]:
print("ā Correct!"); score += 1
else:
print(f"ā Wrong! Answer: {q['answer']}")
elapsed = round(time.time() - start, 1)
print(f"\n=== Score: {score}/{len(questions)} in {elapsed}s ===")
Project: Weather API
Fetch real weather data from the internet using Python's requests library. Calls the OpenWeatherMap API and displays current weather beautifully.
# pip install requests
import requests
API_KEY = "your_api_key_from_openweathermap.org"
def get_weather(city):
url = f"https://api.openweathermap.org/data/2.5/weather"
params = {"q": city, "appid": API_KEY, "units": "metric"}
try:
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
print(f"\nš¤ļø Weather in {data['name']}, {data['sys']['country']}")
print(f"Temperature: {data['main']['temp']}°C")
print(f"Feels like: {data['main']['feels_like']}°C")
print(f"Humidity: {data['main']['humidity']}%")
print(f"Condition: {data['weather'][0]['description'].title()}")
print(f"Wind Speed: {data['wind']['speed']} m/s")
except requests.exceptions.HTTPError:
print(f"City '{city}' not found!")
except requests.exceptions.ConnectionError:
print("No internet connection!")
city = input("Enter city name: ")
get_weather(city)
# Try: Kathmandu, London, Tokyo, New York
š Getting an API Key: Sign up free at openweathermap.org, go to API Keys section, and copy your key. Free tier allows 1000 calls/day ā more than enough for learning!