MadiisAttendance
Python programming complete guide 14 min read 2,696 words 163 sentences uni

Python in 7 Days – Day 1: Core Internals, Metaclasses & Advanced Data Model

M Usman May 24, 2026
29 0 0 score
0%
Your Progress
0/76 sections
Reading Speed
0
words/min
Time Spent
00:00
Table of Contents
Lists H3
Tuples H3
Sets H3
Strings H3

Quick Stats
Words: 2,696
Est. time: 14 min
Readability: Advanced

Word Cloud
lussheburgh hexahedral schillerize kirk knute cuerda defiers routhie henbit dampen cushions WOMANLIKE SELF-EXISTENCE intangible nitranilic

COMPLETE PYTHON PROGRAMMING GUIDE

From Basics to Advanced Concepts with Explanations


Table of Contents

  1. Getting Started

  2. Conditions and Control Flow

  3. Variables and Data Types

  4. Operators

  5. Data Structures

  6. Loops

  7. Functions

  8. Advanced Python Features

  9. Modules and Libraries

  10. Error Handling

  11. Object-Oriented Programming

  12. File Handling

  13. Input/Output Operations


Chapter 1: Getting Started

Your First Python Program

python
print('hello world')

Explanation: The print() function outputs text to the console. This is the traditional first program when learning any programming language.

Output: hello world

Comments in Python

python
# This is a single line comment

Explanation: Comments are ignored by Python and used to explain code. Single-line comments start with #.

python
'''
This is a multi-line comment
that spans multiple lines
'''

Explanation: Triple quotes create multi-line strings that can be used as comments when not assigned to a variable.

python
"""
This is also a multi-line comment
that spans multiple lines
"""

Explanation: Double triple quotes work the same way for multi-line comments.


Chapter 2: Conditions and Control Flow

Basic If Statement

python
if 5 > 2:
    print('five is greater than two')

Explanation: The if statement checks a condition. If the condition is True, the indented code block executes. Indentation is crucial in Python.

Output: five is greater than two

If-Else Statement

python
if 5 > 2:
    print('five is greater than two')
else:
    print('five is less than two')

Explanation: else provides an alternative code block that executes when the if condition is False.

Output: five is greater than two

If-Elif-Else Statement

python
if 5 > 2:
    print('five is greater than two')
elif 5 == 2:
    print('five is equal to two')
else:
    print('five is less than two')

Explanation: elif (else-if) allows checking multiple conditions. The first true condition executes its block.

Output: five is greater than two

Nested If Statements

python
x = 10
if x > 5:
    print('x is greater than 5')
    if x < 10:
        print('x is less than 10')
    else:
        print('x is greater than 10')
else:
    print('x is less than 5')

Explanation: Nested conditions place one if statement inside another for more complex logical checks.

Output:

text
x is greater than 5
x is greater than 10

Logical Operators

python
a = 5
b = 10
c = 15

if a < b and b < c:
    print('a is less than b and b is less than c')

if a < b or b > c:
    print('a is less than b or b is greater than c')

if not a < b:
    print('a is not less than b')

Explanation:

  • and - Both conditions must be True

  • or - At least one condition must be True

  • not - Reverses the boolean value

Output:

text
a is less than b and b is less than c
a is less than b or b is greater than c

Chapter 3: Variables and Data Types

Basic Variables

python
x = 5
y = 'hello'
z = 3.14
print(x)
print(y)
print(z)

Explanation: Variables store data. Python is dynamically typed, so you don't need to declare variable types.

Output:

text
5
hello
3.14

Data Types

python
a = 5        # integer - whole numbers
b = 3.14     # float - decimal numbers
c = 'hello'  # string - text
d = True     # boolean - True/False
e = None     # NoneType - represents no value
print(a, b, c, d, e)

Explanation: Python has several built-in data types for different kinds of data.

Output: 5 3.14 hello True None

Multiple Assignment

python
x, y, z = 1, 2, 3
print(x, y, z)

Explanation: You can assign values to multiple variables in one line.

Output: 1 2 3

Global and Local Variables

python
def my_function():
    global x
    x = 5
    print(x)

my_function()
print(x)

Explanation: The global keyword allows a function to modify a variable defined outside its scope.

Output:

text
5
5

Type Casting

python
x = 5
y = float(x)   # integer to float
z = str(x)     # integer to string
print(x, y, z)

Explanation: Casting converts one data type to another using functions like int(), float(), str().

