Python Programming Guide Professional Reference | 2024 Edition
PYTHON
PROGRAMMING GUIDE
With Console Outputs & Practical Examples
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
A Comprehensive Reference for Python Fundamentals
Variables • Data Types • Strings • Control Flow • Loops • Lists • Functions • OOP
Professional Python Notes with Terminal-Style Outputs
2024 Edition
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
Introduction
This document provides a comprehensive reference to Python programming concepts — from
fundamental variable declarations to advanced Object-Oriented Programming patterns. Each section
includes clear definitions, syntax templates, multiple worked examples, and realistic terminal-style
output displays.
Python is a high-level, interpreted programming language celebrated for its readability, simplicity, and
versatile ecosystem. Whether you're building web applications, performing data analysis, automating
system tasks, or exploring machine learning, Python offers the tools and libraries to support your goals.
Feature Description
Easy to Read Python uses indentation instead of braces, making code visually clean and
easy to follow.
Interpreted Code is executed line by line — no separate compilation step required.
Dynamically Typed Variable types are determined at runtime; no need to declare types
explicitly.
Cross-Platform Python runs on Windows, macOS, Linux, and many embedded systems.
Large Standard Hundreds of built-in modules for file I/O, networking, math, and more.
Library
Huge Ecosystem Libraries like NumPy, Pandas, TensorFlow, Flask, and Django extend
Python enormously.
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
1. Variables
1.1 Variable Declaration
Definition: Variables are named containers that store data values in memory. In Python, variables
are created the moment you assign a value to them — no explicit declaration keyword is needed.
Syntax: variable_name = value
Example 1:
Assigning string and integer values to variables
name = "Rajesh"
age = 25
print(name)
print(age)
Rajesh
OUTPUT
25
Example 2:
Performing arithmetic with numeric variables
x = 10
y = 20
result = x + y
print(result)
OUTPUT 30
Example 3:
Multiple variable assignment using tuple unpacking
# Multiple assignment in one line
a, b, c = 1, 2, 3
print(a, b, c)
OUTPUT 1 2 3
Example 4:
Swapping values of two variables in a single line
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
# Swapping two variables
x = 5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)
x = 10
OUTPUT
y = 5
Example 5:
Using uppercase naming convention for constants
# Constants (by convention uppercase)
PI = 3.14159
MAX_SPEED = 120
print(PI)
print(MAX_SPEED)
3.14159
OUTPUT
120
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
2. Data Types
2.1 Numeric Data Types
Definition: Python supports three numeric data types: int (whole numbers), float (decimal numbers),
and complex (numbers with a real and imaginary part).
Syntax: variable = value # Python infers the type automatically
Example 1:
Checking the type of numeric variables
x = 10
y = 10.5
print(type(x))
print(type(y))
<class 'int'>
OUTPUT
<class 'float'>
Example 2:
Integer arithmetic operations
a = 100
b = 3
print(a // b) # Integer (floor) division
print(a % b) # Modulus (remainder)
print(a ** 2) # Exponentiation
33
OUTPUT 1
10000
Example 3:
Float arithmetic — computing area of a circle
pi = 3.14159
radius = 5.0
area = pi * radius ** 2
print(round(area, 2))
OUTPUT 78.54
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
Example 4:
Working with complex numbers
z = 3 + 4j
print(z)
print([Link])
print([Link])
(3+4j)
OUTPUT 3.0
4.0
2.2 Boolean Data Type
Definition: Boolean values represent truth values: True or False. Booleans are often the result of
comparisons or logical expressions.
Syntax: variable = True # or False
Example 1:
Declaring a boolean variable
is_valid = True
print(is_valid)
print(type(is_valid))
True
OUTPUT
<class 'bool'>
Example 2:
Boolean results from comparison operators
a = 10
b = 20
print(a > b)
print(a < b)
print(a == b)
False
OUTPUT True
False
Example 3:
Using logical operators with booleans
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
print(True and False)
print(True or False)
print(not True)
False
OUTPUT True
False
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
3. Strings
3.1 String Operations
Definition: Strings are sequences of characters enclosed in single or double quotes. Python provides
rich built-in methods for string manipulation.
Syntax: string1 + string2 # Concatenation "text" * n #
Repetition
Example 1:
String concatenation using the + operator
first = "Hello"
second = "World"
print(first + " " + second)
OUTPUT Hello World
Example 2:
String repetition using the * operator
print("Python " * 3)
OUTPUT Python Python Python
Example 3:
Changing string case with built-in methods
text = "Python Programming"
print([Link]())
print([Link]())
print([Link]())
PYTHON PROGRAMMING
OUTPUT python programming
Python Programming
Example 4:
Using f-strings for string interpolation
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
name = "Rajesh"
city = "Hyderabad"
msg = f"My name is {name} and I live in {city}."
print(msg)
OUTPUT My name is Rajesh and I live in Hyderabad.
Example 5:
Using strip(), replace(), and len() on strings
text = " Hello, Python! "
print([Link]())
print([Link]("Python", "World"))
print(len(text))
Hello, Python!
OUTPUT Hello, World!
20
Example 6:
Splitting a string into a list
sentence = "apple,banana,cherry"
fruits = [Link](",")
print(fruits)
print(fruits[1])
['apple', 'banana', 'cherry']
OUTPUT
banana
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
4. Conditional Logic
4.1 if, elif, else
Definition: Conditional statements allow your program to make decisions. Python uses if, elif (else-
if), and else blocks to branch execution based on conditions.
Syntax: if condition: # block elif another_condition: # block
else: # block
Example 1:
Simple if statement checking a single condition
age = 20
if age >= 18:
print("Adult")
OUTPUT Adult
Example 2:
Using elif for grade classification
marks = 80
if marks >= 90:
print("A")
elif marks >= 75:
print("B")
else:
print("C")
OUTPUT B
Example 3:
Nested if statements for multiple conditions
# Nested if
salary = 55000
experience = 3
if salary > 50000:
if experience >= 2:
print("Eligible for bonus")
else:
print("Need more experience")
else:
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
print("Not eligible")
OUTPUT Eligible for bonus
Example 4:
Using the ternary operator for concise conditions
# Ternary (one-line) if
num = 7
result = "Even" if num % 2 == 0 else "Odd"
print(result)
OUTPUT Odd
Example 5:
Using "in" and "not in" operators in conditions
# Using "in" and "not in" in conditions
fruits = ["apple", "banana", "mango"]
if "banana" in fruits:
print("Banana is available")
if "grape" not in fruits:
print("Grape is not in the list")
Banana is available
OUTPUT
Grape is not in the list
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
5. Loops
5.1 for Loop
Definition: The for loop is used to iterate over a sequence (list, tuple, string, range, etc.) and execute
a block of code for each element.
Syntax: for variable in sequence: # body
Example 1:
Iterating over a range of numbers
for i in range(3):
print(i)
0
OUTPUT 1
2
Example 2:
Iterating over a list of strings
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple
OUTPUT banana
cherry
Example 3:
Using enumerate() to get index alongside value
# Enumerate — get index and value
names = ["Alice", "Bob", "Carol"]
for index, name in enumerate(names):
print(f"{index}: {name}")
0: Alice
OUTPUT 1: Bob
2: Carol
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
Example 4:
Nested for loops for a multiplication table
# Nested for loop — multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
2 x 1 = 2
OUTPUT 2 x 2 = 4
2 x 3 = 6
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
5.2 while Loop
Definition: The while loop repeats a block of code as long as a given condition evaluates to True. It
is used when the number of iterations is not known in advance.
Syntax: while condition: # body # update condition
Example 1:
Simple while loop that counts from 1 to 3
count = 1
while count <= 3:
print(count)
count += 1
1
OUTPUT 2
3
Example 2:
Accumulating a sum with a while loop
# Sum of numbers until 0 is entered
total = 0
num = 5
while num != 0:
total += num
num -= 1
print("Sum:", total)
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
OUTPUT Sum: 15
Example 3:
Using break and continue to control loop flow
# break and continue
i = 0
while i < 6:
i += 1
if i == 3:
continue # skip 3
if i == 5:
break # stop at 5
print(i)
1
OUTPUT 2
4
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
6. Lists
6.1 List Methods
Definition: Lists are ordered, mutable collections that can hold items of any data type. Python
provides many built-in methods to add, remove, sort, and search list elements.
Syntax: my_list = [item1, item2, ...] # Declaration my_list.method()
# Calling a method
Example 1:
Appending an element to the end of a list
nums = [1, 2]
[Link](3)
print(nums)
OUTPUT [1, 2, 3]
Example 2:
Sorting a list in ascending order
nums = [3, 1, 2]
[Link]()
print(nums)
OUTPUT [1, 2, 3]
Example 3:
Inserting and removing elements from a list
colors = ["red", "green", "blue"]
[Link](1, "yellow")
print(colors)
[Link]("green")
print(colors)
['red', 'yellow', 'green', 'blue']
OUTPUT
['red', 'yellow', 'blue']
Example 4:
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
Accessing list elements and slicing
nums = [10, 20, 30, 40, 50]
print(nums[0]) # First element
print(nums[-1]) # Last element
print(nums[1:4]) # Slicing
10
OUTPUT 50
[20, 30, 40]
Example 5:
Using list comprehension to generate a list of squares
# List comprehension
squares = [x**2 for x in range(1, 6)]
print(squares)
OUTPUT [1, 4, 9, 16, 25]
Example 6:
Using count(), index(), and reverse() methods
items = ["a", "b", "c", "b", "a"]
print([Link]("b")) # Count occurrences
print([Link]("c")) # First index of "c"
[Link]()
print(items)
2
OUTPUT 2
['a', 'b', 'c', 'b', 'a']
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
7. Functions
7.1 Function Definition & Usage
Definition: Functions are named, reusable blocks of code that perform a specific task. They accept
inputs (parameters), execute logic, and optionally return a result. Functions promote code reuse,
readability, and maintainability.
Syntax: def function_name(parameters): # body return value #
optional
Example 1:
Defining and calling a simple function with no parameters
def greet():
print("Hello World")
greet()
OUTPUT Hello World
Example 2:
Function with parameters and a return value
def add(a, b):
return a + b
result = add(10, 20)
print(result)
OUTPUT 30
Example 3:
Using default parameter values
def power(base, exp=2):
return base ** exp
print(power(3)) # uses default exp=2
print(power(2, 10)) # custom exponent
OUTPUT 9
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
1024
Example 4:
Using **kwargs to accept keyword arguments
def describe(**info):
for key, value in [Link]():
print(f"{key}: {value}")
describe(name="Rajesh", city="Hyderabad", age=25)
name: Rajesh
OUTPUT city: Hyderabad
age: 25
Example 5:
Recursive function to calculate factorial
# Recursive function
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))
OUTPUT 120
Example 6:
Using lambda (anonymous) functions
# Lambda function
square = lambda x: x * x
print(square(6))
nums = [3, 1, 4, 1, 5]
[Link](key=lambda x: -x)
print(nums)
36
OUTPUT
[5, 4, 3, 1, 1]
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
8. Object-Oriented Programming (OOP)
8.1 Classes and Objects
Definition: A class is a blueprint that defines the structure and behavior (attributes and methods) of
objects. An object is a specific instance of a class — it holds its own data and can call the class
methods.
Syntax: class ClassName: # class body (attributes, methods)
Example 1:
Defining a minimal empty class and creating an instance
class Student:
pass
s1 = Student()
print(type(s1))
OUTPUT <class '__main__.Student'>
Example 2:
Class with class-level attributes shared by all instances
class Car:
brand = "Toyota"
color = "Red"
c1 = Car()
print([Link])
print([Link])
Toyota
OUTPUT
Red
8.2 Constructor (__init__)
Definition: The __init__ method is a special constructor that Python calls automatically when a new
object is created. It initializes instance attributes unique to each object.
Syntax: def __init__(self, parameters): [Link] = value
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
Example 1:
Using __init__ to set instance attributes at creation
class Student:
def __init__(self, name):
[Link] = name
s1 = Student("Raj")
print([Link])
OUTPUT Raj
Example 2:
Class with multiple attributes and an instance method
class Employee:
def __init__(self, name, dept, salary):
[Link] = name
[Link] = dept
[Link] = salary
def display(self):
print(f"{[Link]} | {[Link]} | Rs.{[Link]}")
e1 = Employee("Priya", "IT", 75000)
[Link]()
OUTPUT Priya | IT | Rs.75000
Example 3:
Inheritance — Dog overrides Animal's speak() method
# Inheritance
class Animal:
def speak(self):
print("Some sound")
class Dog(Animal):
def speak(self):
print("Woof!")
d = Dog()
[Link]()
OUTPUT Woof!
Example 4:
Encapsulation using private attributes and public methods
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
# Encapsulation with private attributes
class BankAccount:
def __init__(self, owner, balance):
[Link] = owner
self.__balance = balance # private
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
acc = BankAccount("Rajesh", 5000)
[Link](2000)
print(acc.get_balance())
OUTPUT 7000
Example 5:
Implementing __str__ to control object print output
# __str__ method for string representation
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
p = Point(3, 7)
print(p)
OUTPUT Point(3, 7)
Python Fundamentals & OOP Reference Page
Python Programming Guide Professional Reference | 2024 Edition
Conclusion
This guide has covered the essential building blocks of Python programming, from basic variable
declarations all the way to Object-Oriented Programming principles. Each concept has been
demonstrated with multiple, progressively complex examples backed by terminal-style output displays
for realistic reference.
Topic Key Concepts Practical Use
Variables Assignment, naming, constants Storing user input, configuration
Data Types int, float, bool, complex Calculations, flags, scientific
computing
Strings Concatenation, f-strings, methods User messages, text processing
Conditionals if / elif / else, ternary Decision making, form validation
Loops for, while, break, continue Data iteration, automation tasks
Lists CRUD methods, slicing, Collections, sorting, filtering
comprehension
Functions def, return, default args, lambda Code reuse, API design
OOP Classes, __init__, inheritance Modelling real-world entities
With these fundamentals mastered, you are well-prepared to explore advanced Python topics —
including decorators, generators, context managers, asynchronous programming, and the rich
ecosystem of third-party libraries.
Python Fundamentals & OOP Reference Page