0% found this document useful (0 votes)
2 views39 pages

2 Python Programming Fundamentals

This document is a comprehensive beginner's guide to Python programming, covering essential topics such as variables, data types, control flow, functions, and data structures. It includes practical advice on setting up a development environment, writing code, and handling errors, as well as best practices for coding. The guide also features exercises, resources for further learning, and a glossary of terms.

Uploaded by

Nawaz Navu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views39 pages

2 Python Programming Fundamentals

This document is a comprehensive beginner's guide to Python programming, covering essential topics such as variables, data types, control flow, functions, and data structures. It includes practical advice on setting up a development environment, writing code, and handling errors, as well as best practices for coding. The guide also features exercises, resources for further learning, and a glossary of terms.

Uploaded by

Nawaz Navu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON PROGRAMMING FUNDAMENTALS

A Comprehensive Beginner's Guide to Coding in Python

TABLE OF CONTENTS

1. Introduction to Python and Programming

2. Setting Up Your Development Environment

3. Variables, Data Types, and Basic Operations

4. Control Flow: Conditionals and Loops

5. Functions: Building Reusable Code

6. Data Structures: Lists, Tuples, Dictionaries, and Sets

7. String Manipulation and Formatting

8. File Handling and Input/Output Operations

9. Error Handling and Exceptions

10. Object-Oriented Programming Basics

11. Modules and Libraries

12. Working with External Data

13. Best Practices and Code Style

14. Debugging Techniques

15. Building Your First Complete Project

16. Next Steps and Resources

17. Quick Reference Guide

18. Practice Exercises with Solutions

19. Glossary of Terms

20. Appendix: Common Error Messages and Fixes


CHAPTER 1: INTRODUCTION TO PYTHON AND PROGRAMMING

What is Programming?

Programming is the process of creating instructions that a computer can

execute to perform specific tasks. These instructions are written in

programming languages—formal languages designed to communicate with computers.

Programming allows you to:

- Automate repetitive tasks

- Analyze and visualize data

- Build websites and applications

- Solve complex mathematical problems

- Create games and simulations

- Control hardware and robots

Why Python?

Python is one of the most popular programming languages in the world, and for

good reason:

1. Readability: Python code reads almost like English, making it ideal for

beginners.

2. Versatility: Python is used in web development, data science, machine

learning, automation, scientific computing, and more.

3. Large Community: Millions of developers use Python, so help and resources

are readily available.

4. Extensive Libraries: Python has libraries for almost everything—from

analyzing DNA sequences to building neural networks.

5. Cross-Platform: Python runs on Windows, macOS, Linux, and even mobile devices.

A Brief History

Python was created by Guido van Rossum and first released in 1991. It was

designed with an emphasis on code readability and simplicity. The name Python

comes from Monty Python's Flying Circus, not the snake.

Python 3, released in 2008, is the current version and the one you should use.

Python 2 reached end-of-life in 2020 and is no longer supported.


How to Approach Learning Python

1. Practice Daily: Consistency beats intensity. Even 30 minutes of daily

practice is more effective than 5 hours once a week.

2. Type the Code: Do not just read examples—type them out yourself. Muscle

memory matters.

3. Experiment: Change variables, break things, and see what happens.

Experimentation accelerates learning.

4. Build Projects: Apply what you learn to real projects. Theory without

practice does not stick.

5. Embrace Errors: Error messages are your teachers, not enemies. Read them

carefully.
CHAPTER 2: SETTING UP YOUR DEVELOPMENT ENVIRONMENT

Installing Python

1. Visit [Link]

2. Download the latest version of Python 3 for your operating system

3. Run the installer

4. On Windows, check "Add Python to PATH" during installation

5. Verify installation by opening a terminal and typing:

python --version

Choosing a Code Editor

While you can write Python in any text editor, these options offer helpful

features:

1. VS Code (Free)

- Lightweight and fast

- Excellent Python extensions

- Built-in terminal

- Debugging support

2. PyCharm Community Edition (Free)

- Full-featured IDE specifically for Python

- Code completion and refactoring

- Integrated debugger

3. Jupyter Notebook (Free)

- Ideal for data analysis and experimentation

- Run code in chunks and see output immediately

- Great for visualizations

4. Thonny (Free, Beginner-Friendly)

- Simple interface designed for learners

- Step-through debugging

- Variable visualization

Your First Python Program

Open your editor and create a file named [Link]:


print("Hello, World!")