Output: 5 5.0 5

Type Checking

python
x = 5
print(type(x))
y = 'hello'
print(type(y))

Explanation: The type() function returns the data type of a variable.

Output:

text
<class 'int'>
<class 'str'>

Chapter 4: Operators

Arithmetic Operators

python
x = 5
y = 10
print(x + y)   # Addition
print(x - y)   # Subtraction
print(x * y)   # Multiplication
print(x / y)   # Division (returns float)
print(x % y)   # Modulus (remainder)
print(x ** 2)  # Exponentiation (power)
print(x // 2)  # Floor division (integer result)

Explanation: Arithmetic operators perform mathematical operations.

Output:

text
15
-5
50
0.5
5
25
2

Assignment Operators

python
x = 5
x += 3    # Same as: x = x + 3
print(x)
x -= 2    # Same as: x = x - 2
print(x)
x *= 2    # Same as: x = x * 2
print(x)
x /= 2    # Same as: x = x / 2
print(x)
x %= 3    # Same as: x = x % 3
print(x)
x **= 2   # Same as: x = x ** 2
print(x)
x //= 2   # Same as: x = x // 2
print(x)

Explanation: Assignment operators perform an operation and assign the result to the variable.

Output:

text
8
6
12
6.0
0.0
0.0
0.0

Comparison Operators

python
a = 5
b = 10
print(a == b)   # Equal to
print(a != b)   # Not equal to
print(a > b)    # Greater than
print(a < b)    # Less than
print(a >= b)   # Greater than or equal to
print(a <= b)   # Less than or equal to

Explanation: Comparison operators compare values and return boolean results.

Output:

text
False
True
False
True
False
True

Identity Operators

python
a = 5
b = 10
print(a is b)       # True if same object
print(a is not b)   # True if different objects

Explanation: Identity operators check if two variables refer to the same object in memory.

Output:

text
False
True

Membership Operators

python
x = 'hello world'
print('hello' in x)      # True if substring exists
print('world' in x)      # True if substring exists
print('python' in x)     # False if substring doesn't exist
print('hello' not in x)  # True if substring doesn't exist

Explanation: Membership operators check if a value exists in a sequence.

Output:

text
True
True
False
False

Bitwise Operators

python
a = 5   # Binary: 0101
b = 10  # Binary: 1010
print(a & b)   # AND - 0000 = 0
print(a | b)   # OR  - 1111 = 15
print(a ^ b)   # XOR - 1111 = 15
print(~a)      # NOT - inverts bits
print(a << 1)  # Left shift - 1010 = 10
print(a >> 1)  # Right shift - 0010 = 2

Explanation: Bitwise operators work on binary representations of numbers.

Output:

text
0
15
15
-6
10
2

Operator Precedence

python
x = 5 + 3 * 2      # Multiplication before addition
print(x)           # 5 + 6 = 11

y = (5 + 3) * 2    # Parentheses first
print(y)           # 8 * 2 = 16

Explanation: Operator precedence determines the order of operations. Parentheses have the highest precedence.

Output:

text
11
16

Chapter 5: Data Structures

Lists

python
my_list = [1, 2, 3, 4, 5]
print(my_list)

Explanation: Lists are ordered, changeable sequences that can contain duplicate values.

Output: [1, 2, 3, 4, 5]

Tuples

python
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)

Explanation: Tuples are ordered, unchangeable sequences that can contain duplicate values.

Output: (1, 2, 3, 4, 5)

Sets

python
my_set = {1, 2, 3, 4, 5}
print(my_set)

Explanation: Sets are unordered, unchangeable collections with no duplicate values.

Output: {1, 2, 3, 4, 5}

Dictionaries

python
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(my_dict)

Explanation: Dictionaries store key-value pairs. Keys must be unique and immutable.

Output: {'name': 'John', 'age': 30, 'city': 'New York'}

Strings

python
my_string = 'hello world'
print(my_string)

Explanation: Strings are sequences of characters enclosed in quotes.

Output: hello world

Numbers and Booleans

python
my_int = 5
my_float = 3.14
my_bool = True
my_none = None
print(my_int, my_float, my_bool, my_none)

Explanation: Python has integers, floats, booleans, and None as fundamental data types.

Output: 5 3.14 True None


Chapter 6: Loops

For Loop

python
for i in range(5):
    print(i)

Explanation: The for loop iterates over a sequence. range(5) generates numbers 0-4.

Output:

