Python Primer - A Self Study Approach by Bibek Bhandari
Python Primer - A Self Study Approach by Bibek Bhandari
PRIMER
A SELF-STUDY APPROACH
Bibek Bhandari
Zenitha Chalise
About Authors
Meet the authors of " Python Primer: A Self Study Approach" - Bibek
Bhandari and Zenitha Chalise.
Both are high school graduates with a shared passion for computer science
and programming. As self-taught programmers, they have dedicated
themselves to mastering the intricacies of various programming languages.
Key Highlights:
' Python Primer' is more than a book; it's a self-study companion designed
for exploration, creativity, and project-based learning. Perfect for high
school students in Nepal and beyond, eager to delve into the exciting areas
of Python programming.
Content
Introduction --------------------------------- 1
Conclusion ----------------------------------- 90
Introduction
data
analysis,
artificial
2
Community Support: Join a vibrant and supportive community of
developers ready to share knowledge, answer questions, and collaborate,
fostering an ideal environment for learning and growth.
How to Use This Book This book is structured around projects, which
means you'll be learning by doing.
Before we dive into coding, let's set up your Python environment. In this
book, we'll be using Python 3.11. You can download it from the official
Python
website
(python.org).
Additionally, you'll need a text editor or integrated development
environment (IDE) to write and run your Python code. There are many
options available, but some popular choices include Visual Studio Code,
PyCharm, and Jupyter Notebook.
For Windows, make sure to check the box that says " Add Python X.Y to
PATH" during installation. This will make it easier to run Python from the
command line.
After the installation is complete, you can verify if Python was installed
correctly: Open a command prompt (Windows) or terminal (macOS,
Linux).
In this chapter, you will take your first steps into the world of Python
programming by writing a simple program that prints the phrase "Hello,
World!" to the console. This is a common starting point for beginners in
programming and serves as a basic introduction to the syntax of the Python
language.
2. Creating a New File: Open your chosen text editor or IDE and create a
new file. This will be where you write your Python code.
# symbol and are ignored by the Python interpreter. They are used to add
explanations or notes to the code for human readers.
The line print("Hello, World!") is the core of our program. It uses the print()
function to display the text "Hello, World!" on the console.
Saving the File: Save the file with a .py extension. For example, you can
name it hello_world.py.
10
Executing the Program: Type python hello_world.py and press Enter. This
command tells the Python interpreter to run the hello_world.py file.
Key Takeaways
Python programs are written in plain text files with a .py extension.
11
12
In this section, we will explore the concept of variables and data types in
Python. Variables are used to store and manipulate data, while data types
define the type of data that can be stored in a variable.
Variables
Examples:
13
Data Types
Python has several built-in data types, including: 1. Numeric Types: int:
Integer numbers (e.g., 5, -3, 0).
2. String:
Represents text and is enclosed in single (' ') or double (" ") quotes (e.g.,
"Hello", 'Python').
3. Boolean:
4. List:
5. Tuple:
14
6. Dictionary:
7. Set:
{1, 2, 3}).
You can use the type() function to check the data type of a variable:
15
Key Takeaways
Variables are used to store data.
Python has various data types, including numeric types, strings, booleans,
lists, tuples, dictionaries, and sets.
You can use the type() function to determine the data type of a variable.
16
In this project, you will apply what you've learned about variables and basic
operations to create a simple calculator program. This program will be able
to perform addition, subtraction,
multiplication,
and
division
Use the input() function to prompt the user for two numbers and the
operation they want to perform.
Since input() returns a string, you'll need to convert the user input to
numeric values using int() or float().
Performing Operations:
Based on the user's chosen operation, use conditional statements (if, elif,
else) to perform the appropriate calculation.
17
Displaying the Result:
Example code:
18
Running the calculator
3.Run
the
program
using
python
simple_calculator.py.
When you run the program, it will prompt you to enter two numbers and the
operation you want to perform.
For example:
The program will calculate the result (10 * 5 = 50) and display it.
Key takeaways
19
Chapter 2: Making Decisions
Using Conditional Statements (if, else) Introduction
The if Statement
20
The elif Statement
Nested if Statements
You can also nest if statements inside each other to handle more complex
scenarios.
21
Conditional statements (if, else, elif) allow your program to make decisions
based on conditions.
22
You can import the random module at the beginning of your code.
23
Use conditional statements (if, elif, else) to compare the player's guess with
the secret number and provide feedback.
Repeat the Process:
You can use a loop (e.g., while) to allow the player to keep guessing until
they guess the correct number or run out of tries.
24
Use a variable to keep track of the number of tries the player has made and
display it in the game.
End the game when the player guesses the correct number or exceeds the
maximum number of tries.
Example Code
Running the Number Guessing Game Save the code in a .py file (e.g.,
number_guessing_game.py).
Run
the
program
using
python
number_guessing_game.py.
The game will prompt you to guess the number, provide feedback, and keep
track of your attempts until you guess the correct number.
Key Takeaways
26
Chapter 3: Loops and
Iteration
The for loop is used to iterate over a sequence (such as a list or a range of
numbers) and execute a block of code for each item in the sequence.
27
continue: Used to skip the current iteration and move to the next one.
28
Key Takeaways
The while loop is used for repeating code as long as a condition is true.
29
Project: Generating a Fibonacci
Sequence
Introduction
In this project, you will apply your knowledge of loops to generate a
Fibonacci sequence. The Fibonacci sequence is a series of numbers where
each number is the sum of the two preceding ones.
Prompt the user to enter the number of terms they want in the Fibonacci
sequence.
Initialize Variables:
Set initial values for the first two terms of the sequence (first_term and
second_term).
30
Generate the Sequence:
Use a for loop to generate the desired number of terms in the sequence
Example code
31
Running the Fibonacci Sequence Generator: Save the code in a .py file
(e.g., fibonacci_sequence.py).
Run
the
program
using
python
fibonacci_sequence.py.
The program will prompt you to enter the number of terms you want in the
Fibonacci sequence and then generate and display the sequence.
Key Takeaways
32
Chapter 4: Lists and
Dictionaries
Creating Lists
[].
Accessing Elements
You can access individual elements of a list using their index. The index
starts at 0 for the first element.
21 33
Modifying Lists
You can change the value of an element in a list by assigning a new value to
it.
Adding Elements:
Removing Elements
34
List Operations
Concatenation: You can concatenate two or more lists using the + operator.
Key Takeaways
35
In this section, you will learn about dictionaries, which are another essential
data structure in Python. Dictionaries allow you to store data in key-value
pairs, making it easy to retrieve and manipulate information.
Creating Dictionaries
{}.
Accessing Values
You can access the value associated with a specific key in a dictionary by
using the key itself.
36
Modifying Dictionaries
You can change the value associated with a key in a dictionary by assigning
a new value to it.
Adding Entries:
Removing Entries:
37
Dictionary Methods
Key Takeaways
38
In this project, you will combine your knowledge of lists and dictionaries to
create a simple to-do list application. The program will allow users to add,
view, and remove tasks from their to-do list.
Steps to Create the To-Do List Application Initialize the To-Do List:
39
Add Task:
If the user chooses to add a task, prompt them for the task name and priority
level, and add it to the list of tasks as a dictionary.
View Tasks:
If the user chooses to view tasks, iterate through the list of tasks and display
them.
Remove Task:
If the user chooses to remove a task, prompt them for the task number and
remove it from the list.
40
If the user chooses to quit, exit the loop and end the program.
Example Code
The program will present a menu with options to add tasks, view tasks,
remove tasks, or quit.
Key Takeaways
This project combines lists and dictionaries to create a simple interactive to-
do list application.
42
Chapter 5: Functions and
Modules
Creating Functions
You can define a function using the def keyword, followed by the function
name and a set of parentheses. Optionally, you can include parameters
within the parentheses.
43
Function Parameters
They act as placeholders for values that will be provided when the function
is called.
Default Parameters
You can provide default values for parameters in a function. If a value is not
provided when calling the function, the default value will be used.
44
Key Takeaways
45
Creating Modules
A module is simply a Python file (with a .py extension) that contains code
you want to reuse in other Python programs.
Using Modules
46
Module Aliases
You can give a module an alias to make it easier to reference in your code.
You can import specific functions or variables from a module rather than
the entire module.
47
Python comes with a standard library of modules that provide a wide range
of functionality. You can use these modules without installing anything
extra.
48
Project: Building a Simple Contact Book Introduction
In this project, you'll apply the concepts of functions and modules to create
a simple contact book. This contact book will allow users to add new
contacts, view existing contacts, and search for specific contacts by name.
49
Use the Contact Module in a Program: Develop
new
Python
script
(e.g.,
contact_program.py)
to
interact
with
the
contact_book module. Import the module and use its functions to add, view,
and search for contacts.
50
Modify the script to add more contacts, view the updated contact list, and
search for different contacts to ensure the contact book functions as
intended.
Example Output
Key Takeaways
51
Chapter 6: Handling Files
Reading and Writing Text Files
Introduction
In this chapter, you will learn how to work with files in Python. Files are a
common way to store and retrieve data, and Python provides built-in
functions for reading from and writing to files.
You can open a file using the open() function. It takes two arguments: the
file path and the mode (e.g., 'r' for read, 'w' for write).
To close a file after you're done with it, you can use the close() method.
52
Reading from a File
You can use the read() method to read the entire contents of a file.
Writing to a File
You can open a file for writing using the 'w' mode. Be careful, as this will
overwrite the existing contents of the file.
53
Key Takeaways
You can use the open() function to open a file and specify the mode ('r' for
read, 'w' for write).
Use the read() method to read the entire contents of a file, or iterate over the
file line by line.
54
Project: Creating a Text File Word Counter Introduction
In this project, you will create a Python program that reads a text file,
counts the occurrences of each word, and displays the word frequencies.
Steps to Create the Text File Word Counter Reading the File:
Use the open() function to open a text file in read mode. You can specify the
file path as an argument.
Tokenization is the process of breaking the text into words or tokens. You
can use the split() method to split the content into words.
55
Counting Word Frequencies:
Iterate through the words, and for each word, update the dictionary.
56
Example Code
Here's an example code snippet to get you started: Running the Text File
Word Counter
2.Place a text file named sample.txt in the same directory as the text you
want to analyze.
4.Run
the
program
using
Python
word_counter.py.
57
The program will read the text from sample.txt, count the word frequencies,
and display the results.
Key Takeaways
This project combines file handling, text processing, and dictionary usage.
58
Chapter 7: Introduction to
Classes
Creating a Class
You can define a class using the class keyword, followed by the class name.
Inside the class, you can define attributes (variables) and methods
(functions).
59
Once you have a class, you can create objects (instances) of that class. This
allows you to work with specific data associated with each instance.
Class Attributes vs. Instance Attributes Class attributes are shared among
all instances of a class.
60
Key Takeaways
Classes are blueprints for creating objects with specific attributes and
behaviors.
Objects (instances) are created from classes and allow you to work with
specific data.
Class attributes are shared among all instances, while instance attributes are
specific to each instance.
61
Steps to Create the Bank Account System Define the Account Class:
owner_name,
and
balance.
62
Display Account Information:
Create instances of the Account class and use the methods to perform
operations like depositing, withdrawing, and displaying account
information.
63
Example Code
Here's an example code snippet to get you started: Running the Bank
Account System
Key Takeaways
This project involves creating a bank account system using classes and
methods.
initializing
attributes,
and
implementing methods.
65
What is an API?
To make API requests in Python, you will use the requests library. This
library provides easy-to-use functions for sending HTTP requests and
handling responses.
66
Installing the requests Library
You can install the requests library using pip: Making a GET Request
You can access the response content using the text attribute.
You can also check the status code to see if the request was successful.
67
Key Takeaways
APIs allow different software applications to communicate with each other.
68
In this project, you will apply your knowledge of making API requests to
fetch data from a public API. You will use Python to retrieve information
from an external source and process the data as needed.
Find a public API that provides data you are interested in. There are various
public APIs available, such as weather data, news articles, or financial
information.
Use the requests library to make an API request to the chosen API. Specify
the API endpoint and any required parameters.
69
Handling the Response:
Process the API response. Depending on the API, the data may be in JSON,
XML, or another format. Use appropriate methods to extract and display the
information you need.
70
Example Code
The program will fetch data from the chosen API and display the
information to the user.
71
Key Takeaways
This project involves making API requests to fetch data from a public API.
72
Web scraping can be used for various purposes, including data collection,
market research, competitive analysis, and more.
73
Always check for a website's robots.txt file, which provides guidelines for
web crawlers.
Beautiful Soup: A library for parsing HTML and XML documents, making
it easy to extract data.
Requests: Used for making HTTP requests to fetch the HTML content of
web pages.
Selenium: A browser automation tool that can be used for dynamic web
scraping.
74
Use the requests library to send a GET request to the URL of the web page
you want to scrape.
Use a parsing library like Beautiful Soup to parse the HTML content and
navigate the DOM tree.
Extract Data:
Use Beautiful Soup to find and extract the specific elements or data you're
interested in.
75
Store or Process Data:
Once you've extracted the data, you can choose to store it in a file, database,
or process it further as needed.
Example Code
Key Takeaways
Python provides libraries like Beautiful Soup and Requests for web
scraping.
Web scraping should be done ethically and in compliance with website
terms of service.
77
Select a website from which you want to extract information. Identify the
specific data you're interested in.
Use your web browser's developer tools to inspect the HTML structure of
the page. Identify the HTML
78
Write the Web Scraper:
Use Python along with the Requests and Beautiful Soup libraries to build
the web scraper. Fetch the HTML content, parse it, and extract the desired
information.
Once you've extracted the data, you can process it further as needed. This
could involve cleaning, organizing, or storing the information.
79
Example Code
5.Run
the
program
using
python
web_scraper.py.
80
The program will fetch the HTML content, extract the specified information,
and save it to a file.
Key Takeaways
81
In this chapter, you will learn how to create basic data visualizations using
the Matplotlib library in Python. Data visualization is a powerful tool for
understanding and presenting data in a visual format, such as charts and
graphs.
What is Matplotlib?
Matplotlib can be used for simple line plots, bar charts, scatter plots, and
more.
82
Installing Matplotlib
You can install Matplotlib using pip: Creating a Simple Line Plot
A bar chart is used to represent data with rectangular bars. You can create a
bar chart using the bar() function.
83
Creating a Scatter Plot
Customizing Plots
84
Key Takeaways
You can create various types of plots, such as line plots, bar charts, and
scatter plots, to visualize your data.
85
Project: Plotting Data from a CSV File Introduction
In this project, you will use Python and Matplotlib to read data from a CSV
file and create visualizations.
CSV (Comma Separated Values) files are a common format for storing
tabular data. This project will help you practice reading data from files and
creating meaningful visualizations.
Use the csv module to open and read the data from the CSV file.
86
Extract Data for Plotting:
Separate the data into appropriate lists or arrays for plotting. Depending on
the content of the CSV
Use Matplotlib to create the desired plot, such as a line plot, bar chart, or
scatter plot.
Add titles, labels, legends, and customize the appearance of the plot as
needed.
87
Display or Save the Plot:
Example Code
88
Running the Project 1.Prepare a CSV file (data.csv) with suitable data for
plotting.
2.Save the code in a .py file (e.g., csv_plotter.py) in the same directory as
the CSV file.
The program will read the data from the CSV file and create a plot based on
the specified visualization.
Key Takeaways
This project involves reading data from a CSV file and creating
visualizations using Matplotlib.
89
Conclusion
In Chapt er -2
In Chapt er -3
You learned about loops, both for and while, to perform repetitive tasks.
In Chapt er -4
You studied data structures like lists and dictionaries to organize and
manage data.
In Chapt er -5
You delved into defining and calling functions to modularize your code.
You organized code into modules and built a Simple Contact Book.
In Chapt er -6
You learned how to read and write text files, and the importance of context
managers (with statements).
In Chapt er -7
You understood the concept of classes and objects, and how they
encapsulate data and behavior.
91
In Chapt er -8
You discovered how to make API requests in Python using the requests
library.
In Chapt er -9
You learned about web scraping and how to extract information from
websites.
In Chapt er -10
92
Now that you have a solid foundation in Python, here are some next steps
and resources for further learning:
programming,
algorithms,
data
93
Books: There are many excellent Python books available that cover a wide
range of topics and expertise levels.
Community and Forums: Join Python forums and communities like Stack
Overflow, Reddit's r/learnpython, and Python's official forum for asking
questions and getting help.
94
of
classes,
inheritance,
Projects:
Data Analysis and Visualization: Use Pandas for data manipulation and
Matplotlib or Seaborn for creating insightful visualizations.
Books: There are many excellent Python books available, covering a wide
range of topics and expertise levels.
to reach out at
building!
Happy Coding!