Complete Python Programming Notes
By: Backbencher Codes
Website: https://backbencher.codes
Online Compiler: https://www.backbencher.codes/compiler
Table of contents
- 1. Introduction to Python
- 2. Output and comments
- 3. Variables and data types
- 4. Input and type conversion
- 5. Operators
- 6. Conditional statements
- 7. Loops
- 8. Functions
- 9. Strings
- 10. Lists
- 11. Tuples
- 12. Sets
- 13. Dictionaries
- 14. Slicing and comprehensions
- 15. Object-oriented programming
- 16. Practice programs
- Further learning
These notes are a cleaned-up, readable version of the handwritten Python notes supplied as a PDF. Spelling, formatting, and code syntax have been corrected where needed so the examples are usable. Explanations are kept at beginner level.
1. Introduction to Python
Python is a high-level, general-purpose programming language. Its readable syntax makes it useful for scripting, web development, automation, data analysis, machine learning, and many other tasks.
Main features
- Readable syntax: Python code is designed to be easy to read.
- Interpreted execution: Python code is commonly run by the Python interpreter.
- Dynamic typing: A variable can refer to values of different types during execution.
- Automatic memory management: Python manages object memory automatically.
- Multiple programming styles: Python supports procedural, object-oriented, and functional programming.
- Cross-platform: Python is available on Windows, macOS, and Linux.
print("Hello, Python!")
Python uses indentation to define blocks of code. Use consistent indentation, conventionally four spaces per level.
2. Output and comments
print()
print() displays values. The sep argument controls the separator between values, and end controls what is printed at the end.
print("Hello")
print("Welcome", "to", "Backbencher Codes")
print("2026", "10", "28", sep="-")
print("Hello", end=" ")
print("again")
Output:
Hello
Welcome to Backbencher Codes
2026-10-28
Hello again
Comments and docstrings
# This is a single-line comment.
"""This string can be used as a module or function docstring."""
def greet():
"""Return a greeting message."""
return "Hello!"
Python does not have a special multi-line comment syntax. Several # comments can be used across multiple lines. Triple-quoted strings are strings, and are commonly used for docstrings.
3. Variables and data types
A variable is a name that refers to a value. Python does not require a type declaration when assigning a variable.
price = 100
tax = 18
total = price + tax print(total) # 118
### Common built-in types
| Type | Example | Description |
|---|---|---|
| `int` | `10` | Integer number |
| `float` | `10.5` | Decimal number |
| `complex` | `2 + 3j` | Complex number |
| `str` | `"Python"` | Text |
| `bool` | `True` | Boolean value |
| `list` | `[1, 2, 3]` | Ordered, mutable collection |
| `tuple` | `(1, 2, 3)` | Ordered, immutable collection |
| `set` | `{1, 2, 3}` | Collection of unique values |
| `dict` | `{"name": "Asha"}` | Key-value mapping |
| `NoneType` | `None` | Absence of a value |
Use `type()` to inspect a value's type:
```python
print(type(10)) # <class 'int'>
print(type(10.5)) # <class 'float'>
print(type("Python")) # <class 'str'>
print(type(None)) # <class 'NoneType'>
Python is dynamically typed, but it is also strongly typed: incompatible types are not automatically combined in every operation.
number = 10
number = "ten" # Allowed: the name now refers to a string.
4. Input and type conversion
input() reads a line from the user and returns it as a string.
name = input("Enter your name: ")
print("Welcome,", name)
Convert input when a numeric value is required:
first = int(input("Enter the first number: "))
second = int(input("Enter the second number: "))
print("Sum:", first + second)
For decimal values, use float().
Type conversion
text = "135"
number = int(text)
print(number + 5) # 140
value = 12
print(float(value)) # 12.0
print(str(value)) # "12"
Implicit conversion happens automatically in supported operations, such as 2 + 1.5, which produces 3.5. Explicit conversion is performed with functions such as int(), float(), and str(). Conversion can fail if the input is not valid for the target type.
5. Operators
Arithmetic operators
| Operator | Meaning | Example (a = 10, b = 3) |
|---|---|---|
+ |
Addition | a + b → 13 |
- |
Subtraction | a - b → 7 |
* |
Multiplication | a * b → 30 |
/ |
True division | a / b → 3.333... |
// |
Floor division | a // b → 3 |
% |
Remainder | a % b → 1 |
** |
Exponentiation | a ** b → 1000 |
a = 10
b = 3
print(a + b)
print(a // b)
print(a % b)
print(a ** b)
Comparison operators
==, !=, >, <, >=, and <= compare values and return a Boolean result.
age = 20
print(age >= 18) # True
print(age == 18) # False
Logical operators
and: true when both operands are truthy.or: true when at least one operand is truthy.not: reverses the truth value.
a = 10
b = 12
c = 0
print(a > 0 and b > 0) # True
print(a > 0 or c > 0) # True
print(not c) # True
Assignment operators
Examples include =, +=, -=, *=, /=, //=, and %=.
count = 5
count += 2
print(count) # 7
Membership operators
in and not in test membership in a sequence or collection.
languages = ["Python", "Java", "C++"]
print("Python" in languages) # True
print("Rust" not in languages) # True
Identity operators
is and is not test whether two references point to the same object. Use == to compare values in most cases.
first = [1, 2]
second = first
third = [1, 2]
print(first == third) # True: same contents
print(first is third) # False: different objects
print(first is second) # True: same object
Bitwise operators
Bitwise operators work on integer bits: & (AND), | (OR), ^ (XOR), ~ (invert), << (left shift), and >> (right shift).
a = 10 # binary 1010
b = 4 # binary 0100
print(a & b) # 0
print(a | b) # 14
print(a ^ b) # 14
print(a << 1) # 20
print(a >> 1) # 5
Operator overloading
Classes can define special methods to customize operators. For example, __add__() customizes the behavior of + for instances of a class. See the OOP section for a simple class example.
6. Conditional statements
Use if, elif, and else to choose which code block runs.
number = 10
if number > 5:
print("Greater than 5")
elif number == 5:
print("Equal to 5")
else:
print("Less than 5")
Conditions can be combined with and, or, and not.
age = 20
has_id = True
if age >= 18 and has_id:
print("Entry allowed")
else:
print("Entry not allowed")
Nested conditions
number = 10
if number > 0:
if number % 2 == 0:
print("Positive even number")
else:
print("Positive odd number")
else:
print("Zero or negative number")
7. Loops
while loop
A while loop repeats while its condition is true. Update the loop state to avoid an infinite loop when repetition should end.
count = 1
while count <= 3:
print(count)
count += 1
for loop
A for loop iterates over items in an iterable, such as a string, list, tuple, or range.
for language in ["Python", "Java", "C++"]:
print(language)
range()
range(stop) starts at 0 and stops before stop. range(start, stop, step) lets you set the start and step.
for number in range(5):
print(number, end=" ") # 0 1 2 3 4
print()
for number in range(2, 10, 2):
print(number, end=" ") # 2 4 6 8
break and continue
breakexits the nearest enclosing loop.continueskips the rest of the current iteration and moves to the next iteration.
for number in range(1, 6):
if number == 3:
continue
if number == 5:
break
print(number)
# Output: 1, 2, 4
Nested loops
A loop inside another loop is called a nested loop.
for row in range(1, 3):
for column in range(1, 4):
print(row, column)
8. Functions
A function is a reusable block of code defined with def. It can accept arguments and return a result.
def greet(name):
return f"Hello, {name}!"
print(greet("Asha"))
Parameters and arguments
- Parameter: A name in the function definition.
- Argument: A value supplied when calling the function.
def student(first_name, last_name):
print(first_name, last_name)
student("Asha", "Patil")
student(last_name="Patil", first_name="Asha")
Default arguments
def greet(name="there"):
print("Hello,", name)
greet()
greet("Sahil")
Variable-length arguments
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary.
def show_items(*args):
for item in args:
print(item)
show_items("Python", "Java", "C++")
def show_details(**kwargs):
for key, value in kwargs.items():
print(key, value)
show_details(name="Asha", course="BSc CS")
Return statement
return ends a function call and sends a value back to the caller. If a function has no return statement, it returns None.
def square(number):
return number * number
result = square(4)
print(result) # 16
Docstrings
A docstring describes a module, class, or function and appears as the first statement in its body.
def is_even(number):
"""Return True when number is even."""
return number % 2 == 0
Mutable objects and function calls
A function can modify a mutable object, such as a list, when it receives a reference to that object. Rebinding a local parameter does not rebind the caller's variable.
def add_item(items):
items.append("new")
values = ["old"]
add_item(values)
print(values) # ['old', 'new']
9. Strings
A string is an immutable sequence of Unicode characters. Strings can be written with single, double, or triple quotes.
single = 'Hello'
double = "Python"
multiline = """This is
multiple lines."""
Indexing and slicing
Indexing starts at 0; negative indexes count from the end. A slice uses string[start:stop:step], where stop is excluded.
word = "Python"
print(word[0]) # P
print(word[-1]) # n
print(word[1:4]) # yth
print(word[::-1]) # nohtyP
Common string operations and methods
text = " backbencher codes "
print(text.strip())
print(text.upper())
print(text.lower())
print("python programming".title())
print("banana".find("na"))
print("banana".count("a"))
print("a,b,c".split(","))
print("-".join(["2026", "10", "28"]))
print("Python".startswith("Py"))
print("Python".endswith("on"))
find() returns -1 if a substring is not found. index() raises ValueError if it is not found. Methods such as upper() return new strings; they do not modify the original string.
Escape sequences and concatenation
print("First line\nSecond line")
print("Column1\tColumn2")
first = "Backbencher"
second = "Codes"
print(first + " " + second)
10. Lists
A list is an ordered, mutable collection. It can contain values of different types and can grow or shrink.
languages = ["Python", "Java", "C++"]
print(languages[0])
print(languages[-1])
languages[1] = "JavaScript"
print(languages)
Common list methods
numbers = [3, 1, 2]
numbers.append(4) # Add one item at the end
numbers.extend([5, 6]) # Add multiple items
numbers.insert(0, 10) # Insert at an index
numbers.remove(10) # Remove first matching value
last = numbers.pop() # Remove and return last item
numbers.sort() # Sort in place
numbers.reverse() # Reverse in place
print(numbers)
Other useful operations include len(items), min(items), max(items), sum(items) for numeric values, items.count(value), and items.index(value).
del items[index]deletes an item by index.items.pop(index)removes and returns an item; the index is optional.items.remove(value)removes the first matching value.items.clear()removes all items.
Copying a list
Assignment creates another reference to the same list. Use copy() or slicing for a shallow copy.
original = [1, 2, 3]
reference = original
copied = original.copy()
reference.append(4)
print(original) # [1, 2, 3, 4]
print(copied) # [1, 2, 3]
11. Tuples
A tuple is an ordered, immutable collection.
point = (10, 20)
print(point[0])
print(point[-1])
single_item = (5,) # The comma makes this a tuple.
Tuple values cannot be reassigned through an index. Tuples support indexing, slicing, iteration, count(), and index().
12. Sets
A set is an unordered collection of unique hashable values. It does not support indexing. An empty set is created with set(), because {} creates an empty dictionary.
values = {1, 2, 2, 3}
print(values) # Contains 1, 2, and 3; order is not guaranteed.
empty_set = set()
values.add(4)
values.discard(2)
Set operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union: {1, 2, 3, 4, 5}
print(a & b) # Intersection: {3}
print(a - b) # Difference: {1, 2}
print(a ^ b) # Symmetric difference: {1, 2, 4, 5}
A frozenset is an immutable set.
13. Dictionaries
A dictionary stores key-value pairs. Keys must be hashable and unique; values can be of any type.
student = {
"name": "Asha",
"course": "BSc CS",
"year": 3,
}
print(student["name"])
print(student.get("city", "Not provided"))
Adding, updating, and deleting entries
student["city"] = "Kolhapur" # Add a key
student["year"] = 4 # Update a value
del student["course"] # Delete a key
Useful dictionary methods
person = {"name": "Asha", "age": 20}
print(person.keys())
print(person.values())
print(person.items())
print(person.get("name"))
person.update({"city": "Pune"})
person.pop("age")
To iterate over keys and values:
for key, value in person.items():
print(key, value)
14. Slicing and comprehensions
Slicing sequences
Slicing works with strings, lists, and tuples.
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[::2]) # [10, 30, 50]
print(numbers[::-1]) # Reversed copy
List comprehension
squares = [number * number for number in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
even_numbers = [number for number in range(10) if number % 2 == 0]
print(even_numbers)
Dictionary comprehension
squares = {number: number * number for number in range(1, 5)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16}
Comprehensions provide a compact way to build collections from iterables. Use a normal loop when it makes the logic easier to understand.
15. Object-oriented programming
Object-oriented programming (OOP) organizes code around objects that combine data and behavior. The notes cover classes, objects, self, constructors, encapsulation, inheritance, polymorphism, and data abstraction.
Classes and objects
A class defines a type of object. An object is an instance of a class. Attributes store data, and methods define behavior.
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says woof!"
pet = Dog("Buddy")
print(pet.name)
print(pet.speak())
__init__() initializes a newly created instance. self refers to the current instance and is written explicitly as the first parameter of an instance method; Python supplies it when the method is called on an object.
Instance attributes and class attributes
Instance attributes belong to an individual object. Class attributes are shared through the class unless an instance shadows them.
class Counter:
total_created = 0 # Class attribute
def __init__(self):
Counter.total_created += 1
self.value = 0 # Instance attribute
first = Counter()
second = Counter()
print(first.value) # 0
print(Counter.total_created) # 2
Encapsulation and attribute access
Encapsulation keeps related data and behavior together. In Python, a leading underscore (for example, _value) signals that an attribute is intended for internal use; it is a convention, not strict access control. A double leading underscore triggers name mangling in many class attributes.
class BankAccount:
def __init__(self, balance=0):
self._balance = balance
def deposit(self, amount):
if amount > 0:
self._balance += amount
def get_balance(self):
return self._balance
account = BankAccount(100)
account.deposit(50)
print(account.get_balance()) # 150
Inheritance
Inheritance lets a class reuse or extend another class.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some sound"
class Cat(Animal):
def speak(self):
return "Meow"
cat = Cat("Milo")
print(cat.name)
print(cat.speak())
Cat inherits from Animal and overrides the speak() method. super() can be used to call a method from the parent class.
Polymorphism
Polymorphism allows different object types to provide their own behavior through a common interface.
class Dog:
def speak(self):
return "Woof"
class Cat:
def speak(self):
return "Meow"
for animal in [Dog(), Cat()]:
print(animal.speak())
Data abstraction
Abstraction exposes the operations a user needs while hiding implementation details. Python supports abstract base classes through the abc module.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
print(Square(4).area()) # 16
Operator overloading
Special methods let custom objects respond to operators such as +.
class NumberPair:
def __init__(self, value):
self.value = value
def __add__(self, other):
if not isinstance(other, NumberPair):
return NotImplemented
return NumberPair(self.value + other.value)
first = NumberPair(10)
second = NumberPair(12)
print((first + second).value) # 22
16. Practice programs
Add two numbers
first = float(input("First number: "))
second = float(input("Second number: "))
print("Sum:", first + second)
Check even or odd
number = int(input("Enter an integer: "))
if number % 2 == 0:
print("Even")
else:
print("Odd")
Check whether a number is prime
number = int(input("Enter an integer: "))
if number < 2:
print("Not prime")
else:
is_prime = True
for divisor in range(2, int(number ** 0.5) + 1):
if number % divisor == 0:
is_prime = False
break
print("Prime" if is_prime else "Not prime")
Print a multiplication table
number = int(input("Enter a number: "))
for multiplier in range(1, 11):
print(f"{number} x {multiplier} = {number * multiplier}")
Find the largest number in a list
numbers = [12, 43, 7, 19, 25]
print("Largest:", max(numbers))