text
0
1
2
3
4

While Loop

python
i = 0
while i < 5:
    print(i)
    i += 1

Explanation: The while loop continues as long as the condition is true.

Output:

text
0
1
2
3
4

Range Function Variations

python
for i in range(5):           # 0 to 4
    print(i)

for i in range(1, 10, 2):    # Start, stop, step
    print(i)

Explanation: range() can take 1, 2, or 3 arguments for flexible iteration.

Output (first loop): 0 1 2 3 4
Output (second loop): 1 3 5 7 9

Break and Continue

python
# Break - exits the loop
for i in range(10):
    if i == 5:
        break
    print(i)

# Continue - skips to next iteration
for i in range(10):
    if i == 5:
        continue
    print(i)

Explanation: break stops the loop entirely. continue skips the rest of the current iteration.

Output (break): 0 1 2 3 4
Output (continue): 0 1 2 3 4 6 7 8 9


Chapter 7: Functions

Basic Functions

python
def my_function():
    print('hello world')

my_function()

Explanation: Functions are reusable code blocks defined with def. Call them by name with parentheses.

Output: hello world

Functions with Parameters

python
def my_function(name):
    print('hello ' + name)

my_function('john')

Explanation: Parameters allow functions to accept input values.

Output: hello john

Multiple Parameters

python
def my_function(name, age):
    print('hello ' + name + ', you are ' + str(age) + ' years old')

my_function('john', 30)

Explanation: Functions can accept multiple parameters separated by commas.

Output: hello john, you are 30 years old

Lambda Functions

python
my_lambda = lambda x: x * 2
print(my_lambda(5))

my_lambda = lambda x, y: x + y
print(my_lambda(5, 10))

my_lambda = lambda x, y, z: x * y * z
print(my_lambda(2, 3, 4))

Explanation: Lambda functions are small, anonymous functions defined in one line.

Output:

text
10
15
24

Map Function

python
my_list = [1, 2, 3, 4, 5]
my_map = map(lambda x: x * 2, my_list)
print(list(my_map))

Explanation: map() applies a function to every item in an iterable.

Output: [2, 4, 6, 8, 10]

Filter Function

python
my_list = [1, 2, 3, 4, 5]
my_filter = filter(lambda x: x % 2 == 0, my_list)
print(list(my_filter))

Explanation: filter() keeps only items that satisfy a condition.

Output: [2, 4]

Reduce Function

python
from functools import reduce

my_list = [1, 2, 3, 4, 5]
my_reduce = reduce(lambda x, y: x + y, my_list)
print(my_reduce)

Explanation: reduce() applies a function cumulatively to reduce a sequence to a single value.

Output: 15


Chapter 8: Advanced Python Features

List Comprehensions

python
my_list = [1, 2, 3, 4, 5]
my_list_comp = [x * 2 for x in my_list]
print(my_list_comp)

Explanation: List comprehensions provide a concise way to create lists.

Output: [2, 4, 6, 8, 10]

Dictionary Comprehensions

python
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict_comp = {k: v * 2 for k, v in my_dict.items()}
print(my_dict_comp)

Explanation: Dictionary comprehensions create dictionaries using a compact syntax.

Output: {'a': 2, 'b': 4, 'c': 6}

Set Comprehensions

python
my_set = {1, 2, 3, 4, 5}
my_set_comp = {x * 2 for x in my_set}
print(my_set_comp)

Explanation: Set comprehensions create sets using a similar compact syntax.

Output: {2, 4, 6, 8, 10}

Generator Expressions

python
my_list = [1, 2, 3, 4, 5]
my_gen_exp = (x * 2 for x in my_list)
print(list(my_gen_exp))

Explanation: Generator expressions create iterators that yield values one at a time.

Output: [2, 4, 6, 8, 10]

Iterators

python
my_list = [1, 2, 3, 4, 5]
my_iter = iter(my_list)
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))

Explanation: Iterators allow traversing through sequences. next() gets the next item.

Output:

text
1
2
3
4
5

Generators

python
def my_generator():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5

my_gen = my_generator()
print(next(my_gen))
print(next(my_gen))
print(next(my_gen))
print(next(my_gen))
print(next(my_gen))

Explanation: Generators use yield to produce values lazily, saving memory.

Output:

text
1
2
3
4
5

Chapter 9: Modules and Libraries

Math Module

python
import math