Save the file and run it:

- In terminal: python [Link]

- In VS Code: Press the play button or F5

Congratulations! You have written your first Python program.


CHAPTER 3: VARIABLES, DATA TYPES, AND BASIC OPERATIONS

Variables

Variables are containers for storing data values. In Python, you create a

variable by assigning a value to a name:

name = "Alice"
age = 25
height = 1.65
is_student = True

Variable Naming Rules:

- Must start with a letter or underscore

- Can contain letters, numbers, and underscores

- Case-sensitive (Name and name are different)

- Cannot use reserved keywords (if, for, while, etc.)

Good names: user_name, total_score, is_valid

Bad names: x, n, tmp (unless in very short contexts)

Basic Data Types

1. Integers (int)

Whole numbers: 42, -7, 0, 1000000

2. Floating-Point Numbers (float)

Decimal numbers: 3.14, -0.5, 2.0

3. Strings (str)

Text: "Hello", 'Python', "123"

Can use single or double quotes

4. Booleans (bool)

True or False

5. NoneType (None)

Represents the absence of a value

Checking Types

type(42) # <class 'int'>


type(3.14) # <class 'float'>
type("Hello") # <class 'str'>
type(True) # <class 'bool'>

Basic Operations
Arithmetic Operators:

+ Addition: 5 + 3 = 8

- Subtraction: 5 - 3 = 2

* Multiplication: 5 * 3 = 15

/ Division: 5 / 3 = 1.666...

// Floor Division: 5 // 3 = 1

% Modulo (remainder): 5 % 3 = 2

** Exponentiation: 5 ** 3 = 125

Comparison Operators:

== Equal to

!= Not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

Logical Operators:

and Both conditions must be True

or At least one condition must be True

not Inverts the condition

Type Conversion

int("42") # Converts string to integer: 42


float("3.14") # Converts string to float: 3.14
str(42) # Converts integer to string: "42"
bool(1) # Converts to boolean: True

Be careful with conversions:


int("3.14") # Error! Cannot convert float string directly to int
int(float("3.14")) # Correct: 3
CHAPTER 4: CONTROL FLOW: CONDITIONALS AND LOOPS

Conditional Statements (if/elif/else)

Conditionals allow your program to make decisions:

age = 18

if age < 13:


print("Child")
elif age < 20:
print("Teenager")
else:
print("Adult")

Key points:

- Use if for the first condition

- Use elif (else if) for additional conditions

- Use else for everything else

- Indentation matters in Python (typically 4 spaces)

Nested Conditionals

score = 85
attendance = 90

if score >= 70:


if attendance >= 80:

print("Pass")

else:

print("Fail due to attendance")


else:
print("Fail due to score")

The for Loop

For loops iterate over sequences:

# Iterate over a list


fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

# Iterate a specific number of times


for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4

# Iterate with index


for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")

The while Loop

While loops continue as long as a condition is True:

count = 0
while count < 5:
print(count)

count += 1

Be careful with while loops—if the condition never becomes False, you create

an infinite loop!

Loop Control Statements

break: Exit the loop immediately

for num in range(10):


if num == 5:

break

print(num) # Prints 0, 1, 2, 3, 4

continue: Skip to the next iteration

for num in range(5):


if num == 2:

continue

print(num) # Prints 0, 1, 3, 4

List Comprehensions

A concise way to create lists:

# Create a list of squares


squares = [x**2 for x in range(10)]
# Result: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# With a condition
evens = [x for x in range(20) if x % 2 == 0]
# Result: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
CHAPTER 5: FUNCTIONS: BUILDING REUSABLE CODE

What are Functions?

Functions are reusable blocks of code that perform a specific task. They help

you organize code, avoid repetition, and make programs easier to understand.

Defining Functions

def greet(name):
# This function greets the person passed in

return f"Hello, {name}!"

# Using the function


message = greet("Alice")
print(message) # Hello, Alice!

Function Components:

- def keyword

- Function name

- Parameters (in parentheses)

- Docstring (optional but recommended)

- Function body (indented)

- return statement (optional)

Parameters and Arguments

def add(a, b):


return a + b

result = add(5, 3) # 5 and 3 are arguments

Default Parameters:

def greet(name, greeting="Hello"):


return f"{greeting}, {name}!"

print(greet("Alice")) # Hello, Alice!


print(greet("Bob", "Hi")) # Hi, Bob!

Keyword Arguments:

