PYTHON SHORT NOTES
Definitions • Practical Examples • Outputs
1. Data Types & Collections 2. Operators & Conditions
3. Loops & Programming Tips 4. Exceptions
5. Modules 6. Functions
7. OOP Concepts 8. GUI with Tkinter
9. Data Science 10. MySQL
Prepared for Exam Success
Rahmatullah Jalalzai
Python Short Notes | Definitions + Examples + Output Page 1
1. Python Data Types & Objects
What is a Data Type?
A data type tells Python what kind of value a variable holds and what operations are allowed on it.
1.1 Numbers (int, float, complex)
• int: whole numbers • float: decimal numbers • complex: numbers with real + imaginary part
a = 10 # int
b = 3.14 # float
c = 2 + 3j # complex
print(type(a), type(b), type(c))
print(a + b)
print([Link], [Link])
Output:
<class 'int'> <class 'float'> <class 'complex'>
13.14
2.0 3.0
1.2 Strings
A string is an immutable sequence of characters. Created with single or double quotes.
s = "Python"
print(s[0]) # first char
print(s[-1]) # last char
print(s[1:4]) # slice
print([Link]())
print(len(s))
print("Py" in s)
Output:
P
n
yth
PYTHON
6
True
1.3 Lists (mutable, ordered, allows duplicates)
A list is a collection that is ordered and changeable. Written with square brackets [].
lst = [10, 20, 30, "hi"]
[Link](40)
[Link](1, 15)
print(lst)
print(lst[2])
[Link]("hi")
print(lst)
print(len(lst))
Output:
[10, 15, 20, 30, 'hi', 40]
20
[10, 15, 20, 30, 40]
5
1.4 Tuples (immutable, ordered)
A tuple is like a list but cannot be changed after creation. Written with parentheses ().
t = (1, 2, 3, "ok")
print(t[0])
print(t[-1])
a, b, c, d = t # unpacking
print(a, d)
print(len(t))
Output:
1
ok
1 ok
4
1.5 Dictionaries (mutable, key-value pairs)
Python Short Notes | Definitions + Examples + Output Page 2
A dictionary stores data as key:value pairs. Keys must be unique and immutable.
d = {"name": "Ali", "age": 21, "city": "Kabul"}
print(d["name"])
print([Link]("age"))
d["age"] = 22
d["country"] = "AFG"
print(d)
print(list([Link]()))
print(list([Link]()))
Output:
Ali
21
{'name': 'Ali', 'age': 22, 'city': 'Kabul', 'country': 'AFG'}
['name', 'age', 'city', 'country']
['Ali', 22, 'Kabul', 'AFG']
1.6 Sets (mutable, unordered, unique items)
A set is a collection of unique elements. Written with curly braces {}. No duplicates allowed.
s1 = {1, 2, 3, 3, 2}
s2 = {3, 4, 5}
print(s1) # duplicates removed
print(s1 | s2) # union
print(s1 & s2) # intersection
[Link](10)
print(s1)
Output:
{1, 2, 3}
{1, 2, 3, 4, 5}
{3}
{1, 2, 3, 10}
1.7 Input / Output (I/O)
input() reads text from user (always returns str). print() displays output.
name = "Rahmat" # simulating input
age = 20
print("Hello", name)
print(f"Age next year: {age + 1}")
print("A", "B", "C", sep="-")
Output:
Hello Rahmat
Age next year: 21
A-B-C
→ File I/O: use open() with 'r' (read), 'w' (write), 'a' (append). Prefer 'with' statement.
Python Short Notes | Definitions + Examples + Output Page 3
2. Comparison Operators & Conditional Statements
2.1 Comparison & Logical Operators
Used to compare values and combine conditions. Result is always True or False (boolean).
x, y = 10, 20
print(x == y) # equal?
print(x != y) # not equal?
print(x < y) # less than?
print(x >= 10)
print(x > 5 and y < 30)
print(x > 15 or y > 15)
print(not (x == 10))
print(5 in [1, 5, 9])
Output:
False
True
True
True
True
True
False
True
2.2 if / elif / else Statement
Controls program flow: run different code based on conditions. Indentation defines the block.
marks = 78
if marks >= 90:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 50:
grade = "C"
else:
grade = "F"
print("Grade:", grade)
Output:
Grade: B
→ Python uses indentation (usually 4 spaces) instead of curly braces {}.
3. Loops in Python
3.1 for Loop
Repeats a block of code for each item in a sequence (list, string, range, etc.).
for i in range(1, 5):
print(i, end=" ")
print()
fruits = ["apple", "banana", "mango"]
for f in fruits:
print([Link]())
Output:
1 2 3 4
APPLE
BANANA
MANGO
3.2 while Loop
Repeats as long as a condition remains True. Useful when the number of iterations is unknown.
Python Short Notes | Definitions + Examples + Output Page 4
n = 1
while n <= 4:
print("Count:", n)
n += 1
print("Done")
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Done
3.3 break & continue
for i in range(1, 8):
if i == 3:
continue # skip 3
if i == 6:
break # stop at 6
print(i, end=" ")
Output:
1 2 4 5
3.4 General Programming Practice
• Use meaningful variable names (student_name not sn)
• Keep functions short and focused on one task
• Comment complex logic • Avoid deep nesting • Test with different inputs
• Follow PEP 8 style guide (spaces around operators, 4-space indent)
Python Short Notes | Definitions + Examples + Output Page 5
4. Exceptions in Python
What is an Exception?
An exception is an error that occurs during program execution and disrupts the normal flow.
4.1 Exception vs Syntax Error
• Syntax Error: detected before running (e.g. missing colon). Code cannot start.
• Exception: occurs while the program is running (e.g. dividing by zero).
# Syntax Error example (will not run):
# if True print("hi") <-- missing colon
# Exception example:
print(10 / 0)
Output:
ZeroDivisionError: division by zero
4.2 Handling Exceptions (try / except)
Use try-except to catch errors and prevent the program from crashing.
try:
num = int("abc")
print(10 / num)
except ValueError:
print("Invalid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
Output:
Invalid number!
4.3 finally Block
The finally block always runs — whether an exception occurred or not. Used for cleanup.
try:
f = open("[Link]", "r")
print([Link]())
except FileNotFoundError:
print("File not found")
finally:
print("Cleanup done")
Output:
File not found
Cleanup done
4.4 Raising Exceptions
You can manually raise an exception with the raise keyword.
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
Output:
ValueError: Age cannot be negative
5. Modules
A module is a file containing Python code (functions, classes, variables) that you can reuse in other programs.
Python Short Notes | Definitions + Examples + Output Page 6
import math
print([Link](16))
print([Link])
from random import randint
print(randint(1, 6)) # dice
import datetime
print([Link]())
Output:
4.0
3.141592653589793
4
2026-08-01
→ Create your own: save code in [Link] then use import mymodule
Python Short Notes | Definitions + Examples + Output Page 7
6. Functions
What is a Function?
A function is a reusable block of code that performs a specific task. Defined with the def keyword.
6.1 Defining & Calling + Return Value
def add(a, b):
return a + b
result = add(5, 3)
print(result)
print(add(10, 20))
Output:
8
30
6.2 Function Arguments
• Positional • Keyword • Default • *args (variable positional) • **kwargs (variable keyword)
def greet(name, msg="Hello"):
print(f"{msg}, {name}!")
greet("Ali")
greet("Sara", msg="Hi")
def total(*nums):
return sum(nums)
print(total(1, 2, 3, 4))
Output:
Hello, Ali!
Hi, Sara!
10
6.3 Function Scope
• Local scope: variables inside a function • Global scope: variables outside functions
x = 100 # global
def demo():
x = 50 # local
print("Inside:", x)
demo()
print("Outside:", x)
Output:
Inside: 50
Outside: 100
7. Object-Oriented Programming (OOP)
OOP Concepts briefly
OOP organizes code using objects. Main ideas: Class, Object, Encapsulation, Inheritance, Polymorphism.
7.1 Classes, Instances & Methods + __init__
A class is a blueprint. An instance (object) is created from the class. __init__ is the constructor.
class Student:
def __init__(self, name, marks):
[Link] = name
[Link] = marks
def result(self):
status = "Pass" if [Link] >= 50 else "Fail"
return f"{[Link]}: {status}"
s1 = Student("Rahmat", 78)
s2 = Student("Ahmad", 42)
print([Link]())
print([Link]())
Output:
Rahmat: Pass
Ahmad: Fail
Python Short Notes | Definitions + Examples + Output Page 8
7.2 Inheritance
A child class inherits attributes and methods from a parent class.
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Woof!"
d = Dog()
print([Link]())
Output:
Woof!
7.3 Polymorphism
Same method name behaves differently depending on the object (overriding).
class Cat(Animal):
def speak(self):
return "Meow!"
animals = [Dog(), Cat(), Animal()]
for a in animals:
print([Link]())
Output:
Woof!
Meow!
Some sound
Python Short Notes | Definitions + Examples + Output Page 9
8. GUI Programming with Tkinter
What is Tkinter?
Tkinter is Python's standard library for creating Graphical User Interfaces (windows, buttons, labels...).
8.1 Create Window, Label, Button, Message Box & Actions
from tkinter import *
from tkinter import messagebox
root = Tk()
[Link]("My First App")
[Link]("300x180")
Label(root, text="Welcome!", font=("Arial", 14)).pack(pady=10)
def on_click():
[Link]("Info", "Button was clicked!")
Button(root, text="Click Me", command=on_click,
bg="blue", fg="white").pack(pady=10)
[Link]()
Output:
(A window opens with title "My First App")
(Clicking the button shows a message box:
"Button was clicked!")
• root = Tk() creates the main window
• Label() shows text • Button() creates clickable button
• command= links a function to the button
• [Link] / showerror / askyesno for dialogs
• .pack() / .grid() / .place() position the widgets
• [Link]() starts the event loop (keeps window open)
GUI Output (what the window looks like):
Message Box that appears after clicking the button:
9. What is Data Science?
Data Science is the field that extracts knowledge and insights from data using statistics, programming and domain expertise.
• Steps: Collect → Clean → Explore → Model → Visualize → Communicate
• Main Python libraries:
– NumPy (arrays & math) – Pandas (tables/dataframes)
Python Short Notes | Definitions + Examples + Output Page 10
– Matplotlib / Seaborn (charts) – Scikit-learn (machine learning)
import numpy as np
arr = [Link]([10, 20, 30, 40])
print([Link]())
print(arr * 2)
# Pandas example (conceptual)
# import pandas as pd
# df = pd.read_csv("[Link]")
# print([Link]())
Output:
25.0
[20 40 60 80]
10. MySQL with Python
MySQL is a popular open-source Relational Database Management System. Python connects to it using libraries like mysql-connector-python.
import [Link]
conn = [Link](
host="localhost",
user="root",
password="mypass",
database="school"
)
cursor = [Link]()
# Create table (run once)
[Link]("""
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
marks INT
)
""")
# Insert
[Link]("INSERT INTO students (name, marks) VALUES (%s, %s)",
("Rahmat", 85))
[Link]()
# Select
[Link]("SELECT * FROM students")
for row in [Link]():
print(row)
[Link]()
Output:
(1, 'Rahmat', 85)
→ Always use parameterized queries (%s) to prevent SQL injection.
→ Common SQL: SELECT, INSERT, UPDATE, DELETE, WHERE, JOIN, ORDER BY
★ Best of luck on your exam! Practice every example above.
Prepared by: Rahmatullah Jalalzai
Python Short Notes — Definitions + Practical Examples + Outputs
Python Short Notes | Definitions + Examples + Output Page 11