🎯 What are Variables?
Variables are containers for storing data values. Python does not require explicit type declarations; the type is inferred from the assigned value. Variables are case-sensitive and must start with a letter or underscore. [web:23]
1. Local Variables
Local variables are defined inside a function and can only be accessed within that function.
def greet():
name = "Alice" # Local variable
print(f"Hello, {name}!")
greet()
def calculate_area(length, width):
area = length * width # Local variable
return area
result = calculate_area(5, 3)
print(result)
2. Global Variables
Global variables are defined outside all functions and are accessible everywhere in the file; use the global keyword to modify them inside a function. [web:23]
counter = 0 # Global variable
def increment():
global counter
counter += 1
print(f"Counter: {counter}")
increment()
increment()
PI = 3.14159 # Global constant
def circle_area(radius):
return PI * radius * radius
print(circle_area(5))
3. Instance Variables
Instance variables belong to a specific object and are usually defined in the __init__ constructor using self. [web:24]
class Student:
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age # Instance variable
student1 = Student("Bob", 20)
print(student1.name)
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
self.speed = 0
car = Car("Toyota", "Camry")
print(f"{car.brand} {car.model}")
4. Class Variables
Class variables are shared across all instances of a class and are defined directly inside the class body. [web:24]
class BankAccount:
interest_rate = 0.05 # Class variable
def __init__(self, balance):
self.balance = balance
acc1 = BankAccount(1000)
acc2 = BankAccount(2000)
print(BankAccount.interest_rate)
class Circle:
pi = 3.14159 # Class variable
def __init__(self, radius):
self.radius = radius
c1 = Circle(5)
c2 = Circle(10)
print(Circle.pi)
🎯 What is I/O?
print() displays output to the console, while input() reads a line of text from the user as a string. Use f-strings for clean, formatted output. [web:39]
1. Basic Output
Use print() to display values and expressions.
print("Hello, Python!")
x = 10
y = 20
print("Sum =", x + y)
2. Reading Input
input() always returns a string; convert it to int or float when needed. [web:23]
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello {name}, you are {age} years old!")
🎯 What are Operators?
Operators are symbols that perform operations on values and variables, such as arithmetic, comparison, logical, and assignment operations. [web:28]
1. Arithmetic Operators
Arithmetic operators include +, -, *, /, //, %, and ** for exponentiation. [web:36]
a = 7
b = 3
print(a + b) # 10
print(a - b) # 4
print(a * b) # 21
print(a / b) # 2.333...
print(a // b) # 2
print(a % b) # 1
print(a ** b) # 343
2. Comparison and Logical
Comparison operators like ==, !=, >, <, >=, <= return booleans and can be combined with logical operators and, or, not. [web:31]
x = 10
y = 5
print(x > y) # True
print(x == y) # False
print(x != y) # True
print(x > 0 and y > 0) # True
print(not (x < y)) # True
🎯 What are Data Types?
Data types describe what kind of values variables can hold, such as integers, floating-point numbers, strings, booleans, lists, tuples, sets, and dictionaries. [web:31]
1. Basic Built‑in Types
Common scalar types are int, float, str, and bool. [web:23]
age = 21 # int
pi = 3.14 # float
name = "Python" # str
is_fun = True # bool
print(type(age))
print(type(pi))
print(type(name))
print(type(is_fun))
2. Collection Types
Collections include list, tuple, set, and dict for grouping multiple values. [web:24]
nums = [1, 2, 3] # list
point = (10, 20) # tuple
unique = {1, 2, 2, 3} # set
student = {"name": "Alice", "age": 20} # dict
print(nums)
print(point)
print(unique)
print(student["name"])
🎯 What is Control Flow?
Control flow statements decide which blocks of code run, using conditionals like if and loops like for and while. [web:31]
1. If / Elif / Else
Use conditional statements to run code only when conditions are true.
score = 85
if score >= 90:
print("Grade A")
elif score >= 75:
print("Grade B")
else:
print("Grade C")
2. For and While Loops
for loops iterate over sequences, and while loops repeat while a condition remains true. [web:39]
# for loop
for i in range(1, 4):
print("For loop:", i)
# while loop
count = 3
while count > 0:
print("While loop:", count)
count -= 1
🎯 What are Functions?
Functions are reusable blocks of code defined with def that can take parameters and return values using return. [web:21]
1. Defining and Calling
A simple function takes arguments, performs work, and optionally returns a result.
def add(a, b):
result = a + b
return result
print(add(3, 4))
2. Default and Keyword Arguments
Parameters can have default values and can be passed by name using keyword arguments. [web:21]
def greet(name, language="Python"):
print(f"Hello {name}, welcome to {language}!")
greet("Alice")
greet(name="Bob", language="JavaScript")
🎯 What is Modularity?
Modularity means organizing code into separate files (modules) and packages so that code is easier to maintain and reuse. Python uses the import statement to load modules. [web:24]
1. Importing Modules
Use import or from ... import ... to reuse code defined in other modules. [web:24]
import math
print(math.sqrt(16))
print(math.pi)
from math import factorial
print(factorial(5))
2. Creating Your Own Module
Any .py file can act as a module and expose functions or variables to other files.
# In helpers.py
def square(x):
return x * x
# In another file:
# from helpers import square
# print(square(5))
🎯 What is OOP?
Object-Oriented Programming (OOP) organizes code into classes and objects, using concepts like attributes, methods, and inheritance. [web:24]
1. Classes and Objects
A class defines a blueprint, and objects are instances of that class.
class Person:
def __init__(self, name):
self.name = name
def say_hello(self):
print(f"Hello, I am {self.name}")
p = Person("Alice")
p.say_hello()
2. Inheritance
Inheritance lets a class reuse and extend behavior from another class. [web:24]
class Animal:
def speak(self):
print("Some sound")
class Dog(Animal):
def speak(self):
print("Woof!")
d = Dog()
d.speak()