print(math.pi)          # Mathematical constant Ο€
print(math.e)           # Mathematical constant e
print(math.sqrt(16))    # Square root
print(math.pow(2, 3))   # Power (2^3)
print(math.floor(3.7))  # Round down
print(math.ceil(3.1))   # Round up
print(math.factorial(5)) # Factorial (5!)

Explanation: The math module provides mathematical functions and constants.

Output:

text
3.141592653589793
2.718281828459045
4.0
8.0
3
4
120

JSON Module

python
import json

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
my_json = json.dumps(my_dict)  # Convert dictionary to JSON string
print(my_json)

my_json_dict = json.loads(my_json)  # Convert JSON string back to dictionary
print(my_json_dict)
print(my_json_dict['name'])
print(my_json_dict['age'])
print(my_json_dict['city'])

Explanation: The json module handles JSON data format for data exchange.

Output:

text
{"name": "John", "age": 30, "city": "New York"}
{'name': 'John', 'age': 30, 'city': 'New York'}
John
30
New York

Datetime Module

python
import datetime

my_date = datetime.datetime.now()  # Current date and time
print(my_date)
print(my_date.year)
print(my_date.month)
print(my_date.day)
print(my_date.hour)
print(my_date.minute)
print(my_date.second)
print(my_date.microsecond)

Explanation: The datetime module provides date and time functionality.

Output (varies based on current time):

text
2024-01-15 14:30:45.123456
2024
1
15
14
30
45
123456

OS Module

python
import os

print(os.getcwd())  # Get current working directory
print(os.listdir())  # List files in current directory

Explanation: The os module provides operating system interface functions.

Output (varies by system):
/home/user/projects
['file1.py', 'file2.py', 'folder']

Regular Expressions

python
import re

my_string = 'hello world'
my_pattern = re.compile('hello')
my_match = my_pattern.search(my_string)
print(my_match)
print(my_match.group())

my_string = 'The rain in Spain stays mainly in the plain'
my_pattern = re.compile('ain')
my_matches = my_pattern.findall(my_string)
print(my_matches)

Explanation: The re module provides regular expression pattern matching.

Output:

text
<re.Match object; span=(0, 5), match='hello'>
hello
['ain', 'ain', 'ain']

Array Module

python
import array

my_array = array.array('i', [1, 2, 3, 4, 5])
print(my_array)

my_array.append(6)           # Add to end
print(my_array)

my_array.insert(0, 0)        # Insert at position
print(my_array)

my_array.pop()               # Remove last
print(my_array)

my_array.remove(3)           # Remove specific value
print(my_array)

my_array[0] = 10             # Modify element
print(my_array)

print(len(my_array))         # Get length
print(my_array.index(5))     # Find index of value
print(my_array.count(5))     # Count occurrences

my_array.reverse()           # Reverse order
print(my_array)

my_array.extend([7, 8, 9])   # Add multiple items
print(my_array)

Explanation: The array module provides efficient array storage for numeric types.

Output:

text
array('i', [1, 2, 3, 4, 5])
array('i', [1, 2, 3, 4, 5, 6])
array('i', [0, 1, 2, 3, 4, 5, 6])
array('i', [0, 1, 2, 3, 4, 5])
array('i', [0, 1, 2, 4, 5])
array('i', [10, 1, 2, 4, 5])
5
4
1
array('i', [5, 4, 2, 1, 10])
array('i', [5, 4, 2, 1, 10, 7, 8, 9])

Chapter 10: Error Handling

Try-Except Blocks

python
# Division by zero
try:
    x = 5 / 0
except ZeroDivisionError:
    print('You cannot divide by zero')

# Invalid type conversion
try:
    x = int('hello')
except ValueError:
    print('You cannot convert a string to an integer')

# Index out of range
try:
    x = my_list[10]
except IndexError:
    print('You cannot access an index that does not exist')

Explanation: try-except blocks catch and handle exceptions, preventing program crashes.

Output:

text
You cannot divide by zero
You cannot convert a string to an integer
You cannot access an index that does not exist

Assert Statement

python
x = 5
assert x == 5, 'x is not equal to 5'  # Assertion passes, no output
print('Assertion 1 passed')

x = 10
assert x == 5, 'x is not equal to 5'  # Assertion fails, raises exception

Explanation: assert checks a condition and raises an error if it's false.

Output:

text
Assertion 1 passed
AssertionError: x is not equal to 5

Pass Statement

python
def my_function():
    pass  # Placeholder for future code

class MyClass:
    pass  # Empty class definition

