Complete Guide to Python Programming Language
From Basics to Advanced Concepts
Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum and first released in 1991. It emphasizes code readability with its notable use of significant whitespace and simple syntax that allows programmers to express concepts in fewer lines of code than would be possible in languages such as C++ or Java.
Python follows a set of guiding principles that emphasize:
Python has evolved through several major versions:
Note: Python 2 reached end-of-life in 2020. All new development should use Python 3.
This example demonstrates the fundamental concepts of Python programming, including comments, the print function, variables, and string formatting.
# This is your first Python program
print("Hello, World!")
# Variables and basic operations
name = "Python Learner"
age = 25
print(f"My name is {name} and I am {age} years old")
Hello, World!
My name is Python Learner and I am 25 years old
Python uses indentation to define code blocks, making it unique among programming languages. This enforced indentation makes Python code more readable and forces programmers to write clean, well-structured code.
In Python, indentation is not just for readability—it's part of the syntax. Code blocks are defined by their indentation level:
variable and Variable are different names.if, else, for, while, def, class.This example covers essential Python syntax elements including comments, variables, data types, and the print function.
# Comments start with #
# Multi-line comments use triple quotes
"""This is a multi-line comment
that can span multiple lines
and is often used for documentation"""
# Variables don't need type declaration
x = 10
y = "Hello"
z = True
# Multiple assignment
a, b, c = 1, 2, 3
# Print function
print("Hello World")
print(x, y, z) # Multiple values
Hello World
10 Hello True
Python has several built-in data types that are used to define the operations possible on them and the storage method for each of them. Python's data types are classes, and variables are instances (objects) of these classes.
Data types in Python are fundamental concepts that determine how data is stored, processed, and manipulated. Every value in Python has a data type, and understanding these types is crucial for effective programming.
type() function or isinstance() function.int(), float(), str()).Python automatically manages memory for all data types. When you create a variable, Python allocates memory for it. When the variable goes out of scope or is reassigned, Python's garbage collector frees the memory.
This example demonstrates Python's three numeric data types: integers, floating-point numbers, and complex numbers.
# Integer (int)
age = 25
year = 2024
# Float (floating point)
height = 5.9
pi = 3.14159
# Complex numbers
complex_num = 3 + 4j
# Type checking
print(type(age)) # <class 'int'>
print(type(height)) # <class 'float'>
print(type(complex_num)) # <class 'complex'>
<class 'int'>
<class 'float'>
<class 'complex'>
This example demonstrates string creation, manipulation, and various formatting methods in Python.
# String creation
name = "John Doe"
message = 'Hello World'
multi_line = """This is a
multi-line string"""
# String operations
print(name.upper()) # JOHN DOE
print(name.lower()) # john doe
print(name.split()) # ['John', 'Doe']
print(len(name)) # 8
# String formatting
age = 25
print(f"I am {age} years old") # f-string (Python 3.6+)
print("I am {} years old".format(age)) # .format()
print("I am %d years old" % age) # % formatting
JOHN DOE
john doe
['John', 'Doe']
8
I am 25 years old
I am 25 years old
I am 25 years old
This example demonstrates boolean values, logical operations, and truthy/falsy values in Python.
# Boolean values
is_student = True
is_working = False
# Boolean operations
print(True and False) # False
print(True or False) # True
print(not True) # False
# Truthy and Falsy values
print(bool(0)) # False
print(bool("")) # False
print(bool([])) # False
print(bool(1)) # True
print(bool("hello")) # True
False
True
False
False
False
False
True
True
Control flow statements determine the order in which program statements are executed. Python provides several control flow statements including conditional statements (if, elif, else), loops (for, while), and control statements (break, continue, pass).
Control flow is the order in which individual statements, instructions, or function calls are executed or evaluated in a program. It determines how your program responds to different conditions and how it repeats operations.
This example demonstrates how to use conditional statements to make decisions in your code based on different conditions.
# Basic if statement
age = 18
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
# if-elif-else chain
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Your grade is {grade}")
You are an adult
Your grade is B
This example demonstrates different ways to use for loops for iterating over sequences like ranges, lists, and dictionaries.
# Iterating over a range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterating with enumerate
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Iterating over a dictionary
person = {"name": "John", "age": 30, "city": "New York"}
for key in person:
print(f"{key}: {person[key]}")
for key, value in person.items():
print(f"{key}: {value}")
0
1
2
3
4
apple
banana
cherry
0: apple
1: banana
2: cherry
name: John
age: 30
city: New York
name: John
age: 30
city: New York
This example demonstrates while loops and control statements like break and continue for controlling loop execution.
# Basic while loop
count = 0
while count < 5:
print(count)
count += 1
# While loop with break
number = 0
while True:
if number == 5:
break
print(number)
number += 1
# While loop with continue
i = 0
while i < 10:
i += 1
if i % 2 == 0:
continue # Skip even numbers
print(i) # Print only odd numbers
0
1
2
3
4
0
1
2
3
4
1
3
5
7
9
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. Python has many built-in functions, but you can also create your own functions.
Functions are fundamental building blocks in Python programming. They allow you to encapsulate code into reusable units, making your programs more organized, maintainable, and efficient.
def keyword followed by the function name and parameters.print(), len(), type()).lambda keyword.This example demonstrates how to define and use functions with different types of parameters and return values.
# Simple function
def greet():
print("Hello, World!")
# Function call
greet()
# Function with parameters
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Alice")
# Function with multiple parameters
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result) # 8
# Function with default parameters
def greet_with_title(name, title="Mr."):
return f"Hello, {title} {name}!"
print(greet_with_title("Smith")) # Hello, Mr. Smith!
print(greet_with_title("Johnson", "Dr.")) # Hello, Dr. Johnson!
Hello, World!
Hello, Alice!
8
Hello, Mr. Smith!
Hello, Dr. Johnson!
This example demonstrates lambda functions, which are small anonymous functions that can be defined in a single line.
# Lambda function syntax: lambda arguments: expression
square = lambda x: x ** 2
print(square(5)) # 25
# Lambda with multiple arguments
add = lambda x, y: x + y
print(add(3, 4)) # 7
# Lambda in built-in functions
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# Lambda with filter
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4]
25
7
[1, 4, 9, 16, 25]
[2, 4]
Data structures are fundamental concepts in programming that help organize and store data efficiently. Python provides several built-in data structures including lists, tuples, dictionaries, and sets, each with their own characteristics and use cases.
Data structures are specialized formats for organizing, processing, retrieving, and storing data. They provide a way to manage large amounts of data efficiently for uses such as large databases and internet indexing services.
Different operations on different data structures have varying time complexities:
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
# Accessing elements
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last element)
# Slicing
print(numbers[1:4]) # [2, 3, 4]
print(numbers[:3]) # [1, 2, 3]
print(numbers[2:]) # [3, 4, 5]
# List methods
fruits.append("orange") # Add to end
fruits.insert(1, "grape") # Insert at index
fruits.remove("banana") # Remove by value
popped = fruits.pop() # Remove and return last element
fruits.sort() # Sort in place
fruits.reverse() # Reverse in place
# List comprehension
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
# Creating dictionaries
person = {
"name": "John Doe",
"age": 30,
"city": "New York",
"skills": ["Python", "JavaScript", "SQL"]
}
# Accessing values
print(person["name"]) # John Doe
print(person.get("age")) # 30
print(person.get("email", "Not found")) # Not found
# Adding/updating items
person["email"] = "john@example.com"
person.update({"phone": "123-456-7890"})
# Dictionary methods
print(person.keys()) # dict_keys(['name', 'age', 'city', 'skills', 'email', 'phone'])
print(person.values()) # dict_values(['John Doe', 30, 'New York', ...])
print(person.items()) # dict_items([('name', 'John Doe'), ('age', 30), ...])
# Dictionary comprehension
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Object-Oriented Programming (OOP) is a programming paradigm that uses objects to design applications and computer programs. It provides a clear modular structure for programs which makes it good for defining abstract data types, implementing code reusability, and protecting information through encapsulation.
OOP is a programming paradigm based on the concept of "objects," which can contain data and code. Data in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods).
__init__, __str__) provide powerful customization.This example demonstrates the fundamental concepts of Object-Oriented Programming in Python, including class definition, object creation, and method usage.
# Defining a class
class Person:
# Constructor method
def __init__(self, name, age):
self.name = name
self.age = age
# Instance method
def introduce(self):
return f"Hi, I'm {self.name} and I'm {self.age} years old"
# Method to update age
def have_birthday(self):
self.age += 1
return f"Happy birthday! I'm now {self.age} years old"
# Creating objects (instances)
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
# Accessing attributes and methods
print(person1.name) # Alice
print(person1.introduce()) # Hi, I'm Alice and I'm 25 years old
print(person2.have_birthday()) # Happy birthday! I'm now 31 years old
Alice
Hi, I'm Alice and I'm 25 years old
Happy birthday! I'm now 31 years old
This example demonstrates inheritance in Python, showing how a child class can inherit properties and methods from a parent class while adding its own unique features.
# Base class (parent class)
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self):
return "Some animal sound"
def get_info(self):
return f"{self.name} is a {self.species}"
# Derived class (child class)
class Dog(Animal):
def __init__(self, name, breed):
# Call parent constructor
super().__init__(name, "Dog")
self.breed = breed
def make_sound(self):
return "Woof! Woof!"
def fetch(self):
return f"{self.name} is fetching the ball"
# Creating instances
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.get_info()) # Buddy is a Dog
print(my_dog.make_sound()) # Woof! Woof!
print(my_dog.fetch()) # Buddy is fetching the ball
Buddy is a Dog
Woof! Woof!
Buddy is fetching the ball
This example demonstrates encapsulation, one of the fundamental principles of Object-Oriented Programming, showing how to control access to object attributes and methods.
# Encapsulation example
class BankAccount:
def __init__(self, account_holder, initial_balance):
self.account_holder = account_holder
self._balance = initial_balance # Protected attribute
self.__account_number = "ACC" + str(hash(account_holder)) # Private attribute
def get_balance(self):
return self._balance
def deposit(self, amount):
if amount > 0:
self._balance += amount
return f"Deposited ${amount}. New balance: ${self._balance}"
else:
return "Invalid amount"
def withdraw(self, amount):
if 0 < amount <= self._balance:
self._balance -= amount
return f"Withdrew ${amount}. New balance: ${self._balance}"
else:
return "Insufficient funds or invalid amount"
# Using the class
account = BankAccount("John Doe", 1000)
print(account.deposit(500)) # Deposited $500. New balance: $1500
print(account.withdraw(200)) # Withdrew $200. New balance: $1300
print(account.get_balance()) # 1300
Deposited $500. New balance: $1500
Withdrew $200. New balance: $1300
1300
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Modules can be imported and used in other Python files, allowing for code organization and reusability.
Modules are a way to organize Python code into logical units. They help break down large programs into smaller, manageable pieces and promote code reuse across different projects.
math, os, sys).datetime, json, re).numpy, pandas, requests).import module_name - imports the entire module.from module_name import item - imports specific items from a module.import module_name as alias - imports with an alias name.from module_name import * - imports all public items (not recommended).Python searches for modules in the following order:
__init__.py file.This example demonstrates how to create custom modules and import them in Python, showing different import methods and module organization.
# math_operations.py (module file)
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
raise ValueError("Cannot divide by zero")
# main.py (using the module)
import math_operations
print(math_operations.add(5, 3)) # 8
print(math_operations.multiply(4, 6)) # 24
# Import specific functions
from math_operations import add, subtract
print(add(10, 5)) # 15
print(subtract(10, 5)) # 5
# Import with alias
import math_operations as math_ops
print(math_ops.divide(15, 3)) # 5.0
8
24
15
5
5.0
This example demonstrates how to use Python's built-in modules for mathematical operations, random number generation, and date/time manipulation.
# Math module
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.ceil(3.7)) # 4
print(math.floor(3.7)) # 3
# Random module
import random
print(random.randint(1, 10)) # Random integer between 1 and 10
print(random.choice(["apple", "banana", "cherry"])) # Random choice
random.shuffle([1, 2, 3, 4, 5]) # Shuffle list
# Datetime module
from datetime import datetime, timedelta
now = datetime.now()
print(now) # Current date and time
print(now.strftime("%Y-%m-%d %H:%M:%S")) # Formatted date
tomorrow = now + timedelta(days=1)
print(tomorrow) # Tomorrow's date
3.141592653589793
4.0
4
3
7
banana
2024-01-15 14:30:25.123456
2024-01-15 14:30:25
2024-01-16 14:30:25.123456
Python provides built-in functions and methods to handle files. File handling is an important part of any web application. Python has several functions for creating, reading, updating, and deleting files.
File handling is the process of working with files stored on a computer's file system. Python provides a simple and efficient way to read from and write to files, making it easy to persist data and work with external files.
open() function to create a file object.with statements to ensure proper file closure.This example demonstrates different methods for reading files in Python, including reading entire content, line-by-line processing, and handling different encodings.
# Reading a file
with open("sample.txt", "r") as file:
content = file.read()
print(content)
# Reading line by line
with open("sample.txt", "r") as file:
for line in file:
print(line.strip())
# Reading all lines into a list
with open("sample.txt", "r") as file:
lines = file.readlines()
print(lines)
# Reading with encoding
with open("sample.txt", "r", encoding="utf-8") as file:
content = file.read()
Hello
World
Python
Hello
World
Python
['Hello\n', 'World\n', 'Python\n']
This example demonstrates different methods for writing to files in Python, including writing, appending, and error handling for file operations.
# Writing to a file (overwrites existing content)
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a new line.\n")
# Appending to a file
with open("output.txt", "a") as file:
file.write("This line is appended.\n")
# Writing multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as file:
file.writelines(lines)
# Writing with context manager
try:
with open("data.txt", "w") as file:
file.write("Some data")
except IOError as e:
print(f"Error writing file: {e}")
# After first write operation:
Hello, World!
This is a new line.
# After append operation:
Hello, World!
This is a new line.
This line is appended.
# After writelines operation:
Line 1
Line 2
Line 3
Exceptions are events that occur during the execution of a program that disrupt the normal flow of the program's instructions. Python provides a way to handle these exceptions using try-except blocks, allowing the program to continue running even when errors occur.
Exceptions are Python's way of handling errors and exceptional situations that occur during program execution. They provide a mechanism to detect and respond to errors gracefully, preventing program crashes and allowing for proper error recovery.
Python exceptions form a hierarchy, with more specific exceptions inheriting from more general ones:
This example demonstrates basic exception handling in Python using try-except blocks to catch and handle different types of errors gracefully.
# Basic try-except block
try:
number = int("abc")
except ValueError:
print("Invalid number format")
# Multiple except blocks
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except TypeError:
print("Invalid type for operation")
# Catching all exceptions
try:
# Some risky operation
pass
except Exception as e:
print(f"An error occurred: {e}")
Invalid number format
Cannot divide by zero
This example demonstrates advanced exception handling techniques including try-except-else-finally blocks, raising exceptions, and creating custom exception classes.
# Try-except-else-finally
try:
number = int("123")
except ValueError:
print("Invalid number")
else:
print(f"Successfully converted: {number}")
finally:
print("This always executes")
# Raising exceptions
def divide_numbers(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
try:
result = divide_numbers(10, 0)
except ValueError as e:
print(e) # Cannot divide by zero
# Custom exceptions
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
try:
raise CustomError("This is a custom error")
except CustomError as e:
print(e.message)
Successfully converted: 123
This always executes
Cannot divide by zero
This is a custom error
Write a function that finds the maximum number in a list without using the built-in max() function.
def find_max(numbers):
if not numbers:
return None
max_num = numbers[0]
for num in numbers[1:]:
if num > max_num:
max_num = num
return max_num
# Test
numbers = [3, 7, 2, 9, 1, 5]
print(find_max(numbers)) # 9
Write a function to reverse a string without using the built-in reverse() method.
def reverse_string(text):
reversed_text = ""
for char in text:
reversed_text = char + reversed_text
return reversed_text
# Alternative solution using slicing
def reverse_string_slice(text):
return text[::-1]
# Test
text = "Hello, World!"
print(reverse_string(text)) # !dlroW ,olleH
print(reverse_string_slice(text)) # !dlroW ,olleH
Write a function to check if a string is a palindrome (reads the same forwards and backwards).
def is_palindrome(text):
# Remove spaces and convert to lowercase
cleaned_text = "".join(text.lower().split())
return cleaned_text == cleaned_text[::-1]
# Test
print(is_palindrome("racecar")) # True
print(is_palindrome("A man a plan a canal Panama")) # True
print(is_palindrome("hello")) # False