COMPLETE PYTHON PROGRAMMING GUIDE
From Basics to Advanced Concepts with Explanations
Table of Contents
Getting Started
Conditions and Control Flow
Variables and Data Types
Operators
Data Structures
Loops
Functions
Advanced Python Features
Modules and Libraries
Error Handling
Object-Oriented Programming
File Handling
Input/Output Operations
Chapter 1: Getting Started
Your First Python Program
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
# This is a single line commentExplanation: Comments are ignored by Python and used to explain code. Single-line comments start with #.
'''
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.
"""
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
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
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
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
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:
x is greater than 5 x is greater than 10
Logical Operators
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 Trueor- At least one condition must be Truenot- Reverses the boolean value
Output:
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
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:
5 hello 3.14
Data Types
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
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
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:
5 5
Type Casting
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
x = 5 print(type(x)) y = 'hello' print(type(y))
Explanation: The type() function returns the data type of a variable.
Output:
<class 'int'> <class 'str'>
Chapter 4: Operators
Arithmetic Operators
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:
15 -5 50 0.5 5 25 2
Assignment Operators
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:
8 6 12 6.0 0.0 0.0 0.0
Comparison Operators
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:
False True False True False True
Identity Operators
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:
False True
Membership Operators
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:
True True False False
Bitwise Operators
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:
0 15 15 -6 10 2
Operator Precedence
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:
11 16
Chapter 5: Data Structures
Lists
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
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
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
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
my_string = 'hello world' print(my_string)
Explanation: Strings are sequences of characters enclosed in quotes.
Output: hello world
Numbers and Booleans
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
for i in range(5): print(i)
Explanation: The for loop iterates over a sequence. range(5) generates numbers 0-4.
Output:
0 1 2 3 4
While Loop
i = 0 while i < 5: print(i) i += 1
Explanation: The while loop continues as long as the condition is true.
Output:
0 1 2 3 4
Range Function Variations
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
# 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
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
def my_function(name): print('hello ' + name) my_function('john')
Explanation: Parameters allow functions to accept input values.
Output: hello john
Multiple Parameters
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
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:
10 15 24
Map Function
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
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
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
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
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
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
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
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:
1 2 3 4 5
Generators
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:
1 2 3 4 5
Chapter 9: Modules and Libraries
Math Module
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:
3.141592653589793 2.718281828459045 4.0 8.0 3 4 120
JSON Module
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:
{"name": "John", "age": 30, "city": "New York"}
{'name': 'John', 'age': 30, 'city': 'New York'}
John
30
New YorkDatetime Module
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):
2024-01-15 14:30:45.123456 2024 1 15 14 30 45 123456
OS Module
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
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:
<re.Match object; span=(0, 5), match='hello'> hello ['ain', 'ain', 'ain']
Array Module
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:
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
# 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:
You cannot divide by zero You cannot convert a string to an integer You cannot access an index that does not exist
Assert Statement
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:
Assertion 1 passed AssertionError: x is not equal to 5
Pass Statement
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
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
# 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
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
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):
What is your name? John Hello, John! What is your age? 25 You are 25 years old.
Print Function Variations
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
| Function | Purpose | Example |
|---|---|---|
print() | Display output | print("Hello") |
input() | Get user input | name = input() |
len() | Get length | len([1,2,3]) β 3 |
type() | Get data type | type(5) β <class 'int'> |
int() | Convert to integer | int("5") β 5 |
float() | Convert to float | float("3.14") β 3.14 |
str() | Convert to string | str(5) β "5" |
list() | Convert to list | list((1,2,3)) β [1,2,3] |
dict() | Create dictionary | dict(name="John") |
range() | Generate numbers | range(5) β 0,1,2,3,4 |
sum() | Sum elements | sum([1,2,3]) β 6 |
max() | Find maximum | max([1,2,3]) β 3 |
min() | Find minimum | min([1,2,3]) β 1 |
sorted() | Sort elements | sorted([3,1,2]) β [1,2,3] |
How to Use This Document
Copy the code blocks into a Python file (
.pyextension) or a Jupyter notebookRun the code to see the outputs
Modify the examples to experiment with different values
Reference the explanations to understand what each concept does
Use the chapter organization to find specific topics quickly
To Save as a Word Document:
Select all text in this document (Ctrl+A)
Copy (Ctrl+C)
Open Microsoft Word
Paste (Ctrl+V)
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 (
pythonin terminal) to test code snippets
End of Python Programming Guide
This document covers fundamental to intermediate Python concepts with practical examples and detailed explanations.
hi
bye
hi
hi
hi
hu
Ghgjgj
gy
hey
Good usman this is very good