DeepSeek - Python Tutorial
DeepSeek - Python Tutorial
Table of Contents
1. Python Basics
2. Control Structures
3. Functions
4. Working with Files
5. Object-Oriented Programming
6. Working with APIs
1. Python Basics
# 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
# 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)
2. Control Structures
If-Else Statements
# Basic if-else
temperature = 30
Loops
# For loop
fruits = ["apple", "banana", "cherry"] # List of fruits
# 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
# 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
# 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
5. Object-Oriented Programming
# Class definition
class Dog: # Class names conventionally use CamelCase
"""A simple Dog class"""
# 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!
API Authentication
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
)
headers = {
'Authorization': f'token {GITHUB_TOKEN}', # Token-based auth
'Accept': 'application/vnd.github.v3+json' # Specify API version
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # Raises exception for 4XX/5XX errors
# 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']}")
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'
}
repos.extend(current_page_repos)
page += 1
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'])
import time
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def setup_session():
"""Configure session with retry strategy"""
session = requests.Session()
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:
Would you like me to expand on any particular section or provide additional examples?