💻 COMPLETE WORKING CODE
Master Python for
Generative AI
This is the only guide required to start your
Generative AI journey
1 Variables 2 Strings 3 Loops
4 Lists 5 Dicts 6 Files 7 Classes
Naved Khan + Follow
Senior Gen-AI Engineer
1. Variables & Basic Types 2
Variables store data values. Python automatically determines the data type based on
the value assigned.
Basic Data Types
[Link]
name = "Python" # str
age = 30 # int
price = 99.99 # float
is_active = True # bool
print(name) # Output: Python
print(age) # Output: 30
print(price) # Output: 99.99
print(is_active) # Output: True
# Type checking
print(type(name)) # Output: <class 'str'>
print(type(age)) # Output: <class 'int'>
Key Types: str (text), int (whole numbers), float (decimals), bool (True/False)
2/21
Naved Khan + Follow
Senior Gen-AI Engineer
2. Strings & f-strings 3
Strings are sequences of characters. f-strings allow embedding variables directly into
text using curly braces.
String Operations
[Link]
text = "Hello World"
print([Link]()) # Output: HELLO WORLD
print([Link]()) # Output: hello world
print([Link]("World", "Python")) # Output: Hello Python
f-strings (Formatted String Literals)
[Link]
# f-strings allow embedding variables
name = "Alice"
score = 95
message = f"Hello {name}, your score is {score}"
print(message) # Output: Hello Alice, your score is 95
# Multi-line f-string
info = f"""
Name: {name}
Score: {score}
Grade: A
"""
print(info)
3/21
Naved Khan + Follow
Senior Gen-AI Engineer
3. Basic Operators 4
Operators perform operations on values. Python supports arithmetic, comparison,
and logical operators.
Arithmetic Operators
[Link]
a, b = 10, 3
print(a + b) # Output: 13
print(a - b) # Output: 7
print(a * b) # Output: 30
print(a / b) # Output: 3.333...
print(a // b) # Output: 3
print(a % b) # Output: 1
( )
Comparison Operators
[Link]
# Compare values and return True/False
print(a > b) # Output: True
print(a == b) # Output: False
print(a != b) # Output: True
Logical Operators
[Link]
# Combine boolean expressions
print(True and False) # Output: False
print(True or False) # Output: True
print(not True) # Output: False
4/21
Naved Khan + Follow
Senior Gen-AI Engineer
4. User Input 5
The input() function reads text from the user. Always returns a string, so convert to
numbers when needed.
Getting User Input
[Link]
name = input("Enter your name: ")
# User enters: "Alice"
print(f"Hello, {name}!") # Output: Hello, Alice!
Converting Input to Number
[Link]
# Use int() or float() to convert
age = int(input("Enter your age: "))
# User enters: "25"
print(f"You are {age} years old") # Output: You are 25 years old
Multiple Inputs
[Link]
# Use split() and map() for multiple values
x, y = map(int, input("Enter two numbers: ").split())
# User enters: "10 20"
print(f"Sum: {x + y}") # Output: Sum: 30
5/21
Naved Khan + Follow
Senior Gen-AI Engineer
5. Conditional Statements 6
Conditional statements execute code based on conditions. Use if/elif/else to control
program flow.
if/elif/else Statements
[Link]
score = 85
if score >= 90:
print("Grade: A") # Output: (not executed)
elif score >= 80:
print("Grade: B") # Output: Grade: B
elif score >= 70:
print("Grade: C") # Output: (not executed)
else:
Ternary Operator
[Link]
# One-line conditional expression
status = "Pass" if score >= 60 else "Fail"
print(status) # Output: Pass
Multiple Conditions
[Link]
# Combine conditions with and/or
age = 20
if age >= 18 and age < 65:
print("Eligible to work") # Output: Eligible to work
6/21
Naved Khan + Follow
Senior Gen-AI Engineer
6. Lists Basics 7
Lists store ordered collections of items. Access elements by index, use slicing to get
subsets.
Creating and Accessing Lists
[Link]
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = ["hello", 42, True]
# Accessing elements
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry (last element)
# Slicing
print(numbers[1:3]) # Output: [2, 3]
print(numbers[:3]) # Output: [1, 2, 3]
print(numbers[2:]) # Output: [3, 4, 5]
# List length
print(len(fruits)) # Output: 3
7/21
Naved Khan + Follow
Senior Gen-AI Engineer
7. List Methods 8
List methods modify lists in-place. append() adds items, pop() removes and returns
items.
Common List Methods
list_methods.py
items = ["apple", "banana"]
# append() - add to end
[Link]("cherry")
print(items) # Output: ['apple', 'banana', 'cherry']
# pop() - remove and return last item
last = [Link]()
print(last) # Output: cherry
print(items) # Output: ['apple', 'banana']
# pop(index) - remove specific index
first = [Link](0)
print(first) # Output: apple
# Other useful methods
[Link](0, "orange") # Insert at index
[Link]("banana") # Remove by value
print(items) # Output: ['orange']
8/21
Naved Khan + Follow
Senior Gen-AI Engineer
8. Dictionaries 9
Dictionaries store key-value pairs. Access values by keys, perfect for structured data.
Creating and Using Dictionaries
[Link]
# Creating dictionaries
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Accessing values
print(person["name"]) # Output: Alice
print([Link]("age")) # Output: 30
# Adding/updating values
person["email"] = "alice@[Link]"
person["age"] = 31
print(person) # Output: {'name': 'Alice', 'age': 31, 'city': 'New
York', 'email': 'alice@[Link]'}
# Dictionary methods
print([Link]()) # Output: dict_keys(['name', 'age', 'city',
'email'])
print([Link]()) # Output: dict_values(['Alice', 31, 'New York',
'alice@[Link]'])
9/21
Naved Khan + Follow
Senior Gen-AI Engineer
9. Dictionary get() Method 10
get() safely retrieves values without raising errors. Returns None or a default value if
key doesn't exist.
Safe Dictionary Access
dict_get.py
data = {"name": "Bob", "age": 25}
# get() returns None if key doesn't exist (safe)
city = [Link]("city")
print(city) # Output: None
# get() with default value
city = [Link]("city", "Unknown")
print(city) # Output: Unknown
# Regular access raises KeyError if key missing
# city = data["city"] # Would raise KeyError
# get() for existing key
name = [Link]("name")
print(name) # Output: Bob
Checking if Key Exists
dict_get.py
if "age" in data:
print(f"Age: {data['age']}") # Output: Age: 25
10/21
Naved Khan + Follow
Senior Gen-AI Engineer
10. For Loops 11
For loops iterate over sequences. Use range() for numbers, iterate directly over
lists/strings.
Iterating Over Collections
for_loops.py
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output: apple
# Output: banana
# Output: cherry
# Using range()
for i in range(5):
print(i)
# Output: 0 1 2 3 4
# range with start and end
for i in range(2, 5):
print(i)
# Output: 2 3 4
# Iterating over dictionary
person = {"name": "Alice", "age": 30}
for key, value in [Link]():
print(f"{key}: {value}")
# Output: name: Alice
# Output: age: 30
11/21
Naved Khan + Follow
Senior Gen-AI Engineer
11. While Loops 12
While loops repeat code while a condition is true. Use break to exit, continue to skip
iterations.
Conditional Repetition
while_loops.py
# Basic while loop
count = 0
while count < 5:
print(count)
count += 1
# Output: 0 1 2 3 4
# While loop with break
num = 0
while True:
num += 1
if num > 3:
break
print(num)
# Output: 1 2 3
# While loop with continue
i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)
# Output: 1 2 4 5
12/21
Naved Khan + Follow
Senior Gen-AI Engineer
12. List Comprehensions 13
List comprehensions create lists concisely. Combine loops and conditions in one line
for efficiency.
Creating Lists Efficiently
[Link]
# Basic list comprehension
squares = [x ** 2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
# List comprehension with condition
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # Output: [0, 2, 4, 6, 8]
# List comprehension with transformation
words = ["hello", "world", "python"]
upper_words = [[Link]() for word in words]
print(upper_words) # Output: ['HELLO', 'WORLD', 'PYTHON']
Nested List Comprehension
[Link]
matrix = [[i * j for j in range(3)] for i in range(3)]
print(matrix) # Output: [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
13/21
Naved Khan + Follow
Senior Gen-AI Engineer
13. File Operations - Text 14
File operations read/write text files. Use 'with' statement for automatic file closing
and error handling.
Reading and Writing Text Files
file_text.py
# Writing to a file
with open("[Link]", "w") as f:
[Link]("Hello, World!\n")
[Link]("Python is great!")
# Reading from a file
with open("[Link]", "r") as f:
content = [Link]()
print(content) # Output: Hello, World!\nPython is great!
# Reading line by line
with open("[Link]", "r") as f:
for line in f:
print([Link]())
# Output: Hello, World!
# Output: Python is great!
Appending to Files
file_text.py
with open("[Link]", "a") as f:
[Link]("\nNew line added")
14/21
Naved Khan + Follow
Senior Gen-AI Engineer
14. File Operations - CSV 15
CSV files store tabular data. Use csv module to read/write structured data with
proper formatting.
Working with CSV Files
file_csv.py
import csv
# Writing CSV file
data = [
["Name", "Age", "City"],
["Alice", 30, "NYC"],
["Bob", 25, "LA"]
]
with open("[Link]", "w", newline="") as f:
writer = [Link](f)
[Link](data)
# Reading CSV file
with open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
Reading as Dictionary
file_csv.py
with open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
print(row["Name"]) # Output: Alice then Bob
15/21
Naved Khan + Follow
Senior Gen-AI Engineer
15. Exception Handling 16
Exception handling prevents crashes from errors. Use try/except to catch and handle
errors gracefully.
Error Handling Basics
[Link]
# Basic try/except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!") # Output: Cannot divide by zero!
# Multiple exceptions
try:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError:
print("Invalid input!")
except ZeroDivisionError:
print("Cannot divide by zero!")
# try/except/finally
try:
f = open("[Link]", "r")
data = [Link]()
except FileNotFoundError:
print("File not found!") # Output: File not found!
finally:
print("Cleanup code here") # Output: Cleanup code here
16/21
Naved Khan + Follow
Senior Gen-AI Engineer
16. Modules - datetime 17
The datetime module handles dates and times. Create dates, format them, and
perform date arithmetic.
Working with Dates and Times
datetime_module.py
from datetime import datetime, date, timedelta
# Current date and time
now = [Link]()
print(now) # Output: 2024-01-15 10:30:45.123456
# Formatting dates
formatted = [Link]("%Y-%m-%d %H:%M:%S")
print(formatted) # Output: 2024-01-15 10:30:45
# Creating specific date
birthday = date(1990, 5, 15)
print(birthday) # Output: 1990-05-15
# Date arithmetic
today = [Link]()
future = today + timedelta(days=30)
Parsing Date Strings
datetime_module.py
date_str = "2024-01-15"
parsed = [Link](date_str, "%Y-%m-%d")
print(parsed) # Output: 2024-01-15 00:00:00
17/21
Naved Khan + Follow
Senior Gen-AI Engineer
17. Modules - time 18
The time module provides time-related functions. Use sleep() for delays, time() for
timestamps.
Time Operations
time_module.py
import time
# Current time in seconds since epoch
timestamp = [Link]()
print(timestamp) # Output: 1705312245.123456
# Sleep/delay
print("Start")
[Link](2) # Wait 2 seconds
print("End") # Output: Start (wait 2s) End
# Formatted time string
formatted = [Link]("%Y-%m-%d %H:%M:%S", [Link]())
print(formatted) # Output: 2024-01-15 10:30:45
# Measuring execution time
start = [Link]()
[Link](0.1)
end = [Link]()
print(f"Elapsed: {end - start:.2f}s") # Output: Elapsed: 0.10s
18/21
Naved Khan + Follow
Senior Gen-AI Engineer
18. Classes Basics 19
Classes define objects with attributes and methods. Create reusable code structures
for complex data.
Defining and Using Classes
[Link]
# Defining a class
class Person:
# Class attribute
species = "Homo sapiens"
# Instance method
def greet(self):
return f"Hello, I'm {[Link]}"
# Creating an instance
person1 = Person()
[Link] = "Alice" # Instance attribute
print([Link]()) # Output: Hello, I'm Alice
print([Link]) # Output: Homo sapiens
# Multiple instances
person2 = Person()
[Link] = "Bob"
print([Link]()) # Output: Hello, I'm Bob
student2 = Student("Bob", 19, "B")
print([Link]) # Output: Bob
19/21
Naved Khan + Follow
Senior Gen-AI Engineer
19. Constructors (__init__) 20
Constructors initialize objects when created. The __init__ method sets up instance
attributes automatically.
Initializing Objects
[Link]
class Student:
# Constructor method
def __init__(self, name, age, grade):
[Link] = name
[Link] = age
[Link] = grade
def display_info(self):
return f"{[Link]}, Age: {[Link]}, Grade: {[Link]}"
# Creating instance with constructor
student1 = Student("Alice", 20, "A")
print(student1.display_info()) # Output: Alice, Age: 20, Grade: A
student2 = Student("Bob", 19, "B")
print([Link]) # Output: Bob
print([Link]) # Output: 19
print([Link]) # Output: B
20/21
Naved Khan + Follow
Senior Gen-AI Engineer
20. Class Examples 21
Complete class example showing attributes and methods working together. Methods
modify object state.
Complete Class Example
class_example.py
class Car:
def __init__(self, brand, model, year):
[Link] = brand
[Link] = model
[Link] = year
[Link] = 0
def accelerate(self, amount):
[Link] += amount
return f"Speed: {[Link]} km/h"
def get_info(self):
return f"{[Link]} {[Link]} {[Link]}"
my_car = Car("Toyota", "Camry", 2020)
print(my_car.get_info()) # Output: 2020 Toyota Camry
print(my_car.accelerate(30)) # Output: Speed: 30 km/h
print(my_car.speed) # Output: 30
print(my_car.accelerate(20)) # Output: Speed: 50 km/h
21/21
Naved Khan + Follow
Senior Gen-AI Engineer
Want more
content like this?
Naved Khan
Senior Gen-AI Engineer
Tap that follow button and
stay in the loop!
❤️ 💬 🔄 🔖
Like Comment Share Save