Python Programming A Stepbystep Guide To Learning The Language C K Dhaliwal download
Python Programming A Stepbystep Guide To Learning The Language C K Dhaliwal download
https://ebookbell.com/product/python-programming-a-stepbystep-
guide-to-learning-the-language-c-k-dhaliwal-56520724
https://ebookbell.com/product/python-programming-for-advanced-the-
updated-advanced-guide-to-master-python-programming-step-by-step-in-a-
few-days-with-machine-learning-and-data-science-resources-vol-3-bill-
steven-232306752
https://ebookbell.com/product/python-the-first-stepbystep-guide-for-
beginners-to-programming-and-deep-learning-with-python-data-science-
andrew-johnson-36695666
https://ebookbell.com/product/absolute-beginners-guide-to-python-
programming-master-coding-quickly-with-handson-realworld-projects-
stepbystep-guidance-and-comprehensive-learning-for-all-ages-stirling-
hale-58084436
https://ebookbell.com/product/python-3-a-stepbystep-guide-to-learn-in-
an-easy-way-the-fundamentals-of-python-programming-language-john-
bach-43213818
Mastering Python Programming For Iot Development A Step By Step Guide
To Build Smart Devices And Systems With Pyth The Essential Python
Workbooks Book 8 Ruder
https://ebookbell.com/product/mastering-python-programming-for-iot-
development-a-step-by-step-guide-to-build-smart-devices-and-systems-
with-pyth-the-essential-python-workbooks-book-8-ruder-231559626
https://ebookbell.com/product/langchain-programming-for-beginners-a-
stepbystep-guide-to-ai-application-development-with-langchain-python-
openaichatgpt-googlegemini-and-other-llms-code-with-nathan-
sebhastian-58491116
https://ebookbell.com/product/learn-to-program-with-
python-3-a-stepbystep-guide-to-programming-2nd-edition-irv-
kalb-42280876
https://ebookbell.com/product/computer-programming-allinonecoding-for-
beginners-a-stepbystep-guide-to-learn-python-java-sql-c-c-c-html-and-
css-from-scratch-michail-klling-55885230
https://ebookbell.com/product/python-programming-the-ultimate-
beginners-guide-to-python-language-fundamentals-a-crash-course-with-
stepbystep-exercises-john-russel-53747934
Python Programming
A Step-by-Step Guide to Learning the Language
Python Programming
A Step-by-Step Guide to Learning the Language
Dr. C. K. Dhaliwal
Assistant Professor
Chandigarh Business School of Administrations
Mohali, Punjab
***
Poonam Rana
Assistant Professor
Chandigarh Business School of Administrations
Mohali, Punjab
***
Dr. T. P. S. Brar
Professor & Head of Department
Chandigarh Group of Colleges
Mohali, Punjab
First published 2025
by CRC Press
4 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN
and by CRC Press
2385 NW Executive Center Drive, Suite 320, Boca Raton FL 33431
CRC Press is an imprint of Informa UK Limited
© 2025 Manakin Press Pvt. Ltd
The right of of C. K. Dhaliwal, Poonam Rana and Dr. T. P. S. Brar to be identified as authors
of this work has been asserted in accordance with sections 77 and 78 of the Copyright,
Designs and Patents Act 1988.
All rights reserved. No part of this book may be reprinted or reproduced or utilised in any
form or by any electronic, mechanical, or other means, now known or hereafter invented,
including photocopying and recording, or in any information storage or retrieval system,
without permission in writing from the publishers.
For permission to photocopy or use material electronically from this work, access www.
copyright.com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive,
Danvers, MA 01923, 978-750-8400. For works that are not available on CCC please contact
mpkbookspermissions@tandf.co.uk
Trademark notice: Product or corporate names may be trademarks or registered trademarks,
and are used only for identification and explanation without intent to infringe.
Print edition not for sale in South Asia (India, Sri Lanka, Nepal, Bangladesh, Pakistan or
Bhutan).
British Library Cataloguing-in-Publication Data
A catalogue record for this book is available from the British Library
ISBN: 9781032646558 (hbk)
ISBN: 9781032669571 (pbk)
ISBN: 9781032691053 (ebk)
DOI: 10.4324/9781032691053
Typeset in Times New Roman
by Manakin Press, Delhi
Organization of the Book
Chapter 1 This is an introductory chapter that provides an overview of Python,
covering its history, features, applications, and installation process. It highlights
Python's dynamic, high-level, and object-oriented language features and cross-
platform compatibility. The chapter emphasizes the use of Python in web development,
data science, and machine learning. It also explains Python interactive help and
demonstrates how to install and execute Python on different platforms. Additionally,
the chapter covers how Python differs from other programming languages.
Chapter 4 This chapter covers conditional statements in Python, including if, if-
else, and if-elif-if statements. It also covers loops in Python, including while, for,
and infinite loops, along with examples of how to use them. Additionally, the chapter
covers the use of the break, continue, and pass statements in Python loops, which are
used to change the flow of control in a program.
Chapter 5 This chapter covers the native data types in Python, including numbers,
lists, tuples, sets, dictionaries, and strings. It provides examples and use cases for
each data type. The chapter highlights the differences between mutable and immutable
data types and how to work with them. Additionally, it covers how to manipulate and
operate on data types, including slicing and indexing.
Chapter 6 This chapter covers Python functions, including the types of functions in
Python, such as built-in functions, user-defined functions, and anonymous functions.
It discusses the advantages of using functions, such as code reusability, modularity,
and easier debugging. The chapter also covers the differences between pass by value
and pass by reference and demonstrates recursion, which is the ability of a function
to call itself.
vi Python Programming: A Step-by-Step Guide to Learning the Language
Chapter 7 This chapter covers Python modules, which are files that contain Python
definitions and statements. It demonstrates how to create a module and how to import
it into another Python program. Additionally, the chapter covers standard modules,
which are built-in modules that come with Python, and Python packages, which are
directories containing modules. It highlights how to use and install standard modules
and how to create and install Python packages.
Chapter 8 This chapter covers Python exceptions, which are errors that occur during
program execution. It explains the different types of built-in exceptions in Python,
such as ZeroDivisionError and TypeError. The chapter demonstrates how to handle
exceptions using the try-except block and how to raise and catch user-defined
exceptions. It also provides examples of exception handling and how to use the else
and finally clauses with the try-except block.
Chapter 9 This chapter covers file operations in Python, including how to create,
open, read, write, and close files using file methods such as read() and write(). The
chapter also covers renaming and deleting files, as well as creating and navigating
directories in Python using the os module. It provides examples of how to use file
methods and how to handle file exceptions.
Chapter 10 This chapter covers designing classes in Python, which are templates for
creating objects that have similar properties and behaviors. It explains how to create
objects from a class, how to access object attributes, and how to use built-in class
attributes, such as name and doc. The chapter also covers garbage collection in Python,
which is the process of freeing up memory that is no longer being used by a program.
It provides examples of how to design and use classes in Python.
Chapter 11 This chapter covers inheritance in Python, which is the ability to create
a new class from an existing class. It explains the different types of inheritance in
Python, including single inheritance, multiple inheritance, and multilevel inheritance.
The chapter also covers method overriding in Python, which is the ability to redefine a
method in a subclass. Additionally, the chapter discusses special functions in Python,
which are predefined methods that are called under certain circumstances, such as init
and str. It provides examples of how to use inheritance and special functions in Python.
Chapter 12 This chapter covers operator overloading in Python, which is the ability to
redefine the behavior of an operator in a class. It explains how to overload the + and -
operators in Python, as well as bitwise and relational operators. The chapter provides
examples of how to use operator overloading to customize the behavior of operators
in Python.
The Appendix- I is given which provides the list of Python Standard Modules with
the description of each.
Authors
Detailed Contents
Introduction to Python
Language
Highlights
l Introduction and History of Python Language
l Features of Python
l Applications of Python
l Python Interactive Help
l Installing and Executing Python
l How Python Differs from Other Languages
Today, Python is one of the most popular programming languages in the world,
and is used in a wide variety of applications, including web development, data
analysis, artificial intelligence, and scientific computing. It is a powerful and
flexible language that is well-suited to many different tasks, and it has a large
and vibrant community of developers who continue to work on improving the
language and developing new libraries and tools.
Introduction to Python Language 5
your platform, you can compile the source code manually using a C compiler.
The installation process for Python may differ slightly depending on the
platform, and specific instructions can be found on the official website for
each platform, such as Unix or Linux.
running Python code. Some popular IDEs for Python include PyCharm,
Visual Studio Code, and Spyder.
Once you have Python installed and set up, you can start writing and running
Python code to perform various tasks and solve problems.
This will execute the script, and you should see the output Hello, World! in
the terminal or command prompt.
You can also pass command-line arguments to a Python script by including
them after the script name. For example, if you have a script called add.py
14 Python Programming: A Step-by-Step Guide to Learning the Language
that takes two numbers as arguments and adds them together, you could run
it with the following command:
python add.py 2 3
This would execute the script with the arguments 2 and 3, and the output
would be 5.
Note that in order to run a Python script from the command-line, you must
have Python installed on your computer and the Python executable must be
in your system’s PATH variable.
This would define a variable x with the value 5, and then define a variable y
with the value 10 (which is the result of multiplying x by 2). Finally, it would
print the value of y to the console.
16 Python Programming: A Step-by-Step Guide to Learning the Language
You can exit the interactive interpreter by typing exit() or quit() at the
command prompt and pressing Enter. This will return you to the terminal or
command prompt.
13. Memory Safety: C++ is a language that provides the programmer with
the ability to manually manage memory. While this gives the programmer
more control over how memory is used, it also means that the program
can be susceptible to memory-related bugs, such as buffer overflows
and memory leaks. Python has built-in garbage collection, meaning that
it automatically manages memory, which makes it less susceptible to
memory-related bugs.
These are just a few of the many differences between C++ and Python. While
both languages are widely used and powerful, they have different strengths
and weaknesses, and the choice of language will depend on the specific needs
of the project and the preferences of the programmer.
into objects and classes. Python, on the other hand, allows for more
procedural and functional programming styles as well.
6. Application: Java is often used for web development, desktop application
development, and mobile app development. Python is often used for web
development, scientific computing, data analysis, machine learning, and
automation.
7. Performance: Java is generally faster than Python because it is
a compiled language, and the JVM can optimize the bytecode for
performance. Python, on the other hand, is an interpreted language,
meaning that the code is executed directly by an interpreter, which can
be slower. However, Python has some libraries that are implemented in
C or C++ that can boost its performance.
8. Garbage Collection: Java has a more advanced garbage collector than
Python, meaning that it can handle memory more efficiently.
9. Learning Curve: Java is generally considered more difficult to learn
and use than Python. Java has a steep learning curve because it is a more
complex language with a larger number of features and more stringent
syntax rules. Python, on the other hand, has a simpler syntax and a
smaller set of features, making it easier to learn and use.
These are just a few of the many differences between Java and Python. While
both languages are widely used and powerful, they have different strengths
and weaknesses, and the choice of language will depend on the specific needs
of the project and the preferences of the programmer.
1.15 Summary
In this chapter, we have learned about the programming language and its
needs. Then we gave a brief look at the origin and history of the Python
language along with its features and limitations. We have explored in detail
how Python language differs from other existing and prominent programming
languages such as C,C++, and Java. The setup and installation of Python
language along with a simple first program are also discussed in detail.
Review Questions
1. What is Python and what makes it a popular programming language?
2. How does Python differ from other programming languages?
Introduction to Python Language 23
Highlights
l Keywords and identifiers
l Python statements
l Documentation and indentation
l Python Variables
l Python data types
l Input and output
l Import
Python has several built-in data types including strings, integers, and
lists. These data types can be used to store and manipulate different kinds
of information in a program. In addition to these basic data types, Python
also has advanced data types such as dictionaries and sets.
Python also has a built-in module for input/output operations, which
allows a program to read from and write to external sources, such as files
and streams. The module, called io, provides several functions to perform
these operations, such as open(), read(), and write().
2.1 Keywords
In Python, a keyword is a word that has a special meaning in the Python
language. Keywords are used to define the syntax and structure of the
26 Python Programming: A Step-by-Step Guide to Learning the Language
Python language, and they cannot be used as identifiers (i.e., variable names,
function names, etc.) in Python code.
Keyword Description
and Logical operator returns True if both operands are True,
otherwise, it returns False.
as Used to create an alias for a module or variable when
importing or renaming.
assert Used to check if a given condition is True, and raises an
exception if it is False.
async Used to define an asynchronous function or context manager.
await Used inside an async function to wait for an asynchronous
operation to complete.
break Used to exit a loop early, before the loop condition is met.
class Used to define a new class.
continue Used to skip the current iteration of a loop and continue with
the next iteration.
def Used to define a new function.
del Used to delete an object or an item from a collection.
elif Short for “else if”, used in a conditional statement to check
for additional conditions.
else Used in a conditional statement as a catch-all option if no
other conditions are met.
except Used to handle exceptions that are raised in a try block.
False Boolean value that represents the absence of truth.
finally Used in a try-except block to specify a block of code that
will always be executed, regardless of whether an exception
was raised or not.
for Used to iterate over a sequence of items, such as a list or a
tuple.
from Used in an import statement to import specific items from
a module.
global Used to indicate that a variable is a global variable, accessible
from anywhere in the code.
if Used to start a conditional statement.
import Used to import a module or a specific item from a module.
Python Data Types and Input Output 27
Keyword Description
in Used to check if an item is in a sequence, such as a list or
a tuple.
is Used to check if two variables refer to the same object.
lambda Used to create small anonymous functions.
None Special value that represents the absence of a value or a null
value.
nonlocal Used to indicate that a variable is nonlocal to the current
function, meaning it is defined in an outer function.
not Logical operator that negates a boolean value.
or Logical operator that returns True if at least one of the
operands is True, otherwise it returns False.
pass Used as a placeholder for a block of code that does nothing.
raise Used to raise an exception.
return Used to exit a function and return a value to the calling code.
True Boolean value that represents the presence of truth.
try Used to specify a block of code that might raise an exception.
while Used to start a loop that will continue to execute as long as
the loop condition is True.
with Used to create a context manager, which is used to
automatically set up and tear down resources.
yield Used in a function
2.2 Identifiers
In Python, an identifier is a name used to identify a variable, function, class,
module, or other objects. There are a few rules and conventions for naming
identifiers in Python:
• Identifiers must start with a letter or an underscore (_).
• Identifiers cannot start with a number.
• Identifiers can only contain letters, numbers, and underscores.
• Identifiers are case-sensitive, so myVariable and myvariable are
considered to be different identifiers.
• Python reserves a set of keywords that cannot be used as identifiers.
Examples include if, else, for, class, etc.
28 Python Programming: A Step-by-Step Guide to Learning the Language
2.4 Indentation
Indentation is used in Python to indicate blocks of code. The standard
indentation is four spaces, and most Python code follows this convention.
For example
Code 2.1 Illustration of indentation in Python
def foo():
# This line is indented by four spaces
x=5
if x > 0:
# This line is also indented by four spaces
print(“x is positive”)
# This line is not indented, so it’s not part of the if block
It is important to be consistent with your indentation, as the meaning of the
code can change based on the indentation level. For example
Code 2.2 Illustration of indentation in Python
x=5
if x > 0:
print(“x is positive”)
print(“This line is not indented, so it’s not part of the if block”)
This code will print both messages because the second print statement is not
indented, so it is not part of the if block.
Code 2.3 Illustration of indentation in Python
x=5
if x > 0:
print(“x is positive”)
print(“This line is indented, so it is part of the if block”)
print(“This line is not indented, so it’s not part of the if block”)
30 Python Programming: A Step-by-Step Guide to Learning the Language
This code will only print the first message, because the second print statement
is indented, so it is part of the if block.
lines and are commonly used for longer explanations and docstrings. Here is
an example:
Code 2.7 Illustration of double quotes in Python
“””
This is a multiline
comment. It can span
multiple lines.
“””
You can also use triple single quotes to create a multiline comment:
Code 2.8 Illustration of single quotes in Python
‘’’
This is also a
multiline comment. It
can also span multiple
lines.
‘’’
Both triple quotes (single or double) can be used to create a multiline
comment in Python. The advantage of using triple quotes is that you can
create a multiline comment even if it contains multiple lines of the same type
of quote character.
2.6 Docstrings
In Python, a docstring is a string literal that appears as the first statement
in a module, function, class, or method definition. It is used to provide
documentation for the code, and can be accessed using the built-in help()
function or the __doc__ attribute. Docstrings are enclosed in triple quotes
(either single or double) and are typically written in plain text, but can also
include markdown formatting.
It is a good practice to include a docstring in any function or class you write,
as it makes your code more readable and user-friendly.
Here is an example of a simple Python function with a docstring:
32 Python Programming: A Step-by-Step Guide to Learning the Language
Parameters:
a (int): The first number
b (int): The second number
Returns:
int: The sum of a and b
“””
return a + b
In this example, the function add takes two numbers as input, adds them
together, and returns the result. The docstring provides a brief description of
what the function does, and explains the parameters and return value.
To access the docstring of this function, you can use the help() function like
this:
help(add)
You can also access the docstring programmatically using the __doc__
attribute:
print(add.__doc__)
2.7 Variables
A Python variable is a reserved memory location to store values. In other
words, a variable in a python program gives data to the computer for
Python Data Types and Input Output 33
assigned to it during its lifetime must always have that type. Variables in
Python are not subject to this restriction. In Python, a variable may be
assigned a value of one type and then later re-assigned a value of a different
type:
Code 2.11 Illustration of variable in Python
var = 21.09
print(var)
21.09
Let’s see another example:
Code 2.12 Illustration of variable in Python
>>> var = “Welcome to Python”
>>> print(var)
Welcome to Python
Parenthesis are optional around tuples in Python and they’re also optional
in multiple assignment (which uses a tuple-like syntax). All of these are
equivalent:
Python Data Types and Input Output 35
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
ebookbell.com