def create_profile(name, age, city):


return f"{name}, {age}, from {city}"

profile = create_profile(age=25, city="New York", name="Alice")

Variable Arguments:

def sum_all(*numbers):
return sum(numbers)

print(sum_all(1, 2, 3, 4, 5)) # 15

def print_info(**kwargs):
for key, value in [Link]():

print(f"{key}: {value}")

print_info(name="Alice", age=25, city="NYC")

Scope: Local vs Global Variables

global_var = "I'm global"

def my_function():
local_var = "I'm local"

print(global_var) # Can access global

print(local_var) # Can access local

my_function()
print(global_var) # Works
# print(local_var) # Error! local_var does not exist here

Lambda Functions

Small anonymous functions:

square = lambda x: x ** 2
print(square(5)) # 25

# Often used with map, filter, sorted


numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
CHAPTER 6: DATA STRUCTURES: LISTS, TUPLES, DICTIONARIES,
AND SETS

Lists

-----

Ordered, mutable collections:

fruits = ["apple", "banana", "cherry"]

# Accessing elements
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last element)

# Slicing
print(fruits[0:2]) # ['apple', 'banana']

# Modifying
[Link]("date")
[Link](1, "apricot")
[Link]("banana")
popped = [Link]() # Removes and returns last element

# Other useful methods


[Link]()
[Link]()
print(len(fruits))
print("apple" in fruits)

Tuples

Ordered, immutable collections:

coordinates = (10, 20)

# Accessing
print(coordinates[0]) # 10

# Unpacking
x, y = coordinates

# Tuples are immutable


# coordinates[0] = 15 # Error!

# Use tuples when data should not change

Dictionaries

Key-value pairs:

person = {
"name": "Alice",

"age": 25,

"city": "New York"


}

# Accessing
print(person["name"])
print([Link]("email", "Not found"))

# Modifying
person["age"] = 26
person["email"] = "alice@[Link]"

# Methods
print([Link]())
print([Link]())
print([Link]())

# Iterating
for key, value in [Link]():
print(f"{key}: {value}")

Sets

----

Unordered collections of unique elements:

numbers = {1, 2, 3, 3, 3} # Duplicates removed


print(numbers) # {1, 2, 3}

# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b) # Union: {1, 2, 3, 4, 5, 6}


print(a & b) # Intersection: {3, 4}
print(a - b) # Difference: {1, 2}
print(a ^ b) # Symmetric difference: {1, 2, 5, 6}
CHAPTER 7: STRING MANIPULATION AND FORMATTING

String Basics

# Creating strings
single = 'Hello'
double = "World"
multiline = "This is a
multiline string"

# Concatenation
full = single + " " + double # "Hello World"

# Repetition
print("Hi! " * 3) # "Hi! Hi! Hi! "

String Methods

text = " Hello, World! "

print([Link]()) # " HELLO, WORLD! "


print([Link]()) # " hello, world! "
print([Link]()) # "Hello, World!"
print([Link]("World", "Python")) # " Hello, Python! "
print([Link](",")) # [' Hello', ' World! ']
print("-".join(["a", "b", "c"])) # "a-b-c"
print([Link]("World")) # 10
print([Link]("l")) # 3
print([Link](" ")) # True

String Formatting

f-strings (Recommended, Python 3.6+):

name = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old.")
print(f"Next year I'll be {age + 1}.")
print(f"Pi is approximately {3.14159:.2f}")

.format() method:

print("My name is {} and I'm {} years old.".format(name, age))


print("My name is {0} and I'm {1} years old.".format(name, age))
CHAPTER 8: FILE HANDLING AND INPUT/OUTPUT OPERATIONS

Reading Files

# Method 1: Using with statement (recommended)


with open("[Link]", "r") as file:
content = [Link]()

print(content)

# Read line by line


with open("[Link]", "r") as file:
for line in file:

print([Link]())

# Read all lines into a list


with open("[Link]", "r") as file:
lines = [Link]()

Writing Files

# Write (overwrites existing content)


