Python Complete Practical Tutorial: From Basics to
Professional API Usage
This comprehensive tutorial will take you from Python basics to professional API usage with
detailed explanations for each concept and code line.
Table of Contents
1. Python Basics
2. Control Structures
3. Functions
4. Working with Files
5. Object-Oriented Programming
6. Working with APIs
7. Professional API Usage
1. Python Basics
Variables and Data Types
python Copy Download
# Integer variable
age = 25 # Declaring an integer variable to store age
# Explanation: 'age' is a variable name, '=' is assignment operator, '25' is the integer
value
# Float variable
temperature = 98.6 # Storing a decimal number
# Explanation: Floating-point numbers contain decimal points
# String variable
name = "Alice" # Text data enclosed in quotes
# Explanation: Strings can use single or double quotes
# Boolean variable
is_student = True # Can be True or False
# Explanation: Booleans represent binary true/false values
# Printing variables
print("Name:", name, "Age:", age) # Output multiple values
# Explanation: print() displays output to console, commas separate items
Basic Operations
python Copy Download
# Arithmetic operations
a = 10
b = 3
sum = a + b # Addition
difference = a - b # Subtraction
product = a * b # Multiplication
quotient = a / b # Division (returns float)
floor_division = a // b # Integer division
remainder = a % b # Modulus (remainder)
power = a ** b # Exponentiation (a to the power of b)
print("Sum:", sum) # Output: Sum: 13
# Explanation: Each operation performs basic math and stores result
2. Control Structures
If-Else Statements
python Copy Download
# Basic if-else
temperature = 30
if temperature > 25: # Condition to check
print("It's hot outside") # Executed if condition is True
# Explanation: Indented block runs when condition is met
elif temperature > 15: # Else-if condition
print("It's warm outside")
else: # Default case
print("It's cold outside")
Loops
python Copy Download
# For loop
fruits = ["apple", "banana", "cherry"] # List of fruits
for fruit in fruits: # Iterate through each item
print(fruit) # Print current fruit
# Explanation: 'fruit' takes each value in 'fruits' sequentially
# While loop
count = 0 # Initialize counter
while count < 5: # Condition to check
print("Count:", count)
count += 1 # Increment count (same as count = count + 1)
# Explanation: Loop continues until condition becomes False
3. Functions
Basic Functions
python Copy Download
# Function definition
def greet(name): # 'def' starts function definition, 'name' is parameter
"""This function greets the person passed as parameter""" # Docstring
print("Hello, " + name + "!") # Function body
# Function call
greet("Alice") # Output: Hello, Alice!
# Explanation: Calls the function with "Alice" as argument
# Function with return value
def square(number):
"""Returns the square of a number"""
return number * number # Returns computed value
result = square(4) # Stores returned value (16)
print(result)
4. Working with Files
Reading and Writing Files
python Copy Download
# Writing to a file
with open('example.txt', 'w') as file: # 'w' for write mode
file.write("Hello, World!\n") # Write text to file
file.write("This is a second line.")
# Explanation: 'with' ensures proper file closing after block
# Reading from a file
with open('example.txt', 'r') as file: # 'r' for read mode
content = file.read() # Read entire file content
print(content)
# Reading line by line
with open('example.txt', 'r') as file:
for line in file: # Iterate through lines
print("Line:", line.strip()) # strip() removes whitespace
5. Object-Oriented Programming
Classes and Objects
python Copy Download
# Class definition
class Dog: # Class names conventionally use CamelCase
"""A simple Dog class"""
def __init__(self, name, age): # Constructor method
"""Initialize name and age attributes"""
self.name = name # Instance variable
self.age = age # Instance variable
def bark(self): # Method
"""Make the dog bark"""
print(self.name + " says Woof!")
# Creating objects
my_dog = Dog("Rex", 3) # Create Dog instance
print(my_dog.name) # Access attribute: Output: Rex
my_dog.bark() # Call method: Output: Rex says Woof!
6. Working with APIs
Making HTTP Requests
python Copy Download
import requests # Import the requests library
# Basic GET request
response = requests.get('https://api.github.com') # Send GET request
# Explanation: requests.get() sends HTTP GET request to URL
print("Status Code:", response.status_code) # HTTP status code
print("Response Content:", response.text) # Response body as text
print("JSON Response:", response.json()) # Parse JSON response
API with Parameters
python Copy Download
# API request with parameters
params = {'q': 'python'} # Query parameters
response = requests.get('https://api.github.com/search/repositories', params=params)
# Check if request was successful
if response.status_code == 200: # HTTP 200 means OK
data = response.json() # Parse JSON response
print("Total repositories found:", data['total_count'])
# Explanation: Access JSON data like a dictionary
for repo in data['items'][:3]: # First 3 results
print(repo['name'], "-", repo['html_url'])
else:
print("Error:", response.status_code)
7. Professional API Usage
API Authentication
python Copy Download
import requests
from requests.auth import HTTPBasicAuth
# Basic Authentication
response = requests.get(
'https://api.github.com/user',
auth=HTTPBasicAuth('username', 'password') # Not recommended for production
)
# Better: Use environment variables or config files
import os
from dotenv import load_dotenv
load_dotenv() # Load environment variables from .env file
GITHUB_TOKEN = os.getenv('GITHUB_TOKEN') # Get token from environment
headers = {
'Authorization': f'token {GITHUB_TOKEN}', # Token-based auth
'Accept': 'application/vnd.github.v3+json' # Specify API version
}
response = requests.get('https://api.github.com/user', headers=headers)
print(response.json())
Handling API Responses Professionally
python Copy Download
def get_github_user(username):
"""Fetch GitHub user data with proper error handling"""
url = f'https://api.github.com/users/{username}'
headers = {'Accept': 'application/vnd.github.v3+json'}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # Raises exception for 4XX/5XX errors
return response.json() # Return parsed JSON on success
except requests.exceptions.HTTPError as errh:
print("HTTP Error:", errh)
except requests.exceptions.ConnectionError as errc:
print("Connection Error:", errc)
except requests.exceptions.Timeout as errt:
print("Timeout Error:", errt)
except requests.exceptions.RequestException as err:
print("Something went wrong:", err)
return None # Return None if request failed
# Usage
user_data = get_github_user('octocat')
if user_data:
print(f"Name: {user_data['name']}")
print(f"Bio: {user_data['bio']}")
print(f"Public repos: {user_data['public_repos']}")
Working with Paginated API Responses
python Copy Download
def get_all_repos(username):
"""Fetch all repositories for a user, handling pagination"""
repos = []
page = 1
per_page = 100 # Max allowed by GitHub API
while True:
url = f'https://api.github.com/users/{username}/repos'
params = {
'page': page,
'per_page': per_page,
'sort': 'updated'
}
response = requests.get(url, params=params)
response.raise_for_status()
current_page_repos = response.json()
if not current_page_repos: # No more repos
break
repos.extend(current_page_repos)
page += 1
# Check if we got fewer than requested (last page)
if len(current_page_repos) < per_page:
break
return repos
# Usage
repositories = get_all_repos('torvalds')
print(f"Total repositories: {len(repositories)}")
for repo in repositories[:5]: # Print first 5
print(repo['name'])
Rate Limiting and Retry Logic
python Copy Download
import time
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def setup_session():
"""Configure session with retry strategy"""
session = requests.Session()
# Configure retry strategy
retry_strategy = Retry(
total=3, # Total retries
backoff_factor=1, # Delay between retries (1, 2, 4 seconds)
status_forcelist=[429, 500, 502, 503, 504] # Status codes to retry
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("https://", adapter)
session.mount("http://", adapter)
return session
def make_api_call(url):
"""Make API call with rate limiting and retry"""
session = setup_session()
try:
response = session.get(url)
# Check rate limits (GitHub example)
if 'X-RateLimit-Remaining' in response.headers:
remaining = int(response.headers['X-RateLimit-Remaining'])
if remaining < 10: # Getting close to limit
reset_time = int(response.headers['X-RateLimit-Reset'])
sleep_time = max(reset_time - time.time(), 0)
print(f"Approaching rate limit. Sleeping for {sleep_time} seconds")
time.sleep(sleep_time)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
return None
# Usage
data = make_api_call('https://api.github.com/rate_limit')
if data:
print("Rate limit info:", data['resources']['core'])
This comprehensive tutorial covers Python from the very basics to professional API usage patterns.
Each section builds on the previous one, with detailed explanations for every line of code. To
continue your learning:
1. Practice each concept with your own variations
2. Explore more complex API integrations
3. Learn about async API calls with aiohttp
4. Study API documentation for services you want to use
5. Build projects that combine multiple concepts
Would you like me to expand on any particular section or provide additional examples?