Python Programming
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 worldwide.
Python supports multiple programming paradigms, including structured, object-oriented, functional, imperative, and aspect-oriented programming.
Why Learn Python?
- Beginner-friendly - Simple syntax that's easy to learn
- Versatile - Used in web development, data science, AI, and more
- Large community - Extensive libraries and frameworks
- Cross-platform - Runs on Windows, macOS, and Linux
- Open source - Free to use and distribute
Key Application Areas
Web Development
Django, Flask, FastAPI
Data Science
Pandas, NumPy, Matplotlib
Machine Learning
TensorFlow, PyTorch, Scikit-learn
Installing Python
Python is available for all major operating systems. The installation process is straightforward and well-documented.
Windows Installation
- Download the installer from the official website: python.org
- Run the downloaded .exe file
- Check "Add Python to PATH" during installation
- Click "Install Now"
- Verify installation by opening Command Prompt and typing
python --version
macOS Installation
- Download the macOS installer from the official website
- Open the downloaded .pkg file
- Follow the installation prompts
- Verify installation in Terminal with
python3 --version
Linux Installation
Most Linux distributions come with Python pre-installed. To install the latest version:
# For Ubuntu/Debian
sudo apt update
sudo apt install python3
# For Fedora
sudo dnf install python3
# Verify installation
python3 --version
Pro Tip
Use virtual environments to isolate project dependencies. Create one with:
python -m venv myenv
Python Syntax Basics
Python syntax is designed for readability with significant whitespace and minimal punctuation.
Indentation Matters
Python uses indentation to define code blocks instead of curly braces.
# Correct
if 5 > 2:
print("Five is greater than two!")
# Incorrect (will cause error)
if 5 > 2:
print("Five is greater than two!")
Comments
Comments start with #
and run to the end of the line.
# This is a single-line comment
"""
This is a multi-line comment.
It can span multiple lines.
"""
print("Hello, World!") # Comment after code
Try It Yourself!
# Your first Python program
print("Hello, World!")
# Simple calculation
result = 5 * 3
print("5 multiplied by 3 is:", result)
# Conditional statement
if result > 10:
print("Result is greater than 10!")
else:
print("Result is 10 or less")
Variables & Data Types
Variables are created when you assign a value. Python determines the data type automatically.
Basic Data Types
- Integer (int) - Whole numbers without decimals
- Float (float) - Numbers with decimals
- String (str) - Sequence of characters
- Boolean (bool) - True or False
- List (list) - Ordered, mutable collection
- Tuple (tuple) - Ordered, immutable collection
- Dictionary (dict) - Key-value pairs collection
# Integers
age = 25
# Floats
temperature = 36.6
# Strings
name = "John"
# Booleans
is_student = True
# List
fruits = ["apple", "banana", "orange"]
# Tuple
coordinates = (10.5, 20.3)
# Dictionary
person = {
"name": "Maria",
"age": 30,
"city": "New York"
}
Try It Yourself!
# Working with numbers
x = 10
y = 3.5
sum = x + y
print("Sum:", sum)
# Working with strings
greeting = "Hello, "
name = "Anna"
message = greeting + name
print(message)
# Working with lists
numbers = [1, 2, 3, 4, 5]
numbers.append(6)
print("Number list:", numbers)
# Working with dictionaries
book = {"title": "War and Peace", "author": "Tolstoy", "year": 1869}
print(f"Book: {book['title']}, Author: {book['author']}")
# Type checking
print("Type of x:", type(x))
print("Type of name:", type(name))
print("Type of numbers:", type(numbers))
Conditional Statements
Conditional statements let you execute different code blocks based on conditions.
The if Statement
if condition:
# execute if condition is true
elif another_condition:
# execute if first condition is false and this is true
else:
# execute if all conditions are false
Try It Yourself!
# Determine leap year
year = 2024
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
else:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
# Password check
password = "Python123"
user_input = "python123"
if user_input == password:
print("Access granted!")
else:
print("Incorrect password!")
Loops in Python
Loops allow you to execute a block of code repeatedly. Python has two loop types: for
and while
.
For Loop
Used to iterate over sequences (lists, tuples, strings, etc.).
# Iterate through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterate through a string
for char in "Python":
print(char)
# Using range()
for i in range(5): # 0 to 4
print(i)
for i in range(2, 6): # 2 to 5
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
While Loop
Executes a block of code as long as a condition is true.
# Counter
count = 0
while count < 5:
print(count)
count += 1 # equivalent to count = count + 1
Try It Yourself!
# Find prime numbers
print("Prime numbers between 2 and 30:")
for num in range(2, 31):
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=" ")
print("\n\nEven numbers from 0 to 10:")
n = 0
while n <= 10:
if n % 2 != 0:
n += 1
continue
print(n, end=" ")
n += 1
Functions in Python
Functions allow you to group code for reuse and organization.
Defining Functions
def function_name(parameters):
"""Function documentation (docstring)"""
# function body
return result # optional
Try It Yourself!
# Factorial function
def factorial(n):
"""Calculate factorial of n"""
if n == 0:
return 1
else:
return n * factorial(n-1)
print("Factorial of 5:", factorial(5))
# Fibonacci function
def fibonacci(n):
"""Return nth Fibonacci number"""
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print("First 10 Fibonacci numbers:")
for i in range(10):
print(fibonacci(i), end=" ")
Learning Resources
Official Documentation
Online Courses
Recommended Books
- Automate the Boring Stuff with Python - Al Sweigart
- Python Crash Course - Eric Matthes
- Fluent Python - Luciano Ramalho
Practice Platforms
- Codewars - Coding challenges
- LeetCode - Algorithm practice
- Project Euler - Math-based problems