with open("[Link]", "w") as file:
[Link]("Hello, World!

")

[Link]("Second line

")

# Append (adds to existing content)


with open("[Link]", "a") as file:
[Link]("Third line

")

File Modes

"r" - Read (default)

"w" - Write (creates new or truncates existing)

"a" - Append

"x" - Create (fails if file exists)

"b" - Binary mode

"t" - Text mode (default)

"r+" - Read and write

Working with CSV Files

import csv

# Reading CSV
with open("[Link]", "r") as file:
reader = [Link](file)

for row in reader:

print(row)

# Writing CSV
with open("[Link]", "w", newline="") as file:
writer = [Link](file)

[Link](["Name", "Age", "City"])

[Link](["Alice", 25, "NYC"])

[Link](["Bob", 30, "LA"])


CHAPTER 9: ERROR HANDLING AND EXCEPTIONS

Understanding Errors

Errors in Python fall into two categories:

1. Syntax errors: Code that violates Python's grammar rules

2. Exceptions: Errors that occur during execution

Common Built-in Exceptions:

- ValueError: Invalid value (e.g., int("abc"))

- TypeError: Wrong type (e.g., "2" + 2)

- IndexError: List index out of range

- KeyError: Dictionary key not found

- FileNotFoundError: File does not exist

- ZeroDivisionError: Division by zero

The try/except Block

try:
number = int(input("Enter a number: "))

result = 10 / number

print(f"Result: {result}")
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("You can't divide by zero!")
except Exception as e:
print(f"An unexpected error occurred: {e}")

The else and finally Clauses

try:
file = open("[Link]", "r")

content = [Link]()
except FileNotFoundError:
print("File not found!")
else:
print("File read successfully!")

print(content)
finally:
print("This always executes")
Raising Exceptions

def withdraw(balance, amount):


if amount > balance:

raise ValueError("Insufficient funds")

if amount < 0:

raise ValueError("Amount must be positive")

return balance - amount

Custom Exceptions

class ValidationError(Exception):
pass

class InvalidAgeError(ValidationError):
def __init__(self, age):

[Link] = age

[Link] = f"Age {age} is invalid. Must be between 0 and 150."

super().__init__([Link])

def validate_age(age):
if age < 0 or age > 150:

raise InvalidAgeError(age)
CHAPTER 10: OBJECT-ORIENTED PROGRAMMING BASICS

What is OOP?

Object-Oriented Programming (OOP) is a paradigm that organizes code around

"objects"—bundles of data (attributes) and behavior (methods).

Key Concepts:

- Class: A blueprint for creating objects

- Object: An instance of a class

- Attributes: Data stored in an object

- Methods: Functions that belong to a class

Creating a Class

class Dog:
# Class attribute (shared by all instances)

species = "Canis familiaris"

def __init__(self, name, age):

# Instance attributes

[Link] = name

[Link] = age

def bark(self):

return f"{[Link]} says woof!"

def get_human_age(self):

return [Link] * 7

# Creating objects
my_dog = Dog("Buddy", 3)
print(my_dog.name) # Buddy
print(my_dog.bark()) # Buddy says woof!
print(my_dog.get_human_age()) # 21

The __init__ Method

This special method (constructor) runs automatically when you create a new

object. It initializes the object's attributes.

self Parameter

self refers to the current instance of the class. It must be the first

parameter of instance methods, though you don't pass it explicitly when


calling the method.

Inheritance

Inheritance allows a class to inherit attributes and methods from another class:

class Animal:
def __init__(self, name):

[Link] = name

def speak(self):

raise NotImplementedError("Subclass must implement this")

class Cat(Animal):
def speak(self):

return f"{[Link]} says meow!"

class Dog(Animal):
def speak(self):

return f"{[Link]} says woof!"

animals = [Cat("Whiskers"), Dog("Buddy")]


for animal in animals:
print([Link]())

Encapsulation

Control access to attributes:

class BankAccount:
def __init__(self, owner, balance=0):

[Link] = owner

self._balance = balance # Protected (convention)

@property

def balance(self):

return self._balance

def deposit(self, amount):

if amount > 0:

self._balance += amount

return True

return False

def withdraw(self, amount):

if 0 < amount <= self._balance:


self._balance -= amount

return True

return False
CHAPTER 11: MODULES AND LIBRARIES

What are Modules?

Modules are Python files containing functions, classes, and variables that you

can import and use in other programs.

Importing Modules

# Import entire module


import math
print([Link](16))

# Import specific items


from math import sqrt, pi
print(sqrt(16))
print(pi)

# Import with alias


import numpy as np
import pandas as pd

# Import everything (generally not recommended)


from math import *

Creating Your Own Modules

Create a file named my_module.py:

def greet(name):
return f"Hello, {name}!"

PI = 3.14159

Use it in another file:

import my_module
print(my_module.greet("Alice"))
print(my_module.PI)

Popular Standard Library Modules

- os: Operating system interface

- sys: System-specific parameters

- datetime: Date and time manipulation

- json: JSON data handling

- re: Regular expressions

- collections: Advanced data structures

- itertools: Iterator tools

- math, random, statistics: Mathematical operations


CHAPTER 12: WORKING WITH EXTERNAL DATA

Working with JSON

JSON (JavaScript Object Notation) is a common data format:

import json

# Python to JSON
person = {"name": "Alice", "age": 25}
json_string = [Link](person, indent=2)

# JSON to Python
parsed = [Link](json_string)

# Reading JSON from file


with open("[Link]", "r") as file:
data = [Link](file)

# Writing JSON to file


with open("[Link]", "w") as file:
[Link](data, file, indent=2)

Working with APIs

import requests

response = [Link]("[Link]
if response.status_code == 200:
data = [Link]()

print(data)
else:
print(f"Error: {response.status_code}")
CHAPTER 13: BEST PRACTICES AND CODE STYLE

PEP 8: The Python Style Guide

PEP 8 is the official style guide for Python code. Following it makes your

code more readable and professional.

Key Guidelines:

1. Indentation

Use 4 spaces per indentation level. Never mix tabs and spaces.

2. Line Length

Limit lines to 79 characters. Use parentheses for implicit line continuation.

3. Blank Lines

- Two blank lines between top-level functions and classes

- One blank line between methods in a class

4. Imports

- One import per line

- Group imports: standard library, third-party, local

- Use absolute imports

5. Naming Conventions

- Variables and functions: lowercase_with_underscores

- Classes: CapitalizedWords

- Constants: UPPERCASE_WITH_UNDERSCORES

- Private attributes: _leading_underscore

6. Whitespace

- No spaces inside parentheses

- One space after commas

- One space around operators

Docstrings

Document your functions and classes:

def calculate_area(length, width):


# Calculate the area of a rectangle.

#
# Args:

# length (float): The length of the rectangle

# width (float): The width of the rectangle

# Returns:

# float: The area of the rectangle

# Raises:

# ValueError: If length or width is negative

if length < 0 or width < 0:

raise ValueError("Dimensions must be non-negative")

return length * width


CHAPTER 14: DEBUGGING TECHNIQUES

Print Debugging

The simplest but often effective technique:

def calculate(x, y):


print(f"DEBUG: x={x}, y={y}")

result = x + y

print(f"DEBUG: result={result}")

return result

Using the Debugger (pdb)

import pdb

def complex_function():
x = 10

y = 20

pdb.set_trace() # Execution pauses here

result = x + y

return result

Common pdb commands:

- n (next): Execute next line

- s (step): Step into function call

- c (continue): Continue execution

- p variable: Print variable value

- q (quit): Exit debugger

Assertions

def divide(a, b):


assert b != 0, "Divisor cannot be zero"

return a / b
CHAPTER 15: BUILDING YOUR FIRST COMPLETE PROJECT

Project: To-Do List Application

Let's build a command-line to-do list application that demonstrates the

concepts we've learned.

import json
from datetime import datetime

class TodoList:
def __init__(self, filename="[Link]"):

[Link] = filename

[Link] = self.load_tasks()

def load_tasks(self):

try:

with open([Link], "r") as file:

return [Link](file)

except FileNotFoundError:

return []

def save_tasks(self):

with open([Link], "w") as file:

[Link]([Link], file, indent=2)

def add_task(self, description, priority="medium"):

task = {

"id": len([Link]) + 1,

"description": description,

"priority": priority,

"completed": False,

"created": [Link]().isoformat()

[Link](task)

self.save_tasks()

print(f"Task added: {description}")

def list_tasks(self):

if not [Link]:
print("No tasks found!")

return

for task in [Link]:

status = "[X]" if task["completed"] else "[ ]"

print(f"{status} {task['id']}. {task['description']} "

f"(Priority: {task['priority']})")

def complete_task(self, task_id):

for task in [Link]:

if task["id"] == task_id:

task["completed"] = True

self.save_tasks()

print(f"Task {task_id} completed!")

return

print(f"Task {task_id} not found.")

def delete_task(self, task_id):

[Link] = [t for t in [Link] if t["id"] != task_id]

self.save_tasks()

print(f"Task {task_id} deleted.")

def main():
todo = TodoList()

while True:

print("

Todo List ")

print("1. Add task")

print("2. List tasks")

print("3. Complete task")

print("4. Delete task")

print("5. Exit")

choice = input("Choose an option: ")

if choice == "1":

desc = input("Task description: ")


priority = input("Priority (low/medium/high): ") or "medium"

todo.add_task(desc, priority)

elif choice == "2":

todo.list_tasks()

elif choice == "3":

task_id = int(input("Task ID to complete: "))

todo.complete_task(task_id)

elif choice == "4":

task_id = int(input("Task ID to delete: "))

todo.delete_task(task_id)

elif choice == "5":

print("Goodbye!")

break

else:

print("Invalid option. Please try again.")

if __name__ == "__main__":
main()
CHAPTER 16: NEXT STEPS AND RESOURCES

Where to Go From Here

1. Web Development

- Learn Flask or Django for backend development

- Learn HTML, CSS, and JavaScript for frontend

- Build web applications

2. Data Science

- Master NumPy, Pandas, and Matplotlib

- Learn statistics and machine learning

- Explore scikit-learn and TensorFlow

3. Automation and Scripting

- Automate file operations

- Build web scrapers with BeautifulSoup

- Create system administration scripts

4. Game Development

- Learn Pygame for 2D games

- Explore Panda3D for 3D games

5. Desktop Applications

- Learn Tkinter for simple GUIs

- Explore PyQt or Kivy for advanced applications

Recommended Resources

Books:

- "Automate the Boring Stuff with Python" by Al Sweigart

- "Python Crash Course" by Eric Matthes

- "Fluent Python" by Luciano Ramalho

- "Effective Python" by Brett Slatkin

Online Platforms:

- Codecademy: Interactive Python courses

- LeetCode: Practice coding problems

- HackerRank: Coding challenges and competitions

- Real Python: In-depth tutorials and articles


Communities:

- r/learnpython (Reddit)

- Python Discord server

- Stack Overflow

- [Link] documentation
CHAPTER 17: QUICK REFERENCE GUIDE

Data Types

int: 42, -7, 0

float: 3.14, -0.5

str: "Hello", 'World'

bool: True, False

list: [1, 2, 3]

tuple: (1, 2, 3)

dict: {"key": "value"}

set: {1, 2, 3}

Operators

Arithmetic: +, -, *, /, //, %, **

Comparison: ==, !=, >, <, >=, <=

Logical: and, or, not

Assignment: =, +=, -=, *=, /=

Control Flow

if condition:
# code
elif other_condition:
# code
else:
# code

for item in iterable:


# code

while condition:
# code

Common Built-in Functions

print(), len(), type(), int(), float(), str()

range(), enumerate(), zip(), map(), filter()

sum(), min(), max(), sorted(), reversed()

input(), open(), isinstance(), hasattr()

String Methods

.upper(), .lower(), .strip(), .split()


.join(), .replace(), .find(), .count()

.startswith(), .endswith(), .format()

List Methods

.append(), .extend(), .insert(), .remove()

.pop(), .sort(), .reverse(), .index()

.count(), .copy(), .clear()

Dict Methods

.keys(), .values(), .items()

.get(), .update(), .pop(), .clear()

File Operations

open(), .read(), .readline(), .readlines()

.write(), .close(), with statement


CHAPTER 18: PRACTICE EXERCISES WITH SOLUTIONS

Exercise 1: Temperature Converter

Write a function that converts Celsius to Fahrenheit and vice versa.

Solution:

def convert_temperature(value, scale):


if [Link]() == "c":

return (value * 9/5) + 32

elif [Link]() == "f":

return (value - 32) * 5/9

else:

raise ValueError("Scale must be 'C' or 'F'")

# Test
print(convert_temperature(0, "C")) # 32.0
print(convert_temperature(32, "F")) # 0.0

Exercise 2: Palindrome Checker

Write a function that checks if a string is a palindrome.

Solution:

def is_palindrome(text):
cleaned = "".join([Link]() for char in text if [Link]())

return cleaned == cleaned[::-1]

# Test
print(is_palindrome("A man a plan a canal Panama")) # True
print(is_palindrome("Hello")) # False

Exercise 3: Fibonacci Sequence

Write a function that generates the first n Fibonacci numbers.

Solution:

def fibonacci(n):
if n <= 0:

return []

elif n == 1:

return [0]

fibs = [0, 1]

while len(fibs) < n:

[Link](fibs[-1] + fibs[-2])
return fibs

# Test
print(fibonacci(10))
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Exercise 4: Word Frequency Counter

Write a function that counts word frequencies in a text.

Solution:

def word_frequency(text):
words = [Link]().split()

frequency = {}

for word in words:

word = [Link](".,!?;:"'")

frequency[word] = [Link](word, 0) + 1

return frequency

# Test
text = "The quick brown fox jumps over the lazy dog"
print(word_frequency(text))

Exercise 5: Simple Calculator Class

Create a Calculator class with basic operations.

Solution:

class Calculator:
def add(self, a, b):

return a + b

def subtract(self, a, b):

return a - b

def multiply(self, a, b):

return a * b

def divide(self, a, b):

if b == 0:

raise ValueError("Cannot divide by zero")

return a / b

def power(self, a, b):

return a ** b

# Test
calc = Calculator()
print([Link](5, 3)) # 8
print([Link](10, 2)) # 5.0
CHAPTER 19: GLOSSARY OF TERMS

Algorithm: A step-by-step procedure for solving a problem

Argument: A value passed to a function when called

Attribute: A variable that belongs to an object or class

Boolean: A data type with values True or False

Class: A blueprint for creating objects

Compiler: A program that translates code into machine language

Condition: An expression that evaluates to True or False

Data Structure: A way of organizing and storing data

Debug: The process of finding and fixing errors in code

Function: A reusable block of code that performs a specific task

IDE: Integrated Development Environment

Immutable: An object that cannot be changed after creation

Index: A number representing a position in a sequence

Interpreter: A program that executes code line by line

Iteration: Repeating a process multiple times

Library: A collection of pre-written code for specific tasks

List: An ordered, mutable collection of items

Loop: A control structure for repeating code

Method: A function that belongs to a class

Module: A file containing Python code

Mutable: An object that can be changed after creation

Object: An instance of a class

Operator: A symbol that performs an operation

Parameter: A variable in a function definition

Recursion: A function that calls itself

Scope: The region of code where a variable is accessible

String: A sequence of characters

Syntax: The rules that define valid code

Tuple: An ordered, immutable collection of items

Variable: A named container for storing data


CHAPTER 20: APPENDIX - COMMON ERROR MESSAGES AND
FIXES

SyntaxError: invalid syntax

Cause: Typo, missing colon, incorrect indentation

Fix: Check for missing colons after if/for/while/def statements

Ensure consistent indentation (4 spaces)

NameError: name 'x' is not defined

Cause: Using a variable before defining it, typo in variable name

Fix: Check spelling, ensure variable is defined before use

TypeError: unsupported operand type(s)

Cause: Trying to perform an operation on incompatible types

Fix: Convert types appropriately (str(), int(), float())

IndexError: list index out of range

Cause: Accessing an index that doesn't exist

Fix: Check list length with len() before accessing

Use negative indices or .get() for safe access

KeyError: 'key'

Cause: Accessing a dictionary key that doesn't exist

Fix: Use .get() method with default value

Check if key exists with 'key' in dict

ValueError: invalid literal for int()

Cause: Trying to convert invalid string to number

Fix: Validate input before conversion

Use try/except for safe conversion

IndentationError: unexpected indent

Cause: Inconsistent indentation

Fix: Use spaces instead of tabs

Ensure all blocks have consistent indentation

AttributeError: 'NoneType' object has no attribute

Cause: Trying to use a method on None

Fix: Check if variable is None before using


Ensure functions return values properly

ModuleNotFoundError: No module named 'x'

Cause: Trying to import a module that isn't installed

Fix: Install with pip: pip install module_name

Check for typos in module name

ZeroDivisionError: division by zero

Cause: Dividing by zero

Fix: Check if denominator is zero before dividing

Use conditional logic or try/except

CONCLUSION

Congratulations on completing this comprehensive guide to Python programming!

You now have a solid foundation in:

- Python syntax and data types

- Control flow and functions

- Data structures

- File handling and error management

- Object-oriented programming

- Best practices and debugging

Remember that programming is a skill best developed through practice. Do not

just read about concepts—build things with them. Start with small projects,

make mistakes, debug them, and learn from the process.

The Python community is welcoming and supportive. When you get stuck, do not

hesitate to ask questions on Stack Overflow, Reddit's r/learnpython, or

Python Discord.

Keep coding, keep learning, and most importantly—have fun!

Document Version 1.0


Total Pages: 35+

You might also like