Applying Python Basics in
Practice
What you'll be able to do:
- Apply Python basics to solve simple problems
- Use functions and file operations effectively
- Debug and run scripts from the command line
Introduction: What is Python and Why
Should You Care?
Core Definition
- Python is a versatile, beginner-friendly
programming language used for automation, data analysis, web development,
and more. Its simple syntax allows you to focus on problem-solving rather
than language rules.
A Simple Analogy
- Think of Python as LEGO blocks. Each block is
a small piece of functionality (variables, functions, or loops). You can
combine them to build simple toys or complex structures.
Limitation:
- Unlike LEGO, Python’s blocks require logical
order, or the program won’t run.
Why This Matters to You
Problem it solves:
- Python lets you automate tasks, analyze data,
and quickly test ideas without writing long, complicated code.
What you'll gain:
- Write small scripts to automate tasks like
file renaming
- Debug your code efficiently and fix errors
- Build reusable functions to save time in
multiple projects
Real-world context:
- Python powers web applications, data analysis
pipelines, and even AI/ML experiments.
The Foundation: Core Concepts Explained
Concept A: Variables
Definition:
- Variables are names that store information for
use in your program. They can hold numbers, text, or other types of data.
Key characteristics:
- You can store any type without declaring it
explicitly.
- Good variable names improve code readability.
Memory storage:
- Variables point to memory locations storing
the actual data.
Example:
name = "Amit"
age = 21
Common confusion:
- Variables can change type dynamically, but
changing types unintentionally may lead to errors.
Concept B: Virtualenv
Definition:
- Virtualenv is a tool that creates isolated
Python environments so project dependencies don’t conflict.
Key characteristics:
- Isolated packages per project
- Easy activation/deactivation
- Helps manage different Python versions
Example:
python -m venv myenv
source myenv/bin/activate
Common confusion:
- Forgetting to activate the environment will
install packages globally instead of the project-specific environment.
Concept C: Data Types
Definition:
Data types determine
the kind of data a variable holds: integer, string, float, boolean, list,
tuple, dictionary, etc.
Key characteristics:
- Strings and tuples are immutable, lists and
dictionaries are mutable.
Type conversion:
- Convert between types using int(), str(),
float(), etc.
Operations: Each type
supports specific operations.
Example:
age = 21 # integer
name = "Amit" # string
scores = [90, 80, 70] # list
Common confusion:
- Adding a string to an integer without
conversion will raise an error.
Definition:
- Input is data you take from the user or files;
output is what your program displays or writes.
Key characteristics:
- Use input() for user input
- Use print() to display output
- Format output for readability
Example:
name = input("Enter your name:
")
print(f"Hello, {name}!")
Common confusion:
- Input is always read as a string; convert it
if needed (int(input())).
Concept E: Functions
Definition:
- Functions are reusable blocks of code that
perform a specific task.
Key characteristics:
- Defined using def
- Can accept parameters and return values
- Modularizes your code
Example:
def greet(name):
return f"Hello, {name}!"
print(greet("Amit"))
Common confusion:
- Forgetting return will return None by default.
Concept F: CLI Usage (Command Line
Interface)
Definition:
- CLI allows running Python scripts from the
terminal instead of an IDE.
Key characteristics:
- Navigate directories using cd
- Run scripts using python script.py
- Pass arguments using sys.argv
Example:
python myscript.py arg1 arg2
Common confusion:
- File paths must be correct; otherwise, Python
cannot find your script.
Concept G: Debugging
Definition:
Debugging is the
process of identifying and fixing errors in your code.
Key characteristics:
- Use print() statements to trace values
- Use debugging tools like pdb or IDE debugger
- Understand error messages and stack traces
Example:
age = "21"
print(int(age) + 5)
Common confusion:
- Type errors are common when converting data
types incorrectly.
Concept H: Working with Files
Definition:
- Reading and writing files allows persistent
storage of data.
Key characteristics:
- Open files using open()
- Use modes: r (read), w (write), a (append)
- Always close files or use with context
Example:
with open("data.txt",
"w") as f:
f.write("Hello, Python!")
Common confusion:
- Forgetting to close files can lock resources
or lose data.
Concept I: Applying Functions
Definition:
- Applying functions means using them to
automate repeated tasks or computations.
Key characteristics:
- Helps avoid code duplication
- Makes code readable and maintainable
- Functions can call other functions
Example:
def square(n):
return n * n
numbers = [2, 3, 4]
squares = [square(x) for x in numbers]
Common confusion:
- Forgetting to pass arguments correctly leads
to errors.
Concept J: Building Small
Problem-Solving Scripts
Definition:
- Combining variables, functions, file I/O, and
loops to create small applications.
Key characteristics:
- Modular approach: small, testable functions
- Reuse existing functions and scripts
- Incremental development and testing
Example:
- Build a script to count lines in a file:
def count_lines(file_path):
with open(file_path, "r") as f:
return len(f.readlines())
print(count_lines("data.txt"))
Common confusion:
- Reading large files entirely into memory may
crash the program; use loops for large files.
Seeing It in Action: Worked Examples
Example 1:
- Reading and Writing Files
# Read content from a file
with open("input.txt",
"r") as f:
data = f.read()
# Process data
lines = data.split("\n")
lines = [line.upper() for line in
lines]
# Write to a new file
with open("output.txt",
"w") as f:
f.write("\n".join(lines))
Key lesson:
- File reading and writing combined with simple
string operations can automate many tasks.
Example 2:
- Function Application
def greet_users(users):
for user in users:
print(f"Hello, {user}!")
greet_users(["Amit",
"Sneha", "Ravi"])
Key lesson:
- Functions help run repetitive tasks with
minimal code.
Example 3:
- Small Problem-Solving Script
def calculate_average(file_path):
with open(file_path, "r") as f:
numbers = [int(line) for line in f.readlines()]
return sum(numbers) / len(numbers)
print(calculate_average("numbers.txt"))
Key lesson:
- Combining file reading, type conversion,
loops, and functions allows practical automation.
Common Pitfalls and How to Avoid Them
Mistake: Forgetting to convert
input types
Solution: Always use int(),
float() as needed.
Mistake: Hardcoding file paths
Solution: Use relative paths or
os.path.join().
Mistake: Forgetting to close files
Solution: Use with context to
handle files safely.
Mistake: Writing large functions
Solution: Break down into smaller
reusable functions.
Your Turn:
- Practice & Self-Assessment
- Practice Task: Build a Python script that:
- Reads a text file
- Counts the frequency of each word
- Writes the top 5 most common words to another
file
Hint: Use
dictionaries and functions. Test on a small file first.
Consolidation: Key Takeaways & Next
Steps
Key Points:
- Variables store data; functions automate
tasks.
- Virtualenv isolates project dependencies.
- Files let you persist data; CLI lets you run
scripts efficiently.
- Debugging helps identify and fix errors
quickly.
- Mental Model: Python basics are building
blocks. Combining them lets you automate, solve problems, and build small
applications.
Next Steps:
- Practice building small scripts daily
- Explore Python libraries like os and sys for
file and system operations
- Gradually move to more advanced topics like classes and modules