EnableGeek Python Beginner to Advanced Free Edition
EnableGeek Python Beginner to Advanced Free Edition
Guide
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the publisher,
except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure accuracy of the
information presented. However, the information contained in this book is sold without
warranty , either express or implied. Neither the author, nor Enablegeek or its dealers and
distributors, will be held liable for any damages caused or alleged to have been caused directly
or indirectly by this book.
Enablegeek has endeavored to provide trademark information about all of the companies and
products mentioned in this book by the appropriate use of capitals. However, Enablegeek
cannot guarantee the accuracy of this information.
Chapter 1 9
____________________________________________________________________________
2
Introduction to Python 9
1.1 History of Python 10
1.1.1 Creation and Early Years (The late 1980s - Early 1990s) 10
1.1.2 Python 2 and Python 3 Split (2008) 10
1.1.3 Growth and Popularity 10
1.1.4 Continuous Development and Version Releases 11
1.2 Features of Python 11
Chapter 2 12
Local Environment Setup 12
2.1 Installation of Python 12
2.1.1 Linux (Debian, Ubuntu, Linuxmint, etc) or macOS 13
2.1.2 Mind it Carefully 15
2.1.3 Install Python on Windows 15
2.2 Python Interpreter 16
Chapter 3 17
Working with Python: Understanding the Basic Syntax 17
3.1 Introduction 17
3.2 Python Syntax Overview 17
3.2.1 Statements and Indentation 17
3.2.2 Variables and Data Types 18
3.2.3 Comments 18
3.2.4 Print Statements 18
3.2.5 Lists 19
3.2.6 Dictionaries 19
3.3 Control Flow Statements 20
3.3.1 Conditional Statements (if, elif, else) 20
3.3.2 Looping Statements (for, while) 20
3.3.3 Input from the user 21
3.3.4 Arithmetic operators 21
3.4 Functions and Modules 22
3.4.1 Functions 22
3.4.2 Modules 22
3.4.3 Exception Handling 23
Chapter 4 25
Python Basic: Python Variable and Data Types 25
4.1 Introduction 25
4.2 Python Variables 26
4.3 Python Data Types 28
4.3.1 Numeric Types 28
4.3.2 String Type 29
4.3.3 Boolean Type 29
____________________________________________________________________________
3
4.3.4 Sequence Types 29
4.3.5 Mapping Type 30
4.3.6 Set Types 30
4.3.7 None Type 31
4.4 Exercise Problem: 1 31
Chapter 5 33
Python Operators: A Comprehensive Overview 33
5.1 Introduction 33
5.2 Arithmetic Operators 33
5.3 Assignment Operators 34
5.4 Comparison Operators 35
5.5 Logical Operators 35
5.6 Bitwise Operators 36
5.7 Membership Operators 36
5.8 Identity Operators 37
5.9 Exercise Problem: 2 37
Chapter 6 39
Conditional Statements in Python: A Comprehensive Guide 39
6.1 Introduction 39
6.2 if Statement 39
6.3 if-else Statement 40
6.4 Nested if-else Statement 41
Chapter 7 44
Complete Guide to Looping in Python: Exploring For, While, and Nested Loops 44
7.1 Introduction 44
7.2 Python for Loop 44
7.3 Python while Loop 45
7.4 Python Nested Loops 46
7.5 Some Examples of Python Loops 47
7.5.1 The sum of the first N numbers by using for loop 47
7.5.2 A sum of first N numbers using a while loop 47
Chapter 8 50
Control Statements in Python: Exploring Break, Continue, and Pass 50
8.1 Introduction 50
8.2 The break Statement 50
8.3 The Continue Statement 51
8.4 The pass Statement 51
Chapter 9 53
Mastering String Manipulation in Python: An Extensive Exploration 53
9.1 Introduction to Strings 53
9.1.1 Accessing Strings 53
____________________________________________________________________________
4
9.1.2 Basic Operations 53
9.1.3 String Slices 54
9.1.4 String Functions and Methods 55
9.2 Formatted String 55
9.2.1 Variable Interpolation 56
9.2.2 Expression Evaluation 56
9.2.3 Formatting Options 57
Chapter 10 58
Python Lists: A Comprehensive Guide to Working with Lists 58
10.1 Introduction 58
10.1.1 Accessing Lists 58
10.1.2 List Operations 59
10.1.3 List Functions and Methods 60
10.2 Working with Lists 60
10.2.1 Counting the Frequency of Elements in a List 61
10.2.1.1 Iterative Method 61
Chapter 11 62
Python Tuples: A Comprehensive Guide to Working with Tuples 62
11.1 Introduction 62
11.1.1 Accessing Tuples 62
Operations 62
11.1.2 Functions and Methods of Tuples 63
11.1.3 Working with Tuples 64
11.2 Data Aggregation from a Tuple 64
11.2.1 Total Sales Quantity 65
11.2.2 Sales by Product 65
11.2.3 Maximum Sales Quantity 66
Chapter 12 67
Python Dictionaries: A Comprehensive Guide to Working with Dictionaries 67
12.1 Introduction 67
12.1.1 Accessing values in dictionaries 67
12.1.2 Adding and Modifying Values 68
12.1.3 Removing Key-Value Pairs 68
12.1.4 Properties of Dictionaries 69
12.1.5 Dictionary Functions 69
12.1.6 Storing User Information 70
12.2 Working with dictionaries 70
12.2.1 Counting Word Frequencies in Text 70
12.2.2 Counting Word Frequencies in a List 71
Chapter 13 72
Functions in Python: A Comprehensive Guide 72
____________________________________________________________________________
5
13.1 Introduction 72
13.1.1 Defining a function 72
13.1.2 Calling a function 73
13.1.3 Types of functions 73
13.1.4 Function Arguments 73
13.1.5 Anonymous functions 74
13.2 Global and local variables 74
13.2.1 Global Variables 74
13.2.2 Local Variables 75
13.2.3 Accessing Global Variables within a Function 75
13.2.4 Shadowing and Local Variables 76
13.2.5 Best Practices and Considerations 76
13.2.6 Fibonacci Series 77
13.2.7 Factorial Function 77
Chapter 14 78
File and Exception Handling in Python: A Comprehensive Guide 78
14.1 Introduction 78
14.1.1 File Handling 78
14.1.2 Input and Output 78
14.1.3 Errors and Exceptions 79
14.1.4 Debugging 79
14.1.5 Exception Handling 79
14.1.6 File Handling Operations 79
14.1.7 Best Practices 80
14.2 Here are various examples of file handling in Python, along with explanations 80
14.2.1 Example 1: Reading from a File 80
14.2.2 Example 2: Writing to a File 80
14.2.3 Example 3: Appending to a File 81
14.2.4 Example 4: Reading Line by Line 81
14.3 Here are various examples of exception handling in Python, along with explanations 82
14.3.1 Example 1: Handling a Specific Exception 82
14.3.2 Example 2: Handling Multiple Exceptions 82
14.3.3 Example 3: Handling Exceptions with Finally Block 83
14.3.4 Example 4: Asynchronous Task with Exception Handling 83
Chapter 15 85
Python Object-Oriented Programming (OOPS): A Comprehensive Guide 85
15.1 Introduction 85
15.1.1 Class and Object 85
15.1.2 Attributes 86
15.1.3 Methods 87
15.1.4 Overloading 87
____________________________________________________________________________
6
15.1.5 Overriding 88
15.1.6 Data Hiding 89
Chapter 16 90
Inheritance in Python: Exploring Types and Relationships 90
16.1 Introduction 90
16.1.1 Single Inheritance 90
16.1.2 Multilevel Inheritance 91
16.1.3 Multiple Inheritance 91
16.1.4 Hybrid Inheritance 92
16.1.5 Hierarchical Inheritance 93
16.2 IS-A Relationship and HAS-A Relationship 93
16.2.1 IS-A Relationship 94
16.2.2 HAS-A Relationship 94
Chapter 17 96
Polymorphism in Python: Exploring Dynamic and Versatile Behavior 96
17.1 Introduction 96
17.2 Duck Typing Philosophy 96
17.3 Method Overloading 96
17.4 Operator Overloading 97
17.5 Constructor Overloading 98
17.6 Method Overriding 98
17.7 Constructor Overriding 99
Chapter 18 101
Exploring Python Features: Regular Expressions, Modules, Networking, Multithreading,
Concurrency, and Databases 101
18.1 Introduction 101
18.1.1 Regular Expressions 101
18.1.2 Modules 101
18.1.3 Networking 102
18.1.4 Multithreading 102
18.1.5 Concurrency 102
18.1.6 Databases 103
18.2 Applications of Python Features 103
18.2.1 Regular Expressions 103
18.2.2 Modules 104
18.2.3 Networking 104
18.2.4 Multithreading 105
18.2.5 Concurrency 106
18.2.6 Databases 107
Chapter 19 108
Comprehensive Guide to Python Database Handling: From Connections to Error
____________________________________________________________________________
7
Handling 108
19.1 Introduction to Python with SQL 109
19.1.1 Connections 109
19.1.2 Executing Queries 109
19.1.3 Transactions 110
19.1.4 Handling Errors 111
19.2 Introduction to Python with No-SQL 111
19.2.1 Getting Started with MongoDB 111
19.2.2 CRUD Operations with Python and MongoDB 112
19.2.3 Querying and Aggregation 112
19.2.4 Indexing and Performance Optimization 112
19.2.5 Working with Geospatial Data 112
19.2.6 Aggregating Data with Map-Reduce 112
19.2.7 Integrating Python Frameworks with MongoDB 112
19.2.8 Real-world Examples and Best Practices 113
19.3 MongoDB with Python 113
19.3.1 Install pymongo 113
19.3.2 Connecting to MongoDB 113
19.3.3 Inserting a Document 114
19.3.4 Querying Documents 114
19.3.5 Updating a Document 114
19.3.6 Deleting Documents 115
Chapter 20 115
Python Networking Essentials: Navigating the World of Network Communication 115
20.1 Introduction to Networking in Python 115
20.1.1 Socket 116
20.1.2 Socket Module 116
20.1.3 Methods 116
20.1.4 Client and server 117
20.1.5 Internet modules 117
20.2 Applications of Python Networking 118
20.2.1 Socket Programming with Python: 118
20.2.2 Uses of Socket Module in Python: 119
20.2.3 Socket Methods in Python 120
20.3 Client and server 122
20.3.1 Implementation of Server code 122
20.3.2 Implementation of Client code 123
20.3.3 Internet modules in Python 124
Chapter 21 125
Mastering Multithreading in Python: From Introduction to Advanced Techniques 125
21.1 Introduction to Multithreading 126
____________________________________________________________________________
8
21.1.1 Introduction to Multitasking 126
21.1.2 isAlive Method 126
21.1.3 Enumerate Function 126
21.1.4 Thread Class 126
21.1.5 Demonstrating Multithreading 126
21.1.6 Running Parallel Programs 127
21.1.7 Operating Based Multithreading 127
21.2 Applications of the Multithreading in Python 127
21.2.1 Sample of Multithreading 127
21.2.2 Sample of Multitasking 129
21.2.3 Sample of isAlive Method 130
21.2.4 Sample of Enumerate Function 131
21.2.5 Thread Class 132
21.3 Demonstrating Multithreading: 133
21.3.1 Running Parallel Programs 134
21.3.1 Operating-Based Multithreading 136
Chapter 22 139
Introduction to Django 139
22.1 What Is a Web Framework? 140
22.2 The MVC Design Pattern 141
22.3 Django’s History 143
22.4 How to Read This Book 144
22.4.1 Required Programming Knowledge 144
22.4.2 Required Python Knowledge 145
22.4.3 New Django Features 145
22.4.4 Getting Help 146
Chapter 23 146
Getting Started with Django Framework 146
23.1 Installing Python 146
23.2 Installing Django 147
23.3 Setting Up a Database 147
23.3.1 Using Django with PostgreSQL 148
23.3.2 Using Django with SQLite 3 148
23.3.3 Using Django with MySQL 149
23.3.4 Using Django Without a Database 149
23.4 Starting a Project 149
23.4.1 The Development Server 150
23.5 What’s Next? 151
Chapter: 24 151
The Basics of Dynamic Web Pages 151
____________________________________________________________________________
9
24.1 Your First View: Dynamic Content 152
24.2 Mapping URLs to Views 153
24.3 Mapping URLs to Views 156
24.3.1 Regular Expressions 156
24.4 How Django Processes a Request 157
24.4.1 How Django Processes a Request: Complete Details 157
24.5 URLconfs and Loose Coupling 159
24.6 Exception 404 Errors 159
24.7 Your Second View: Dynamic URLs 160
24.7.1 A Word About Pretty URLs 161
24.7.2 Wildcard URLpatterns 161
24.7.3 Your Second View: Dynamic URLs 162
24.7.4 Coding Order 163
24.8 Django’s Pretty Error Pages 165
24.9 What’s next? 166
Chapter: 25 166
The Django Template System 166
25.1 Template System Basics 167
25.2 Using the Template System 168
25.2.1 Creating Template Objects 169
25.2.2 Template System Basics 169
25.2.3 Rendering a Template 170
25.2.4 Multiple Contexts, Same Template 172
25.2.5 Context Variable Lookup 173
25.2.6 Method Call Behavior 175
25.2.7 How Invalid Variables Are Handled 177
25.2.8 Playing with Context Objects 177
25.3 Basic Template Tags and Filters 178
25.3.1 Tags 178
25.3.2 for 180
25.3.3 ifequal/ifnotequal 182
25.3.4 Comments 183
25.3.5 Filters 183
25.4 Philosophies and Limitations 184
25.5 Using Templates in Views 185
25.5.1 Template Loading 187
25.5.2 render_to_response() 190
25.5.3 The locals() Trick 190
25.5.4 Subdirectories in get_template() 191
25.5.5 The include Template Tag 191
25.6 Template Inheritance 192
____________________________________________________________________________
10
25.7 What’s next? 196
Chapter: 26 196
Interacting with a Database: Models 196
26.1 The “Dumb” Way to Do Database Queries in Views 197
26.2 The MTV Development Pattern 198
26.3 Configuring the Database 199
26.4 Your First App 201
26.5 Defining Models in Python 202
26.7 Installing the Model 205
26.8 Basic Data Access 208
26.9 Adding Model String Representations 209
26.10 Inserting and Updating Data 210
26.11 Selecting Objects 211
26.11.1 Filtering Data 212
26.11.2 Retrieving Single Objects 213
26.11.3 Ordering Data 213
26.11.4 Chaining Lookups 214
26.11.5 Slicing Data 215
26.12 Deleting Objects 215
26.13 Making Changes to a Database Schema 216
26.13.1 Adding Fields 216
26.13.2 Removing Fields 218
26.13.3 Removing Many-to-Many Fields 219
26.13.4 Removing Models 219
Chapter 27 221
Introduction to Flask 221
27.1 Installation 221
27.1.1 Creating the Application Directory 222
27.1.2 Virtual Environments 222
27.1.3 Creating a Virtual Environment with Python 3 223
27.1.4 Creating a Virtual Environment with Python 2 223
27.1.5 Working with a Virtual Environment 224
27.1.6 Installing Python Packages with pip 225
Chapter 28 226
Basic Application Structure 226
28.1 Initialization 226
28.2 Routes and View Functions 226
28.3 A Complete Application 228
28.4.Development Web Server 228
28.5 Dynamic Routes 230
28.6 Debug Mode 230
____________________________________________________________________________
11
28.7 WARNING 231
28.8 Command-Line Options 231
28.9 Runs a local development server for the Flask application. 232
28.10 The Request-Response Cycle 233
28.10.1 Application and Request Contexts 233
28.10.2 Request Dispatching 235
28.10.3 The Request Object 235
28.11.3 Attribute or Method Description 235
28.12 Request Hooks 236
28.13 Responses 237
28.14 Flask Extensions 239
Chapter 29 240
Templates 240
29.1 The Jinja2 Template Engine 240
29.2 Rendering Templates 241
29.3 Variables 242
29.4 Filter name Description 242
29.4.1 CAUTION 242
29.5 Control Structures 243
29.6 Bootstrap Integration with Flask-Bootstrap 245
29.7 Block name Description 247
29.8 Custom Error Pages 248
29.9 Links 250
29.10 Static Files 251
29.11 Localization of Dates and Times with Flask Moment 252
29.12 Configuration 255
29.13 Form Classes 256
29.14 Field type Description 257
29.15 Validator Description 257
29.16 HTML Rendering of Forms 258
29.17 Form Handling in View Functions 259
29.18 Redirects and User Sessions 261
29.19 Message Flashing 263
Chapter 30 265
Databases 265
30.1 SQL Databases 265
30.2 NoSQL Databases 266
30.3 SQL or NoSQL? 266
30.4 Python Database Frameworks 267
30.5 Performance 267
____________________________________________________________________________
12
____________________________________________________________________________
13
Chapter 1
Introduction to Python
____________________________________________________________________________
____________________________________________________________________________
Python is a high-level, general-purpose programming language known for its simplicity and
readability. It was created by Guido van Rossum and first released in 1991. Python's design
philosophy emphasizes code readability and clean syntax, which makes it easy to understand
and write.
Python is widely used in various domains, including web development, data analysis, artificial
intelligence, scientific computing, and automation. Its versatility and extensive library ecosystem
make it a popular choice for developers, whether beginners or experienced professionals.
One of Python's key strengths is its simplicity. Its syntax is designed to be clear and concise,
utilizing indentation rather than braces or keywords for code blocks. This readability encourages
the use of good coding practices and helps maintainability and collaboration in projects.
Python has an extensive standard library that provides ready-to-use modules and packages for
a wide range of tasks, such as file I/O, networking, database access, and more. Additionally,
Python's package management system, called pip, allows users to easily install and manage
third-party libraries, further expanding its capabilities.
Python's interpreted nature means that developers can write and run code without the need for
compilation, making it highly interactive and suitable for rapid prototyping and development. Its
cross-platform compatibility allows Python programs to run on various operating systems,
including Windows, macOS, and Linux.
Moreover, Python has a thriving and supportive community. Developers around the world
actively contribute to its development, create open-source libraries, and provide extensive
documentation and resources. This community-driven approach fosters collaboration,
knowledge sharing, and continuous improvement of the language.
In summary, Python is a versatile and beginner-friendly programming language known for its
simplicity, readability, and extensive library support. Its popularity spans various industries and
use cases, making it a powerful tool for developers of all levels of expertise.
____________________________________________________________________________
14
1.1 History of Python
Python, a widely used programming language, has a rich history that dates back to the late
1980s. Here is a brief overview of its key milestones and developments:
1.1.1 Creation and Early Years (The late 1980s - Early 1990s)
Python was conceived by Guido van Rossum, a Dutch programmer, in December 1989. He
aimed to develop a successor to the ABC programming language that would be easy to learn
and readable.
Guido started working on Python as a hobby project during the Christmas holidays in 1989. He
named it after the British comedy series "Monty Python's Flying Circus" as a tribute to his love
for the show.
The first implementation of Python, Python 0.9.0, was released in February 1991, and it
included key language features like classes with inheritance, exception handling, and core data
types.
As Python gained popularity, the language evolved with new features and improvements. In
2000, Python 2.0 was released, introducing list comprehensions, a garbage collector, and
Unicode support.
However, Python 2 had backward compatibility issues with certain features, which led to the
development of Python 3.0. Python 3.0 was released in 2008, addressing design flaws and
introducing significant changes incompatible with Python 2.
Python's simplicity, readability, and versatility led to its growing adoption across different
domains, including web development, scientific computing, data analysis, machine learning, and
automation.
The Python Software Foundation (PSF) was established in 2001 as a non-profit organization to
promote and support the Python programming language. PSF played a crucial role in the
language's growth and community development.
____________________________________________________________________________
15
1.1.4 Continuous Development and Version Releases
After the release of Python 3, the Python community followed a "Python 2.7 maintenance mode"
approach, providing bug fixes and security patches for Python 2. However, new features and
improvements were focused on Python 3.
Python has followed a regular release schedule, with major releases occurring approximately
every 18-24 months. Each release introduces enhancements, optimizations, and new features
to improve the language and its ecosystem.
Today, Python enjoys widespread popularity and has a vibrant community of developers. It is
continually evolving, with regular updates and contributions from developers worldwide.
Python's success can be attributed to its simplicity, readability, extensive library ecosystem, and
the dedication of its community to creating a versatile and powerful programming language.
2. Extensive Standard Library: Python comes with a vast standard library that provides
modules and packages for a wide range of functionalities. It includes modules for file I/O,
networking, database access, data manipulation, web development, and much more.
The standard library reduces the need for external dependencies and makes Python a
powerful and comprehensive language.
____________________________________________________________________________
16
6. Large and Active Community: Python has a vibrant and supportive community of
developers worldwide. The community actively contributes to the language's
development, creates third-party libraries, and provides extensive documentation and
resources. This thriving community fosters collaboration, knowledge sharing, and
continuous improvement.
Python's introduction, historical background, and notable features collectively demonstrate its
strengths as a versatile and beginner-friendly programming language. Its simplicity, extensive
library support, cross-platform compatibility, and strong community make it a popular choice for
various applications, from web development to data science and automation.
____________________________________________________________________________
17
Chapter 2
Local Environment Setup
____________________________________________________________________________
____________________________________________________________________________
If you are a Linux or Mac user, you already have Python on your computer. As of the writing of
this course (May 2022), Python 2.7.x is the default version of Python built-in with these two
major operating systems. However, this course is based on Python 3.9.x. In fact, versions of
Python 2 and 3 have a number of intermediate changes in syntax and features. Python's official
site is currently the focus of Python 3X, and they have made it clear that Python's current and
future is Python 3.
Below we will learn about the steps for installing the latest version of Python 3 on some major
operating systems. As mentioned earlier, Linux or Mac has two versions of Python built-in. So to
start this Python interpreter directly, you need to open the terminal and type the command
tuhin@linuxmint:~$ python
And pressing Enter will start the Python 2 interpreter. But since we will not work with this
version, we will focus on the latest version installation below.
The latest version of Ubuntu also has Python 3 installed (eg: Python 3.8.10) but not set by
default. To launch this version of the interpreter you should type python3 into the terminal and
press Enter.
The two pythons have different binary save names and their paths can also be seen.
Issuing the command which python and which python3 commands in the terminal will
____________________________________________________________________________
18
show /usr/bin/python and /usr/local/bin/python3 respectively. That means the default
Python and Python 3.4 paths are different.
However, if we want to install the latest version, we need to download the Gzipped source
tarball of Python-3.11.4 directly from Python-3.11.4 to this link and extract it. This will create a
folder named Python-3.11.4 on the computer.
Now, open the terminal and go to the location of that folder using cd (Change Directory)
command.
Step 1:
(base) ➜ ~ sudo apt install build-essential
Step 2:
(base) ➜ ~ cd ~/Downloads/Python-3.11.4
Step 3:
Then you have to run the following command,
(base) ➜ ~ ./configure
Step 4:
Now run the following command,
(base) ➜ ~ make
Step 5:
Then, run this to install
When all is well, open the terminal and run the command,
(base) ➜ ~ python3
____________________________________________________________________________
19
The output will be as follows
(base) ➜ ~ python3
Python 3.11.4 (main, Aug 25, 2022, 23:26:10)
[GCC 11.2.0] :: Inc. on Linux
Type "help", "copyright", "credits" or "license" for more
information.
>>>
This means that the Python 3.11.4 console or REPL has been launched.
To find out the location of this new python which python3 command you can see which output
can show the path /usr/local/bin/python3
If it is not installed in the above method, then run the following command and follow all the
above steps again.
However, these minor complications can be solved by creating a virtual environment which will
be discussed at the end of the course.
20
1. Go to the official Python website at Python.org and click the “Download Python” button.
2. Choose the appropriate version of Python (Python 3 is recommended) and click on the
corresponding installer link.
3. After the installer file downloads, run it to start the Python installation process.
4. Follow the prompts in the installer to select the installation directory, customize the
installation, and install Python.
5. Once the installation is complete, open the Command Prompt by typing “cmd” in the
Windows search bar and pressing Enter.
6. In the Command Prompt, type “python” and press Enter to start the Python interpreter.
That’s it! You should now have Python installed on your Windows machine and be able to run
Python code from the Command Prompt.
The Python interpreter is a program that runs Python code. It reads and executes the code line
by line, and it is responsible for translating the code written by the programmer into
machine-readable instructions that the computer can execute.
2. Alternate interpreters: There are several other interpreters for Python, such as Jython
(written in Python), IronPython (written in C#), and PyPy (a faster implementation of
Python that uses JIT compilation).
1. Interactive mode: It allows you to type Python code and see the results immediately. It
is useful for experimenting with the language and testing small snippets of code.
2. Script mode: In this mode, you write your code in a file with the .py extension and then
execute that file using the interpreter.
____________________________________________________________________________
21
3. Integrated Development Environment (IDE): An IDE such as PyCharm or IDLE
provides a graphical user interface for writing and running Python code.
Python allows a user to perform interactive mode programming that involves running a program
by typing directly into the command line. To start interactive programming, call the Python
interpreter without passing the script file mentioned below:
(base) ➜ ~ python3
Python 3.11.4 (main, Aug 25, 2022, 23:26:10)
[GCC 11.2.0] :: Inc. on Linux
Type "help", "copyright", "credits" or "license" for more
information.
>>> print("Hello EnableGeek")
Hello EnableGeek
>>>
Then you will get the output in the next line as below,
>>> The sign means that the Python Interpreter is ready to take the Python statement from you
and here you can write.
The Python interpreter takes the source code, which is the code written by the developer, and
converts it into machine-readable instructions that the computer can execute. It also handles
tasks such as memory management and error handling.
____________________________________________________________________________
22
Chapter 3
Working with Python: Understanding the Basic Syntax
____________________________________________________________________________
____________________________________________________________________________
3.1 Introduction
Python is a powerful and versatile programming language known for its simplicity and
readability. To begin coding in Python, it's essential to grasp the basic syntax and understand
how to structure your code effectively. This guide will introduce you to the fundamental concepts
and syntax rules in Python.
Example:
Variables are used to store values. Python supports several data types:
age = 25 # Integer
height = 1.75 # Float
name = "John" # String
is_student = True # Boolean
print(age)
print(height)
print(name)
print(is_student)
____________________________________________________________________________
23
3.2.3 Comments
Comments are essential for documenting your code and adding explanations or notes. In
Python, comments start with the '#' symbol and are ignored by the interpreter. They provide
insights into the code's purpose and help other developers understand your code.
Example:
Comments are used to explain the code and are ignored by the interpreter. They start with the
'#' symbol.
Example:
The print() function is used to display output on the console.
3.2.5 Lists
In Python, a list is a versatile data structure that can hold an ordered collection of elements.
Lists are mutable, which means their elements can be modified. Here are some common
operations and examples related to lists in Python:
Example:
Lists are used to store multiple items in a single variable.
numbers = [1, 2, 3, 4, 5]
sub_list = numbers[1:4]
print(sub_list) # Output: [2, 3, 4]
____________________________________________________________________________
24
3.2.6 Dictionaries
In Python, a dictionary is a built-in data structure that allows you to store a collection of
key-value pairs. It is also known as an associative array or hash table. Here are some common
operations and examples related to dictionaries in Python:
Example:
Dictionaries are key-value pairs used to store data.
person = {
"name": "John",
"age": 25,
"is_student": True
}
print(person["name"]) # Output: John
Example:
Conditional statements are used to perform different actions based on different conditions. The
most common ones are if, elif, and else.
age = 18
____________________________________________________________________________
25
3.3.2 Looping Statements (for, while)
Looping statements enable you to repeat a block of code multiple times. The for loop iterates
over a sequence or collection of items, while the while loop repeats a block of code until a
specific condition is no longer true. Looping is valuable for performing repetitive tasks and
iterating through data.
Example:
Loops are used to repeat a block of code multiple times.
# For loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# While loop
count = 0
while count < 5:
print(count)
count += 1
Example:
The input() function gets user input from the console.
Example:
x = 5
y = 2
addition = x + y # 7
subtraction = x - y # 3
multiplication = x * y # 10
____________________________________________________________________________
26
division = x / y # 2.5
modulus = x % y # 1
exponentiation = x ** y # 25
floor_division = x // y # 2
3.4.1 Functions
Example:
Functions are reusable blocks of code that perform a specific task.
def greet(name):
""" Function to greet a person by name """
print("Hello, " + name + "!")
____________________________________________________________________________
27
To get the full version visit this page.
____________________________________________________________________________
28
Chapter 4
Python Basic: Python Variable and Data Types
____________________________________________________________________________
____________________________________________________________________________
4.1 Introduction
In Python, variables are the building blocks of any program. They act as containers to store and
manipulate data values. Unlike some other programming languages, Python is dynamically
typed, meaning that you don't need to explicitly declare the data type of a variable. Instead,
Python determines the type of a variable based on the value it holds at a given time. This
flexibility allows for greater ease and readability in coding.
Python provides a range of data types to handle different kinds of information. Each data type
serves a specific purpose and offers various operations and functionalities. The commonly used
data types in Python include numeric types (integers and floats), strings, booleans, sequences
(lists, tuples, and ranges), dictionaries, sets, and the special None type.
Numeric types encompass whole numbers (integers) and decimal numbers (floats), enabling
mathematical operations and calculations. Strings represent sequences of characters and are
used to store and manipulate text-based data. Booleans, with their truth values of True or False,
are fundamental for logical evaluations and control flow.
Sequences such as lists, tuples, and ranges allow you to organize and manipulate collections of
elements. Lists are mutable, meaning their elements can be modified, while tuples are
immutable and provide a way to store related data as a unit. Ranges, often used in loops,
represent a sequence of numbers.
Dictionaries are key-value pairs that facilitate efficient data retrieval and storage. They allow you
to associate values with unique keys, enabling quick access and manipulation. Sets are
unordered collections of unique elements, useful for tasks like eliminating duplicates or testing
membership.
Lastly, the None type represents the absence of a value or null value, commonly used to
indicate no return value from a function or uninitialized variables.
Understanding variables and data types is essential as they form the foundation for data
manipulation, control flow, and program structure. With these tools at your disposal, you can
create powerful programs and solve a wide range of problems in Python.
____________________________________________________________________________
29
4.2 Python Variables
Python variables are fundamental elements used to store and manipulate data within a
program. Unlike some other programming languages, Python is dynamically typed, which
means you don't need to explicitly declare the data type of a variable. Instead, Python infers the
type of a variable based on the value assigned to it. This flexibility allows for more concise and
readable code.
To create a variable in Python, you simply assign a value to it using the assignment operator (=).
Here's an example:
name = "John"
age = 25
is_student = True
In the above code, we created three variables: name, age, and is_student. The first variable,
name, is assigned a string value "John", representing a person's name. The second variable,
age, is assigned an integer value 25, representing the person's age. The third variable,
is_student, is assigned a boolean value True, indicating whether the person is a student or not.
Variables in Python can hold values of different types, and you can change the value and type of
a variable at any time.
For example:
age = 25
print(age) # Output: 25
age = "Twenty-five"
print(age) # Output: Twenty-five
In the above code, we initially assigned an integer value of 25 to the variable age. However, we
later reassigned a string value "Twenty-five" to the same variable, and Python handles this
change without any issues.
Variables in Python are case-sensitive, which means age and Age are considered as two
different variables. It's important to use consistent naming conventions to avoid confusion.
____________________________________________________________________________
30
Here are a few examples:
num1 = 10
num2 = 5
# Arithmetic operations
sum = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2
print(sum) # Output: 15
print(difference) # Output: 5
print(product) # Output: 50
print(quotient) # Output: 2.0
In the above code, we perform basic arithmetic operations using the variables num1 and num2.
The results are stored in different variables (sum, difference, product, quotient), which can be
used further in the program.
Variables are not limited to storing primitive types like numbers and strings. They can also store
more complex data structures like lists, dictionaries, or even custom objects.
Here's an example:
student = {
"name": "Alice",
"age": 20,
"grades": [85, 90, 92]
}
In this code, the variable student holds a dictionary that contains information about a student,
such as their name, age, and a list of grades. We can access specific values using the
corresponding keys.
____________________________________________________________________________
31
Variables play a crucial role in programming as they allow us to store, manipulate, and reference
data throughout the program's execution. By using meaningful variable names and
understanding their scope and lifecycle, we can write more readable and maintainable code.
In Python, data types represent the kind of values that can be stored and manipulated within a
program. Python provides a rich set of built-in data types that serve various purposes and allow
you to work with different kinds of data. Understanding and utilizing the appropriate data types is
crucial for writing effective and efficient Python programs.
Let's explore some of the key data types in Python along with examples:
● Integer (int): Represents whole numbers without decimal points. For example: 42, -10.
Numeric types allow you to perform mathematical operations like addition, subtraction,
multiplication, and division.
Here's an example:
x = 10
y = 3.5
sum = x + y
print(sum) # Output: 13.5
Here's an example:
____________________________________________________________________________
32
Strings provide various methods for manipulation, such as concatenation, slicing, and
formatting.
Example:
is_active = True
is_admin = False
For instance:
x = 5
y = 10
is_greater = x > y # False
Example:
fruits = ["apple", "banana", "orange"]
print(fruits) # Output: ["apple", "banana", "orange"]
Tuple (tuple): Tuples are similar to lists but are immutable, meaning their elements cannot be
modified once defined. Tuples are often used for grouping related data.
Example:
coordinates = (10, 20)
print(coordinates) # Output: (10, 20)
Range (range): Range represents a sequence of numbers and is commonly used in loops and
iterations.
____________________________________________________________________________
33
Example:
numbers = range(1, 5)
print(list(numbers)) # Output: [1, 2, 3, 4]
Example:
person = {
"name": "John",
"age": 25,
"city": "New York"
}
print(person["name"]) # Output: John
Example:
numbers = {1, 2, 3, 4, 5}
print(numbers) # Output: {1, 2, 3, 4, 5}
FrozenSet (frozenset): FrozenSets are immutable versions of sets. Once defined, their
elements cannot be modified.
Example:
vowels = frozenset(["a", "e", "i", "o", "u"])
print(vowels) # Output: frozenset({'o', 'u', 'a', 'i', 'e'})
____________________________________________________________________________
34
4.3.7 None Type
None (None): None represents the absence of a value or a null value. It is often used to
indicate the absence of a return value from a function or to initialize variables.
Example:
result = None
These are some of the fundamental data types in Python. Each data type comes with its own
set of operations and methods, enabling you to perform various tasks and manipulate data
effectively. By understanding and utilizing the appropriate data types, you can write Python
programs that are efficient, expressive, and capable of handling a wide range of data and tasks.
Write a Python program that takes user input and determines its data type. The program should
display a message indicating the determined data type or that the input is not an integer or a
float. Use appropriate error-handling techniques to handle cases where the conversion to an
integer or float might fail.
You can use the input() function to get user input and the try and except blocks to handle
potential conversion errors. This program will help users understand the data type of their input
and how Python's type conversion works.
Algorithm:
____________________________________________________________________________
35
Input:
user_input
Output:
data_type
Data_type_float
Pseudo Code:
Begin:
Display "Enter something: "
Read user_input
Try:
Convert user_input to integer
Set data_type as a type of number
Display "Data type: " + data_type
Except for ValueError:
Display "Not an integer."
Try:
Convert user_input to float
Set data_type_float as a type of floating_number
Display "Data type as float: " + data_type_float
Except for ValueError:
Display "Not a float."
End Try
End
____________________________________________________________________________
36
To get the full version visit this page.
____________________________________________________________________________
37
Chapter 5
Python Operators: A Comprehensive Overview
____________________________________________________________________________
____________________________________________________________________________
5.1 Introduction
Operators in Python are symbols or special keywords used to perform various operations on
operands, such as variables, values, or expressions. They enable you to manipulate and
compare data, control program flow, perform mathematical calculations, and more.
Understanding the different types of operators and their functionalities is essential for writing
efficient and expressive Python code. Let's explore the major categories of operators in Python
along with examples and explanations:
4. Division (/): Divides the first operand by the second, resulting in a float value.
5. Floor Division (//): Divides the first operand by the second, resulting in an integer value
(rounded down).
6. Modulo (%): Returns the remainder of the division between the first operand and the
second.
7. Exponentiation (**): Raises the first operand to the power of the second.
Example:
x = 10
y = 3
sum = x + y
difference = x - y
product = x * y
____________________________________________________________________________
38
division = x / y
floor_division = x // y
modulo = x % y
exponentiation = x ** y
print(sum) # Output: 13
print(difference) # Output: 7
print(product) # Output: 30
print(division) # Output: 3.3333333333333335
print(floor_division) # Output: 3
print(modulo) # Output: 1
print(exponentiation) # Output: 1000
Example:
x = 10
y = 3
x += y # Equivalent to x = x + y
print(x) # Output: 13
x **= y # Equivalent to x = x ** y
print(x) # Output: 2197
____________________________________________________________________________
39
Example:
x = 10
y = 5
is_equal = x == y
print(is_equal) # Output: False
is_greater = x > y
print(is_greater) # Output: True
Example:
x = 10
y = 5
____________________________________________________________________________
40
Example:
x = 10
y = 5
bitwise_and = x & y
print(bitwise_and) # Output: 0
bitwise_or = x | y
print(bitwise_or) # Output: 15
bitwise_xor = x ^ y
print(bitwise_xor) # Output: 15
Membership operators are used to test if a value or variable exists within a sequence. The in
operator returns True if the value is found, while the not in operator returns True if the value is
not found.
Example:
…
…
Example:
x = [1, 2, 3]
y = [1, 2, 3]
is_same = x is y
____________________________________________________________________________
41
print(is_same) # Output: False
is_different = x is not y
print(is_different) # Output: True
These are the major categories of operators in Python, providing a wide range of functionalities
to handle different data types and perform various operations. By mastering these operators,
you can effectively manipulate data, control program flow, and solve complex problems using
Python.
Write a Python program that checks the strength of a password based on certain criteria. The
program should ask the user to enter a password and then evaluate its strength according to the
following rules:
1. The password must be at least 8 characters long.
2. The password must contain at least one uppercase letter.
3. The password must contain at least one lowercase letter.
4. The password must contain at least one digit.
5. The password must contain at least one special character (e.g., @, #, $, etc.).
After evaluating the password, the program should provide feedback to the user indicating
whether the password meets the criteria for a strong password or which specific criteria are not
met.
____________________________________________________________________________
42
This problem will require you to utilize a variety of operators to check the conditions and provide
appropriate feedback to the user based on the evaluation of the password's strength.
Input Output
____________________________________________________________________________
43
To get the full version visit this page.
____________________________________________________________________________
44
Chapter 6
Conditional Statements in Python: A Comprehensive Guide
____________________________________________________________________________
____________________________________________________________________________
6.1 Introduction
Conditional statements are an essential aspect of programming, allowing you to control the flow
of your code based on different conditions. In Python, conditional statements are implemented
using if, if-else, and nested if-else constructs. These statements enable you to execute specific
blocks of code based on whether certain conditions are met. Let's delve into each of these
topics and explore their functionalities, along with detailed explanations and examples.
6.2 if Statement
The if statement is the most basic conditional statement in Python. It allows you to execute a
block of code if a certain condition is true. The general syntax of the if statement is as follows:
Example:
if condition:
# Code block to be executed if the condition is true
The condition is an expression that evaluates to either True or False. If the condition is true, the
code block beneath the if statement is executed; otherwise, it is skipped.
Here's an example:
x = 10
if x > 5:
print("x is greater than 5")
In this example, if the value of x is greater than 5, the statement "x is greater than 5" is printed.
Otherwise, nothing is executed.
____________________________________________________________________________
45
6.3 if-else Statement
The if-else statement expands upon the if statement by providing an alternative code block to
execute when the condition is false. The general syntax of the if-else statement is as follows:
Example:
if condition:
# Code block to be executed if the condition is true
else:
# Code block to be executed if the condition is false
If the condition is true, the code block beneath the if statement is executed. If the condition is
false, the code block beneath the else statement is executed.
Here's an example:
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
In this example, if x is greater than 5, the statement "x is greater than 5" is printed. Otherwise,
the statement "x is not greater than 5" is printed.
Example:
if condition1:
# Code block to be executed if condition1 is true
if condition2:
# Code block to be executed if condition2 is true
else:
# Code block to be executed if condition2 is false
else:
# Code block to be executed if condition1 is false
____________________________________________________________________________
46
The nested if-else statement allows for more complex decision-making based on multiple
conditions.
Here's an example:
x = 10
if x > 5:
print("x is greater than 5")
if x == 10:
print("x is equal to 10")
else:
print("x is not equal to 10")
else:
print("x is not greater than 5")
In this example, if x is greater than 5, the statement "x is greater than 5" is printed. If x is also
equal to 10, the statement "x is equal to 10" is printed. Otherwise, the statement "x is not equal
to 10" is printed. If x is not greater than 5, the statement "x is not greater than 5" is printed.
Conditional statements play a crucial role in controlling the flow of your code based on specific
conditions. They enable you to execute different blocks of code, handle different scenarios, and
make decisions dynamically. By mastering if, if-else, and nested if-else statements in Python,
you can create robust and flexible programs that respond intelligently to various conditions and
inputs.
Here's a Python code snippet to determine whether a year is a leap year or not, along with an
explanation:
def is_leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True # Divisible by 400, hence a leap year
else:
return False # Divisible by 100 but not by 400, not a leap
year
else:
return True # Divisible by 4 but not by 100, hence a leap year
else:
____________________________________________________________________________
47
return False # Not divisible by 4, not a leap year.
Explanation:
1. The is_leap_year function takes a year as input and returns True if it is a leap year, and
False otherwise.
2. The first if statement checks if the year is divisible by 4 using the modulus operator %. If
it is divisible by 4, we move to the next condition.
3. The nested if statement checks if the year is divisible by 100. If it is divisible by 100, we
move to the next condition.
5. If the year is not divisible by 100 (but divisible by 4), it is a leap year.
8. Based on the result, the program prints whether the year is a leap year or not.
This code follows the rules for determining leap years: A year is a leap year if it is divisible by 4.
However, if it is divisible by 100, it is not a leap year, unless it is also divisible by 400. This logic
ensures accurate identification of leap years.
____________________________________________________________________________
48
Chapter 7
Complete Guide to Looping in Python: Exploring For, While,
and Nested Loops
____________________________________________________________________________
____________________________________________________________________________
7.1 Introduction
Looping is a fundamental concept in programming that allows you to repeat a block of code
multiple times. In Python, you can achieve looping using the for and while loops. These loops
provide flexibility and control over the execution of code, enabling you to iterate through
sequences, perform repetitive tasks, and solve complex problems. Additionally, nested loops
allow for multiple levels of iteration. In this article, we will explore the functionalities of for loops,
while loops, and nested loops, and provide examples and explanations for each.
Example:
for item in sequence:
# Code block to be executed for each item
In each iteration, the loop assigns the next item from the sequence to the variable item and
executes the code block beneath the loop. The loop continues until all items in the sequence
have been processed.
Here's an example:
fruits = ["apple", "banana", "orange"]
In this example, the for loop iterates over the list of fruits and prints each fruit.
____________________________________________________________________________
49
The for loop is useful when you know the number of iterations or want to iterate over a specific
sequence of items.
while condition:
# Code block to be executed while the condition is true
The loop repeatedly executes the code block as long as the condition remains true. If the
condition becomes false, the loop terminates, and the program continues with the next
statement. Here's an example:
count = 0
In this example, the while loop continues to execute as long as the count is less than 5. The
output will be:
Output:
0
1
2
3
4
The while loop is useful when you need to repeat a block of code based on a condition that may
change during the execution.
____________________________________________________________________________
50
7.4 Python Nested Loops
Nested loops are loops within loops, allowing for multiple levels of iteration. You can nest a for
loop inside another for loop, a while loop inside a while loop, or a combination of both. This
allows you to perform complex operations and work with multidimensional data structures.
Here's an example of a nested loop:
for i in range(3):
for j in range(2):
print(i, j)
print("---------------------")
for i in range(1,3):
for j in range(i,3):
for k in range(j,3):
print(i,j,k)
In this example, the outer loop iterates from 0 to 2, and for each iteration, the inner loop iterates
from 0 to 1. The output will be:
Output:
0 0
0 1
1 0
1 1
2 0
2 1
---------------------
1 1 1
1 1 2
1 2 2
2 2 2
Nested loops are powerful tools for solving problems that involve working with matrices, nested
data structures, or performing operations across multiple dimensions.
Now let's move on to calculating the sum of the first n numbers using for and while loops:
____________________________________________________________________________
51
7.5 Some Examples of Python Loops
The for loop can be used to calculate the sum of the first n numbers.
Here's an example:
n = 5
total = 0
In this example, we initialize the variable total to 0. The for loop iterates from 1 to n+1 (inclusive)
using the range function. Each number is added to the total variable using the += operator.
Finally, the sum of the first n numbers is printed.
Here's an example:
n = 5
total = 0
num = 1
while num <= n:
total += num
num += 1
print("Sum of first", n, "numbers:", total)
____________________________________________________________________________
52
In this example, we initialize the variables total and num to 0 and 1, respectively. The while loop
continues to execute as long as num is less than or equal to n. Inside the loop, each number is
added to the total variable, and num is incremented by 1. Finally, the sum of the first n numbers
is printed.
Both the for and while loops can be used to calculate the sum of the first n numbers, depending
on your preference and the specific requirements of your program.
Here's a Python code to generate a diamond shape pattern using asterisks (*):
rows = 5
spaces = rows - 1
stars = 1
Output:
*
***
*****
*******
*********
*******
*****
***
*
____________________________________________________________________________
53
Explanation:
____________________________________________________________________________
54
To get the full version visit this page.
____________________________________________________________________________
55
Chapter 8
Control Statements in Python: Exploring Break, Continue,
and Pass
____________________________________________________________________________
____________________________________________________________________________
8.1 Introduction
Control statements in Python provide ways to alter the normal flow of program execution. They
allow you to make decisions, skip iterations, terminate loops prematurely, and handle various
scenarios efficiently. This article will dive into three essential control statements: break,
continue, and pass. We will explore their purpose, and usage, and provide multiple examples to
illustrate their functionality.
Here's an example:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
break
print(num)
print("Loop ended")
Output:
1
2
Loop ended
In this example, the loop iterates over the numbers list. When the value of num becomes 3, the
break statement is encountered, and the loop is terminated. The code after the loop is then
executed.
____________________________________________________________________________
56
8.3 The Continue Statement
The continue statement is used to skip the current iteration of a loop and move to the next
iteration. It is useful when you want to skip certain values or perform specific actions for specific
conditions.
Here's an example:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
continue
print(num)
print("Loop ended")
Output:
1
3
5
Loop ended
In this example, the loop iterates over the numbers list. When an even number is encountered
(divisible by 2), the continue statement is triggered, and that iteration is skipped. The code after
the continue statement is not executed, and the loop moves to the next iteration.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
pass
print(num)
print("Loop ended")
____________________________________________________________________________
57
Output:
1
2
3
4
5
Loop ended
In this example, the pass statement is encountered when the num is equal to 3. It acts as a
placeholder, and no code execution is skipped. The loop continues normally, and all the
numbers are printed.
These control statements provide powerful mechanisms to control the flow of your Python
programs. By utilizing break, continue, and pass statements, you can make decisions, handle
exceptions, and create more efficient and flexible code structures. Remember to apply these
statements judiciously based on your specific program requirements.
____________________________________________________________________________
58
Chapter 9
Mastering String Manipulation in Python: An
Extensive Exploration
____________________________________________________________________________
____________________________________________________________________________
Here's an example:
Concatenation: You can concatenate two or more strings using the + operator. It combines the
strings into a single string.
Here's an example:
string1 = "Hello"
string2 = "World"
result = string1 + " " + string2
print(result) # Output: Hello World
Repetition: You can repeat a string multiple times using the * operator. It creates a new string
by repeating the original string.
____________________________________________________________________________
59
Here's an example:
string = "Hello"
result = string * 3
print(result) # Output: HelloHelloHello
Length: You can find the length of a string using the len() function. It returns the number of
characters in the string.
Here's an example:
string = "Hello"
length = len(string)
print(length) # Output: 5
Here's an example:
In this example, the slice [7:12] extracts the characters from index 7 to index 11 (excluding index
12) and returns the string "World".
____________________________________________________________________________
60
● strip(): Removes leading and trailing whitespace from the string.
In this example, the functions and methods are applied to the string variable, producing the
desired results.
String manipulation is a crucial aspect of working with textual data in Python. By understanding
how to access strings, perform basic operations, use string slices, and utilize functions and
methods, you can effectively manipulate and process strings in your Python programs.
Experiment with different examples and explore additional functions and methods to enhance
your string manipulation skills.
____________________________________________________________________________
61
Here's an example:
name = "Alice"
age = 25
greeting = f"Hello, my name is {name} and I am {age} years old."
print(greeting)
Output:
Hello, my name is Alice and I am 25 years old.
In this example, the variable's name and age are directly interpolated into the string using
f-string syntax. The values of the variables are automatically substituted in the final string.
Here's an example:
x = 10
y = 5
result = f"The sum of {x} and {y} is {x + y}."
print(result)
Output:
The sum of 10 and 5 is 15.
In this example, the expression {x + y} is evaluated and the result is inserted into the string.
pi = 3.14159
____________________________________________________________________________
62
result = f"The value of pi is approximately {pi:.2f}."
print(result)
Output:
In this example: .2f is a formatting specifier that specifies the precision of the floating-point
number pi to two decimal places.
F-strings offer a concise and readable way to create formatted strings in Python. They simplify
the process of string interpolation, expression evaluation, and string formatting, making the code
more expressive and efficient. F-strings are a valuable tool for generating dynamic and
formatted output in various applications, including data processing, web development, and
automation.
____________________________________________________________________________
63
Chapter 10
Python Lists: A Comprehensive Guide to Working with Lists
____________________________________________________________________________
____________________________________________________________________________
10.1 Introduction
Lists are one of the most versatile and commonly used data structures in Python. They allow
you to store and manipulate collections of items, such as numbers, strings, or even other lists.
This article will explore the ins and outs of working with lists in Python. We'll cover various
aspects, including accessing lists, performing list operations, working with list functions and
methods, and more.
Here's an example:
python
Copy code
my_list = [10, 20, 30, 40, 50]
print(my_list[0]) # Output: 10
print(my_list[2]) # Output: 30
Adding Elements: You can add elements to a list using the append() method or the + operator
for concatenation. The append() method adds an element to the end of the list, while the +
operator concatenates two lists.
____________________________________________________________________________
64
Here's an example:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
new_list = my_list + [5, 6]
print(new_list) # Output: [1, 2, 3, 4, 5, 6]
Removing Elements: You can remove elements from a list using the remove() method or the
del keyword. The remove() method removes the first occurrence of a specified element, while
the del keyword removes an element at a specified index.
Here's an example:
my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list) # Output: [1, 2, 4, 5]
del my_list[1]
print(my_list) # Output: [1, 4, 5]
List Slicing: You can extract a portion of a list using slicing. Slicing allows you to specify a
range of indices to create a new list. Here's an example:
my_list = [1, 2, 3, 4, 5]
sliced_list = my_list[1:4]
print(sliced_list) # Output: [2, 3, 4]
● sorted(): Returns a sorted version of a list without modifying the original list.
____________________________________________________________________________
65
● insert(): Inserts an element at a specified index.
print(len(my_list)) # Output: 5
print(sorted(my_list)) # Output: [10, 20, 30, 40, 50]
my_list.append(60)
print(my_list) # Output: [10, 20, 30, 40, 50, 60]
my_list.extend([70, 80])
print(my_list) # Output: [10, 20, 30, 40, 50, 60, 70, 80]
my_list.insert(2, 15)
print(my_list) # Output: [10, 20, 15, 30, 40, 50, 60, 70, 80]
print(my_list.count(30)) # Output: 1
____________________________________________________________________________
66
10.2.1.1 Iterative Method
One way to count the frequency of elements in a list is to manually iterate over the list and keep
track of the count for each element.
Here's an example:
my_list = [1, 2, 3, 2, 4, 1, 2, 5]
frequency = {}
for element in my_list:
if element in frequency:
frequency[element] += 1
else:
frequency[element] = 1
print("Element\tFrequency")
for element, count in frequency.items():
print(f"{element}\t\t{count}")
Output:
Element Frequency
1 2
2 3
3 1
4 1
5 1
In this method, we iterate over each element in the list. If the element is already in the frequency
dictionary, we increment its count. Otherwise, we add the element to the dictionary with a count
of 1.
Lists are incredibly versatile and widely used in Python. They provide a flexible and efficient way
to store and manipulate collections of data. By understanding how to access lists, perform list
operations, and utilize functions and methods, you can harness the power of lists to solve
various programming problems and build robust applications.
Experiment with different examples, explore additional functions and methods and leverage the
flexibility of lists to enhance your Python programming skills.
____________________________________________________________________________
67
Chapter 11
Python Tuples: A Comprehensive Guide to Working with
Tuples
____________________________________________________________________________
____________________________________________________________________________
11.1 Introduction
Tuples are an important data structure in Python that allows you to store multiple elements in an
ordered and immutable sequence. This comprehensive article will explore the ins and outs of
working with tuples in Python. We'll cover various aspects, including accessing tuples,
performing tuple operations, working with tuple functions and methods, and providing examples
to illustrate their usage.
Here's an example:
Operations
While tuples are immutable and cannot be modified once created, there are several operations
you can perform on tuples.
Concatenation: You can concatenate two or more tuples using the + operator, which creates a
new tuple containing all the elements from the original tuples.
Here's an example:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2
print(concatenated_tuple) # Output: (1, 2, 3, 4, 5, 6)
____________________________________________________________________________
68
Slicing: You can extract a portion of a tuple using slicing, which allows you to specify a range of
indices to create a new tuple.
Here's an example:
my_tuple = (1, 2, 3, 4, 5)
sliced_tuple = my_tuple[1:4]
print(sliced_tuple) # Output: (2, 3, 4)
● index(): Returns the index of the first occurrence of a specified element in a tuple.
Let's look at a few examples that illustrate the practical usage of tuples in Python:
Tuple Unpacking:
____________________________________________________________________________
69
Returning Multiple Values from a Function:
def get_user_info():
name = "Alice"
age = 25
email = "[email protected]"
return name, age, email
user_info = get_user_info()
print(user_info) # Output: ("Alice", 25, "[email protected]")
Let :
sales_data = (
("Product A", 100),
("Product B", 150),
("Product C", 200),
("Product A", 75),
("Product B", 50),
("Product C", 100),
("Product A", 125),
("Product B", 100),
("Product C", 150)
)
____________________________________________________________________________
70
Here, each element of the tuple represents a sales record for a product, where the first element
is the product name and the second element is the sales quantity.
Here's an example:
total_sales = 0
for record in sales_data:
total_sales += record[1]
print("Total Sales Quantity:", total_sales)
Output:
____________________________________________________________________________
71
To get the full version visit this page.