Explanation: pass is a null operation that does nothing. It's used as a placeholder.


Chapter 11: Object-Oriented Programming

Classes and Objects

python
class MyClass:
    def __init__(self, name, age):
        self.name = name  # Instance attribute
        self.age = age    # Instance attribute
    
    def my_method(self):
        print('Hello, my name is ' + self.name + ' and I am ' + str(self.age) + ' years old')

# Create an object (instance)
my_object = MyClass('John', 30)
my_object.my_method()

Explanation: Classes define blueprints for objects. __init__() is the constructor method.

Output: Hello, my name is John and I am 30 years old


Chapter 12: File Handling

Writing and Reading Files

python
# Write to a file
with open('my_file.txt', 'w') as f:
    f.write('Hello, world!')

# Read from a file
with open('my_file.txt', 'r') as f:
    content = f.read()
    print(content)

Explanation: The with statement ensures files are properly closed after operations.

Output: Hello, world!

Delete Statement

python
my_list = [1, 2, 3, 4, 5]
del my_list[0]  # Delete first element
print(my_list)

Explanation: del removes items from data structures or variables.

Output: [2, 3, 4, 5]


Chapter 13: Input/Output Operations

Input Function

python
name = input('What is your name? ')
print('Hello, ' + name + '!')

age = input('What is your age? ')
print('You are ' + age + ' years old.')

Explanation: input() reads user input from the keyboard as a string.

Output (with user input: John, 25):

text
What is your name? John
Hello, John!
What is your age? 25
You are 25 years old.

Print Function Variations

python
print('Hello, world!')
print('Hello, world!', end=' ')  # Change line ending to space
print('Hello, world!', end='\n') # New line (default)
print('Hello, world!', end='\t') # Tab character
print('Hello, world!', end='\r') # Carriage return
print('Hello, world!', end='\f') # Form feed
print('Hello, world!', end='\v') # Vertical tab

Explanation: The print() function can have custom endings and separators.


Appendix: Common Built-in Functions Quick Reference

FunctionPurposeExample
print()Display outputprint("Hello")
input()Get user inputname = input()
len()Get lengthlen([1,2,3]) β†’ 3
type()Get data typetype(5) β†’ <class 'int'>
int()Convert to integerint("5") β†’ 5
float()Convert to floatfloat("3.14") β†’ 3.14
str()Convert to stringstr(5) β†’ "5"
list()Convert to listlist((1,2,3)) β†’ [1,2,3]
dict()Create dictionarydict(name="John")
range()Generate numbersrange(5) β†’ 0,1,2,3,4
sum()Sum elementssum([1,2,3]) β†’ 6
max()Find maximummax([1,2,3]) β†’ 3
min()Find minimummin([1,2,3]) β†’ 1
sorted()Sort elementssorted([3,1,2]) β†’ [1,2,3]

How to Use This Document

  1. Copy the code blocks into a Python file (.py extension) or a Jupyter notebook

  2. Run the code to see the outputs

  3. Modify the examples to experiment with different values

  4. Reference the explanations to understand what each concept does

  5. Use the chapter organization to find specific topics quickly

To Save as a Word Document:

  1. Select all text in this document (Ctrl+A)

  2. Copy (Ctrl+C)

  3. Open Microsoft Word

  4. Paste (Ctrl+V)

  5. Save as (F12) β†’ Choose .docx or .doc format

Additional Learning Resources

  • Practice by modifying the examples

  • Combine different concepts in your own programs

  • Experiment with error handling to understand exceptions

  • Use Python's interactive mode (python in terminal) to test code snippets


End of Python Programming Guide

This document covers fundamental to intermediate Python concepts with practical examples and detailed explanations.

Discussion (10)
Login to comment
M Usman May 25, 2026

hi

M Usman May 25, 2026

bye

M Usman May 25, 2026

hi

M Usman May 25, 2026

hi

M Usman May 25, 2026

hi

M Usman May 25, 2026

hu

User May 25, 2026

Ghgjgj

M Usman May 25, 2026

gy

M Usman May 24, 2026

hey

M Usman May 24, 2026

Good usman this is very good

Dictionary

Add New Word

Dictionary Words
My Notes
Highlights
Select text and click highlight to save
My Vocabulary
Quick Quiz
Settings
Reading Analytics
Today's reading: 0 min
Total read time: 0 min
Words learned: 0
Streak: 0 days
AI Summary

Generating summary...