Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and readability. Created by Guido van Rossum and first released in 1991, Python has become one of the most popular programming languages in the world.
Python's philosophy emphasizes code readability and simplicity, making it an excellent choice for beginners and experienced developers alike. The language supports multiple programming paradigms, including procedural, object-oriented, and functional programming.
Key features of Python include:
- Easy-to-learn syntax that emphasizes readability
- Extensive standard library with built-in modules
- Cross-platform compatibility
- Large and active community support
- Versatile applications in web development, data science, AI, and more
To get started with Python, you need to install it on your system. You can download Python from the official website at python.org
. Once installed, you can run Python code using the interactive interpreter or by creating Python files with the .py
extension.
# Your first Python program
print("Hello, World!")
print("Welcome to Python programming!")
Python Syntax and Variables
Python syntax is designed to be intuitive and readable. Unlike many other programming languages, Python uses indentation to define code blocks instead of curly braces or keywords.
Variables in Python are created when you assign a value to them. Python is dynamically typed, meaning you don't need to declare the type of a variable explicitly.
# Variable assignment
name = "Alice"
age = 25
height = 5.6
is_student = True
# Python uses indentation for code blocks
if age >= 18:
print("You are an adult")
print("You can vote")
else:
print("You are a minor")
Python follows specific naming conventions for variables. Variable names should be descriptive and follow the snake_case convention. They must start with a letter or underscore, and can contain letters, numbers, and underscores.
myVariable
and myvariable
are different variables.
Comments in Python start with the #
symbol for single-line comments, or use triple quotes for multi-line comments. Proper commenting is essential for code maintainability.
Data Types and Structures
Python provides several built-in data types that are essential for programming. Understanding these data types is crucial for effective Python programming.
The basic data types in Python include integers, floats, strings, and booleans. Python also provides powerful data structures like lists, tuples, dictionaries, and sets.
# Basic data types
integer_num = 42
float_num = 3.14159
text_string = "Hello, Python!"
boolean_value = True
# Data structures
my_list = [1, 2, 3, "four", 5.0]
my_tuple = (10, 20, 30)
my_dict = {"name": "John", "age": 30, "city": "New York"}
my_set = {1, 2, 3, 4, 5}
Lists are ordered, mutable collections that can contain different data types. They support indexing, slicing, and various methods for manipulation.
- Lists: Ordered, mutable collections
[1, 2, 3]
- Tuples: Ordered, immutable collections
(1, 2, 3)
- Dictionaries: Key-value pairs
{"key": "value"}
- Sets: Unordered collections of unique elements
{1, 2, 3}
Python's dynamic typing allows variables to change their type during runtime, providing flexibility but requiring careful attention to data type management in larger applications.
Control Flow Statements
Control flow statements allow you to control the execution order of your program. Python provides several control flow statements including conditional statements and loops.
The if
, elif
, and else
statements are used for conditional execution. Python also provides for
and while
loops for repetitive tasks.
# Conditional statements
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Your grade is: {grade}")
# For loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
# While loop
count = 0
while count < 5:
print(f"Count: {count}")
count += 1
Python's for
loops are particularly powerful because they can iterate over any iterable object, including strings, lists, tuples, and dictionaries. The range()
function is commonly used to generate sequences of numbers for loops.
- Use
break
to exit a loop prematurely - Use
continue
to skip the current iteration - Use
pass
as a placeholder for empty code blocks
List comprehensions provide a concise way to create lists based on existing lists or other iterables, combining loops and conditional logic in a single line.
Functions and Modules
Functions are reusable blocks of code that perform specific tasks. They help organize code, reduce repetition, and make programs more modular and maintainable.
Python functions are defined using the def
keyword, followed by the function name and parameters. Functions can accept arguments, perform operations, and return values.
# Function definition
def greet_user(name, age=18):
"""
This function greets a user with their name and age.
Default age is 18 if not provided.
"""
message = f"Hello, {name}! You are {age} years old."
return message
# Function calls
greeting1 = greet_user("Alice", 25)
greeting2 = greet_user("Bob") # Uses default age
print(greeting1)
print(greeting2)
# Lambda functions (anonymous functions)
square = lambda x: x ** 2
print(square(5)) # Output: 25
Modules are Python files containing functions, classes, and variables that can be imported and used in other Python programs. Python's extensive standard library provides modules for various tasks.
- Import entire modules:
import math
- Import specific functions:
from math import sqrt
- Import with aliases:
import numpy as np
Creating your own modules involves saving Python code in a .py
file and importing it into other programs. This promotes code reusability and organization in larger projects.
Function parameters can include default values, keyword arguments, and variable-length arguments using *args
and **kwargs
, providing flexibility in function design.
Object Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm that organizes code into classes and objects. Python fully supports OOP concepts including encapsulation, inheritance, and polymorphism.
Classes are blueprints for creating objects, while objects are instances of classes. Classes define attributes (data) and methods (functions) that objects can have.
# Class definition
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.mileage = 0
def drive(self, miles):
self.mileage += miles
print(f"Drove {miles} miles. Total mileage: {self.mileage}")
def get_info(self):
return f"{self.year} {self.make} {self.model}"
# Creating objects
my_car = Car("Toyota", "Camry", 2022)
print(my_car.get_info())
my_car.drive(100)
# Inheritance
class ElectricCar(Car):
def __init__(self, make, model, year, battery_size):
super().__init__(make, model, year)
self.battery_size = battery_size
def charge(self):
print("Charging the battery...")
Inheritance allows classes to inherit attributes and methods from parent classes, promoting code reuse and creating hierarchical relationships between classes.
- Encapsulation: Bundling data and methods within classes
- Inheritance: Creating new classes based on existing classes
- Polymorphism: Using the same interface for different data types
Python supports multiple inheritance, allowing a class to inherit from multiple parent classes. Special methods like __init__
, __str__
, and __len__
provide customized behavior for objects.
Error Handling and Exceptions
Error handling is crucial for writing robust Python programs. Python uses exceptions to handle errors that occur during program execution, allowing programs to respond gracefully to unexpected situations.
The try
, except
, else
, and finally
statements are used to handle exceptions. This mechanism prevents programs from crashing when errors occur.
# Basic exception handling
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ValueError:
print("Invalid input! Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("Operation completed successfully!")
finally:
print("This block always executes.")
# Raising custom exceptions
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Age seems unrealistic")
return True
Python provides many built-in exception types for different error conditions. You can also create custom exceptions by defining classes that inherit from the Exception
class.
ValueError
: Raised when a function receives an argument of correct type but inappropriate valueTypeError
: Raised when an operation is performed on an inappropriate typeIndexError
: Raised when trying to access an index that doesn't existKeyError
: Raised when trying to access a dictionary key that doesn't existFileNotFoundError
: Raised when trying to open a file that doesn't exist
Proper exception handling improves user experience and makes debugging easier. Always handle specific exceptions when possible, rather than using broad exception handlers.
The finally
block is useful for cleanup operations that must execute regardless of whether an exception occurred, such as closing files or database connections.