Introduction to Python Programming_nep_fycs (1)
Introduction to Python Programming_nep_fycs (1)
AJAY PASHANKAR
www.profajaypashankar.com Page 1 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Overview and Basic Elements of Python Programming: Features of Python,
Execution of a Python Program, Flavours of Python, Innards of Python,
Python Interpreter, Comments, Docstrings, IDLE, Data types, Dictionary,
Sets, Mapping, Basic Elements of Python, Variables, Input Function, Output
Statements, Command
Exploring List, Tuples and Dictionaries: Lists, List Functions and Methods, List
Operations, List Slices, Nested Lists, Tuples, Functions in Tuple.
Working with Dictionaries: Creating a Dictionary, Operators in Dictionary,
Dictionary Methods, Using for Loop with Dictionaries, Operations on
Dictionaries
Files in Python: Opening and Closing a File, Working with Text Files, ,
Working with Binary Files, The ‘with’ statement, Pickle in Python, The seek()
and tell() Methods, Random Accessing of Binary Files, Zipping and Unzipping
Files, Working with Directories
Regular Expressions: Introduction, Sequence Characters in Regular
Expressions, Special Characters in Regular Expressions, Using Regular
Expression on Files, Retrieving Information from an HTML File
Date And Time in Python: Time, Date, Date and Time Now, combining date
and times, formatting date and time, Finding and comparing dates, Sorting
dates, Knowing the Time taken by a Program, Working with Calendar Module
www.profajaypashankar.com Page 2 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
CHAPTER I: OVERVIEW AND BASIC ELEMENTS OF PYTHON PROGRAMMING
Topics Covered: Features of Python, Execution of a Python Program, Flavours of Python, Innards of
Python, Python Interpreter, Comments, Docstrings, IDLE, Data types, Dictionary, Sets, Mapping,
Basic Elements of Python, Variables, Input Function, Output Statements, and Command Line
Arguments. Operators, Precedence of Operators, Associativity of Operators.
---------------------------------------------------------------------------------------------------------------
The programming language you will be learning is Python. Python is an example of a high-level
language; other high-level languages you might have heard of are C++, PHP, and Java.
As you might infer from the name high-level language, there are also low-level languages,
sometimes referred to as machine languages or assembly languages. Loosely speaking, computers
can only execute programs written in low-level languages. Thus, programs written in a high-level
language have to be processed before they can run. This extra processing takes some time, which is
a small disadvantage of high-level languages.
But the advantages are enormous. First, it is much easier to program in a high-level language.
Programs written in a high-level language take less time to write, they are shorter and easier to read,
and they are more likely to be correct. Second, high-level languages are portable, meaning that
they can run on different kinds of computers with few or no modifications. Low-level programs can
run on only one kind of computer and have to be rewritten to run on another.
Due to these advantages, almost all programs are written in high-level languages. Low-level
languages are used only for a few specialized applications.
Two kinds of applications process high-level languages into low-level languages: interpreters and
compilers. An interpreter reads a high-level program and executes it, meaning that it does what the
program says. It processes the program a little at a time, alternately reading lines and performing
computations.
A compiler reads the program and translates it into a low-level program, which can then be run.
In this case, the high-level program is called the source code, and the translated program is called
the object code or the executable. Once a program is compiled, you can execute it repeatedly
without further translation.
Many modern languages use both processes. They are first compiled into a lower
level language, called byte code, and then interpreted by a program called a virtual machine.
Python uses both processes, but because of the way programmers interact with it, it is usually
considered an interpreted language.
There are two ways to use the Python interpreter: shell mode and script mode. In shell mode, you
type Python statements into the Python shell and the interpreter
---------------------------------------------------------------------------------------------------------------
Python was developed by Guido van Rossum in the late eighties and early nineties at the National
Research Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk,
and Unix shell and other scripting languages.
• Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public
License (GPL).
• Python is now maintained by a core development team at the institute, although Guido van Rossum
still holds a vital role in directing its progress.
• Python 1.0 was released in November 1994. In 2000, Python 2.0 was released. Python
2.7.11 is the latest edition of Python 2.
• Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward compatible with Python 2.
The emphasis in Python 3 had been on the removal of duplicate programming constructs and modules
so that "There should be one -- and preferably only one -- obvious way to do it." Python 3.5.1 is the
latest version of Python 3.
www.profajaypashankar.com Page 3 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
---------------------------------------------------------------------------------------------------------------
Features of python:
Python's features include-
• Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows
a student to pick up the language quickly.
• Easy-to-read: Python code is more clearly defined and visible to the eyes.
• Easy-to-maintain: Python's source code is fairly easy-to-maintain.
• A broad standard library: Python's bulk of the library is very portable and crossplatform compatible
on UNIX, Windows, and Macintosh.
• Interactive Mode: Python has support for an interactive mode, which allows interactive testing and
debugging of snippets of code.
• Portable: Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.
• Extendable: You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
• Databases: Python provides interfaces to all major commercial databases.
• GUI Programming: Python supports GUI applications that can be created and ported
to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.
• Scalable: Python provides a better structure and support for large programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good features. A few are listed
below-
• It supports functional and structured programming methods as well as OOP.
• It can be used as a scripting language or can be compiled to byte-code for building large
applications.
• It provides very high-level dynamic data types and supports dynamic type checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
---------------------------------------------------------------------------------------------------------------
Execution of a Python Program:
a = 10
b = 10
print("Sum ", (a+b))
Output:
Sum 20
Suppose the above python program is saved as first.py. Here first is the name and .py is the
extension. The execution of the Python program involves 2 Steps:
Compilation
Interpreter
Compilation
The program is converted into byte code. Byte code is a fixed set of instructions that represent
arithmetic, comparison, memory operations, etc. It can run on any operating system and hardware.
The byte code instructions are created in the .pyc file. The .pyc file is not explicitly created as Python
handles it internally but it can be viewed with the following command:
-m and py_compile represent module and module name respectively. This module is responsible to
generate .pyc file. The compiler creates a directory named __pycache__ where it stores the
first.cpython-38.pyc file.
Interpreter
The next step involves converting the byte code (.pyc file) into machine code. This step is necessary
as the computer can understand only machine code (binary code). Python Virtual Machine (PVM) first
understands the operating system and processor in the computer and then converts it into machine
code. Further, these machine code instructions are executed by processor and the results are
displayed.
www.profajaypashankar.com Page 4 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
To view the byte code of the file – first.py we can type the following command as :
The dis command is known as “disassembler” that displays the byte code in an understandable
format. The code represents 5 columns:
1. Line Number
2. offset position of byte code
3. name of byte code instruction
4. instruction’s argument
5. constants or names (in brackets)
---------------------------------------------------------------------------------------------------------------
Flavors of Python
Flavors of Python refer to the different types of Python compilers. These flavors are useful to integrate
various programming languages into Python. The following are some of them:
CPython:
This is the standard Python compiler implemented in C language. This is the Python software being
downloaded and used by programmers directly from CPython . In this, any Python program is
internally converted into byte code using C language functions. This byte code is run on the
interpreter available in Python Virtual Machine (PVM) created in C language. The advantage is that it
is possible to execute C and C++ functions and programs in CPython.
---------------------------------------------------------------------------------------------------------------
Jython:
This is earlier known as JPython. This is the implementation of Python programming language which
is designed to run on Java platform. Jython compiler first compiles the Python program into Java byte
code. This byte code is executed by Java Virtual Machine (JVM) to produce the output. Jython contains
libraries which are useful for both Python and Java programmers. This can be downloaded
from Jython .
---------------------------------------------------------------------------------------------------------------
IronPython:
This is another implementation of Python language for .NET framework. This is written in C# (C
Sharp) language. The Python program when compiled gives an intermediate language (IL) which
runs on Common Language Runtime (CLR) to produce the output. This flavor of Python gives
www.profajaypashankar.com Page 5 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
flexibility of using both the .NET and Python libraries. IronPython can be downloaded
from IronPython .
---------------------------------------------------------------------------------------------------------------
PyPy:
This is Python implementation using Python language. Actually, PyPy is written in a language called
RPython which was created in Python language. RPython is suitable for creating language
interpreters. PyPy programs run very fast since there is a JIT (Just In Time) compiler added to the
PVM. PyPy can be downloaded by visiting the page: PyPy . Since the original Python uses only an
interpreter in the Python Virtual Machine (PVM), the Python programs run slowly. To improve the
speed of execution, a compiler called JIT (Just In Time) is introduced into the PVM of PyPy. Hence,
PyPy programs run faster than those of Python. We can download PyPy from PyPy .
---------------------------------------------------------------------------------------------------------------
RubyPython:
This is a bridge between the Ruby and Python interpreters. It encloses a Python interpreter inside
Ruby applications. This flavor of Python can be downloaded from RubyPython .
---------------------------------------------------------------------------------------------------------------
StacklessPython:
Small tasks which should run individually are called tasklets. Tasklets run independently on CPU and
can communicate with others via channels. A channel is a manager that takes care of scheduling the
tasklets, controlling them and suspending them. A thread is a process which runs hundreds of such
tasklets. We can create threads and tasklets in StacklessPython which is reimplementation of original
Python language. This can be downloaded from StacklessPython
---------------------------------------------------------------------------------------------------------------
Pythonxy:
This is pronounced as Python xy and written as Python(X,Y). This is the Python implementation that
we get after adding scientific and engineering related packages. We can download Pythonxy
from Pythonxy .
---------------------------------------------------------------------------------------------------------------
AnacondaPython:
When Python is redeveloped for handling large-scale data processing, predictive analytics and
scientific computing, it is called Anaconda Python. This implementation mainly focuses on large scale
of data. This can be downloaded from AnacondaPython .
---------------------------------------------------------------------------------------------------------------
Innards of Python :
Python is an object-oriented programming language like Java. Python is called an interpreted
language. Python uses code modules that are interchangeable instead of a single long list of
instructions that was standard for functional programming languages. The standard implementation
of Python is called “cpython”. It is the default and widely used implementation of Python.
Internal working of Python
Python doesn’t convert its code into machine code, something that hardware can understand. It
converts it into something called byte code. So within Python, compilation happens, but it’s just not
in a machine language. It is into byte code (.pyc or .pyo) and this byte code can’t be understood by
the CPU. So we need an interpreter called the Python virtual machine to execute the byte codes.
www.profajaypashankar.com Page 6 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
If an error occurs during this interpretation then the conversion is halted with an
error message.
Step 5: Within the PVM the bytecode is converted into machine code that is the
binary language consisting of 0’s and 1’s. This binary language is only understandable
by the CPU of the system as it is highly optimized for the machine code.
Step 6: In the last step, the final execution occurs where the CPU executes the
machine code and the final desired output will come as according to your program.
How Python Internally Works?
Code Editor: Code Editor is the first stage of programs where we write our source
code. This is human-readable code written according to Python’s syntax rules. It is
where the execution of the program starts first.
Source code: The code written by a programmer in the code editor is then saved as
a .py file in a system. This file of Python is written in human-readable language that
contains the instructions for the computer.
Compilation Stage: The compilation stage of Python is different from any other
programming language. Rather than compiling a source code directly into machine
code. python compiles a source code into a byte code. In the compilation stage
python compiler also checks for syntax errors. after checking all the syntax errors, if
no such error is found then it generates a .pyc file that contains bytecode.
Python Virtual Machine(PVM): The bytecode then goes into the main part of the
conversion is the Python Virtual Machine(PVM). The PVM is the main runtime engine
of Python. It is an interpreter that reads and executes the bytecode file, line by line.
Here In the Python Virtual Machine translate the byte code into machine code which
is the binary language consisting of 0s and 1s. The machine code is highly optimized
for the machine it is running on. This binary language is only understandable by the
CPU of a system.
Running Program: At last, the CPU executes the given machine code and the main
outcome of the program comes as performing task and computation you scripted at
the beginning of the stage in your code editor.
Python Libraries/Modules
When you import libraries or modules in your Python program. Firstly python checks if the given
module is built-in, and executes the corresponding C code. If the module is not built-in then the list
of directories is defined in sys. path. the directory of the input script, and directories listed in
the PYTHONPATH. if a .py file corresponds to the modules imported, Python creates a new module
object, On executing the code in the .py file within the object’s namespace. Then Python compiles
source code into byte code( the .pyc file), allowing for quicker execution
Compiler Vs Interpreter
In the system both the compiler and interpreter are the same they convert high-level code to
machine code. The interpreter converts source code into the machine when the program runs in a
system while a compiler converts the source code into machine code before the program runs in our
system.
Compiler Interpreter
www.profajaypashankar.com Page 7 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Compiler Interpreter
---------------------------------------------------------------------------------------------------------------
What is Python Interpreter:
Well if you are new to Python you have come across the word interpreters but before knowing about
Python interpreters, we need to what is an interpreter, what it will do, the advantages and
disadvantages of the interpreter, and so on. Well in this handy article, we will cover the Importance
of Interpreters and the pros and cons of using interpreters in Python.
---------------------------------------------------------------------------------------------------------------
Python Interpreter
Python is an interpreted language developed by Guido van Rossum in the year of 1991. As we all
know Python is one of the most high-level languages used today because of its massive versatility
and portable library & framework features. It is an interpreted language because it executes line-by-
line instructions. There are actually two way to execute python code one is in Interactive mode and
another thing is having Python prompts which is also called script mode. Python does not convert
high level code into low level code as many other programming languages do rather it will scan the
entire code into something called bytecode. every time when Python developer runs the code and
start to execute the compilation part execute first and then it generate an byte code which get
converted by PVM Python Virtual machine that understand the analogy and give the desired output.
---------------------------------------------------------------------------------------------------------------
Interpreted Languages: Perl, BASIC, Python, JavaScript, Ruby, PHP.
Compiled Languages: C, C++, C#, COBOL and CLEO.
---------------------------------------------------------------------------------------------------------------
What are Interpreters?
Interpreters are the computer program that will convert the source code or an high level language
into intermediate code (machine level language). It is also called translator in programming
terminology. Interpreters executes each line of statements slowly. This process is called
Interpretation. For example Python is an interpreted language, PHP, Ruby, and JavaScript.
Working of Interpreter
Example: Here is the simple Python program that takes two inputs as a and b and prints the sum
in the third variable which is c. It follows sequential as well as functional execution of programs
Python3
a=3
b=7
c=a+b
print(c) # output 10
Output
10
---------------------------------------------------------------------------------------------------------------
----
www.profajaypashankar.com Page 8 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
------------------------------------------------------------------------------------------------------------------
----
Comments in python
In Python, comments are used to explain the code and make it more readable. Comments are ignored
by the Python interpreter and are not executed as part of the program. There are two main types
of comments in Python: single-line comments and multi-line comments.
Single-line Comments
Single-line comments start with the hash character (#) and extend to the end of the line. They are
used for brief explanations or notes.
python
Copy code
# This is a single-line comment
print("Hello, World!") # This is an inline comment
Multi-line Comments
Python does not have a distinct syntax for multi-line comments like some other languages. Instead,
you can use a series of single-line comments or use multi-line strings (triple quotes) as comments.
While the latter method is not technically a comment, it is often used as such.
Using Single-line Comments:
python
Copy code
# This is a comment
# that spans multiple lines
# using single-line comments
Using Multi-line Strings:
You can use triple quotes (''' or """) to create a multi-line string that can act as a comment. This is
commonly used for docstrings but can also serve as a multi-line comment.
python
"""
This is a multi-line string
that spans multiple lines.
It can be used as a multi-line comment.
www.profajaypashankar.com Page 9 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
"""
print("Hello, World!")
------------------------------------------------------------------------------------------------------------------
----
Docstrings
Docstrings are a special kind of comment used to describe the purpose of a function, class, or module.
They are written using triple quotes and are placed right after the definition of a function, class, or
module.
python
def example_function():
"""
This is a docstring.
It describes what the function does.
"""
print("Hello, World!")
class ExampleClass:
"""
This is a docstring for the class.
It describes what the class does.
"""
pass
Docstrings can be accessed using the __doc__
------------------------------------------------------------------------------------------------------------------
----
Python Docstrings
When it comes to writing clean, well-documented code, Python developers have a secret weapon at
their disposal – docstrings. Docstrings, short for documentation strings, are vital in conveying the
purpose and functionality of Python functions, modules, and classes.
What are the docstrings in Python?
Python documentation strings (or docstrings) provide a convenient way of associating documentation
with Python modules, functions, classes, and methods. It’s specified in source code that is used,
like a comment, to document a specific segment of code. Unlike conventional source code
comments, the docstring should describe what the function does, not how.
Declaring Docstrings: The docstrings are declared using ”’triple single quotes”’ or
“”” triple double quotes “”” just below the class, method, or function declaration. All
functions should have a docstring.
Accessing Docstrings: The docstrings can be accessed using the __doc__ method of
the object or using the help function. The below examples demonstrate how to declare
and access a docstring.
What should a docstring look like?
The doc string line should begin with a capital letter and end with a period.
The first line should be a short description.
If there are more lines in the documentation string, the second line should be blank,
visually separating the summary from the rest of the description.
The following lines should be one or more paragraphs describing the object’s calling
conventions, side effects, etc.
Docstrings in Python
Below are the topics that we will cover in this article:
Triple-Quoted Strings
Google Style Docstrings
Numpydoc Style Docstrings
One-line Docstrings
Multi-line Docstrings
Indentation in Docstrings
Docstrings in Classes
Difference between Python comments and docstrings
Triple-Quoted Strings
This is the most common docstring format in Python. It involves using triple quotes (either single or
double) to enclose the documentation text. Triple-quoted strings can span multiple lines and are
often placed immediately below the function, class, or module definition
Example 1: Using triple single quotes
Python3
www.profajaypashankar.com Page 10 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
def my_function():
'''Demonstrates triple double quotes
docstrings and does nothing really.'''
return None
print("Using __doc__:")
print(my_function.__doc__)
print("Using help:")
help(my_function)
Output:
Using __doc__:
Demonstrates triple double quotes
docstrings and does nothing really.
Using help:
Help on function my_function in module __main__:
my_function()
Demonstrates triple double quotes
docstrings and does nothing really.
Example 2: Using triple-double quotes
Python3
def my_function():
' ' 'Demonstrates triple double quotes docstrings and does nothing really' ' '
return None
print("Using __doc__:")
print(my_function.__doc__)
print("Using help:")
help(my_function)
Output:
Using __doc__:
Demonstrates triple double quotes docstrings and does nothing really.
Using help:
Help on function my_function in module __main__:
my_function()
Demonstrates triple double quotes
docstrings and does nothing really.
Google Style Docstrings
Google style docstrings follow a specific format and are inspired by Google’s documentation style
guide. They provide a structured way to document Python code, including parameters, return
values, and descriptions.
Python3
Args:
a (int): The first number.
b (int): The second number.
Returns:
int: The product of a and b.
"""
return a * b
print(multiply_numbers(3,5))
Output
www.profajaypashankar.com Page 11 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
15
Parameters
----------
a : float
The dividend.
b : float
The divisor.
Returns
-------
float
The quotient of the division.
"""
if b == 0:
raise ValueError("Division by zero is not allowed.")
return a / b
print(divide_numbers(3,6))
Output
0.5
One-line Docstrings
As the name suggests, one-line docstrings fit in one line. They are used in obvious cases. The closing
quotes are on the same line as the opening quotes. This looks better for one-liners. For example:
Python3
return a**b
print(power.__doc__)
Output:
Returns arg1 raised to power arg2.
Multi-line Docstrings
Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank line,
followed by a more elaborate description. The summary line may be on the same line as the
opening quotes or on the next line. The example below shows a multi-line docstring.
Python3
Parameters:
a (int): The first number.
b (int): The second number.
Returns:
int: The sum of a and b.
www.profajaypashankar.com Page 12 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
"""
return a + b
print(add_numbers(3, 5))
Output:
8
Indentation in Docstrings
The entire docstring is indented the same as the quotes in its first line. Docstring processing tools will
strip a uniform amount of indentation from the second and further lines of the docstring, equal to
the minimum indentation of all non-blank lines after the first line. Any indentation in the first line of
the docstring (i.e., up to the first new line) is insignificant and removed. Relative indentation of
later lines in the docstring is retained.
Python3
class Employee:
"""
A class representing an employee.
Attributes:
name (str): The name of the employee.
age (int): The age of the employee.
department (str): The department the employee works in.
salary (float): The salary of the employee.
"""
Parameters:
name (str): The name of the employee.
age (int): The age of the employee.
department (str): The department the employee works in.
salary (float): The salary of the employee.
"""
self.name = name
self.age = age
self.department = department
self.salary = salary
Parameters:
raise_amount (float): The raise amount to increase the salary.
Returns:
str: A message indicating the promotion and new salary.
"""
self.salary += raise_amount
return f"{self.name} has been promoted! New salary: ${self.salary:.2f}"
def retire(self):
"""
Marks the employee as retired.
Returns:
str: A message indicating the retirement status.
"""
# Some implementation for retiring an employee
return f"{self.name} has retired. Thank you for your service!"
www.profajaypashankar.com Page 13 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Output:
class Employee
| A class representing an employee.
|
| Attributes:
| name (str): The name of the employee.
| age (int): The age of the employee.
| department (str): The department the employee works in.
| salary (float): The salary of the employee.
|
| Methods defined here:
|
| __init__(self, name, age, department, salary)
| Initializes an Employee object.
|
| Parameters:
| name (str): The name of the employee.
| age (int): The age of the employee.
| department (str): The department the employee works in.
| salary (float): The salary of the employee.
|
| promote(self, raise_amount)
| Promotes the employee and increases their salary.
|
| Parameters:
| raise_amount (float): The raise amount to increase the salary.
|
| Returns:
| str: A message indicating the promotion and new salary.
|
| retire(self)
| Marks the employee as retired.
|
| Returns:
| str: A message indicating the retirement status.
------------------------------------------------------------------------------------------------------------------
---
Docstrings in Classes
Let us take an example to show how to write docstrings for a class and the method ‘help’ is used to
access the docstring.
Python3
class ComplexNumber:
"""
This is a class for mathematical operations on complex numbers.
Attributes:
real (int): The real part of the complex number.
imag (int): The imaginary part of the complex number.
"""
Parameters:
real (int): The real part of the complex number.
imag (int): The imaginary part of the complex number.
"""
self.real = real
www.profajaypashankar.com Page 14 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
self.imag = imag
Parameters:
num (ComplexNumber): The complex number to be added.
Returns:
ComplexNumber: A complex number which contains the sum.
"""
re = self.real + num.real
im = self.imag + num.imag
Output:
Help on class ComplexNumber in module __main__:
class ComplexNumber(builtins.objects)
| This is a class for mathematical operations on complex numbers.
|
| Attributes:
| real (int): The real part of complex number.
| imag (int): The imaginary part of complex number.
|
| Methods defined here:
|
| __init__(self, real, imag)
| The constructor for ComplexNumber class.
|
| Parameters:
| real (int): The real part of complex number.
| imag (int): The imaginary part of complex number.
|
| add(self, num)
| The function to add two Complex Numbers.
|
| Parameters:
| num (ComplexNumber): The complex number to be added.
|
| Returns:
| ComplexNumber: A complex number which contains the sum.
Help on method add in module __main__:
add(self, num) unbound __main__.ComplexNumber method
The function to add two Complex Numbers.
Parameters:
num (ComplexNumber): The complex number to be added.
Returns:
ComplexNumber: A complex number which contains the sum.
Difference between Python comments, String, and Docstrings
String: In Python, a string is a sequence of characters enclosed within single quotes (‘ ‘) or double
quotes (” “). Strings are used to represent text data and can contain letters, numbers, symbols,
and whitespace. They are one of the fundamental data types in Python and can be manipulated
using various string methods.
www.profajaypashankar.com Page 15 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
You all must have got an idea about Python docstrings but have you ever wondered what is the
difference between Python comments and docstrings? Let’s have a look at them.
They are useful information that the developers provide to make the reader understand the source
code. It explains the logic or a part of it used in the code. It is written using
#
symbols.
------------------------------------------------------------------------------------------------------------------
----
------------------------------------------------------------------------------------------------------------
---
What is meant by Python IDLE?
An Integrated Development and Learning Environment, sometimes known as IDLE or even IDE, is
included with every Python setup. These are a group of programmes that make it easier to write
code. Although there are several IDEs available, Python IDLE is fairly basic, making it the ideal tool
for a beginner coder.
Python installs for Windows and Mac include Python IDLE. Python IDLE should be easy to locate and
download if you run Linux thanks to the package management. After installation, you may use
Python IDLE as a file editor or an interactive interpreter.
------------------------------------------------------------------------------------------------------------
---
What are the primary features of Python IDLE?
The principal functions of the Python IDLE are given below -
o Made entirely of Python code and the tkinter GUI toolkit.
o Search across numerous files (grep), alter text within editor windows, and search
across any window.
o Cross-platform, largely same behaviour on Windows, Unix, and macOS
o The interactive Python shell window has coloured input, output, and messages of
error.
o Debugging tool featuring stepping, permanent breakpoints, and namespace viewing.
o Very powerful debugger, dialogs, browsers, and configuration.
www.profajaypashankar.com Page 16 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
o Multi undo, Python colorizing, sensible indent, call hints, auto finish, and more
features are included in this multi-window text editor.
------------------------------------------------------------------------------------------------------------
--
Advantages of Python IDLE:
The following are some benefits of utilising Python IDLE:
o Python IDLE is an interactive shell that enables users to easily test and run short bits
of Python code without needing to create a whole programme.
o Python IDLE's code editor has features like syntax highlighting and code completion
that make it simpler and faster to write Python programmes.
o Python IDLE has a built-in debugger that enables programmers to walk through their
code and find faults and problems.
o Python IDLE may be used on Linux, macOS, and Windows thanks to its cross-platform
nature.
o Python IDLE is included with the Python installation, thus users don't need to install
any more programmes in order to begin coding in Python.
o Python IDLE is open-source, free software, which entitles users to use it with no any
limitations for both business and non-commercial uses.
---------------------------------------------------------------------------------------------------------------
Disadvantages of Python IDLE:
Using Python IDLE has certain drawbacks in addition to its numerous benefits, including:
o The Python IDLE IDE is a rudimentary one that lacks many of the more sophisticated
capabilities found in other IDEs. For instance, it lacks tools for project management,
version control, and code refactoring.
o When working with big codebases, Python IDLE is not as quick as other IDEs. When
processing a lot of data, it could become sluggish and unresponsive.
o Python IDLE lacks the sophisticated capabilities and tools necessary for handling
larger codebases, making it unsuitable for the development of large, complicated
projects.
o Compared to other IDEs, Python IDLE has fewer customization possibilities and is less
flexible. It could be challenging for users to alter the UI to suit their tastes.
o Python IDLE's capability and extensibility are constrained by the lack of numerous
third-party plugins.
o Python IDLE's user interface is not particularly contemporary or aesthetically pleasing.
For seasoned developers, this might not be an issue, but for new developers, it might
be a roadblock
------------------------------------------------------------------------------------------------------------
---
What is meant by the Interactive Interpreter?
The first-class area to test with Python code is the interactive interpreter, additionally known as the
shell. The shell is a basic study-eval-print (REPL) loop. Reads a Python assertion, evaluates the
result of that declaration, and prints the result to the display screen.
Then leap to examine the subsequent statement. The Python shell is a first-rate vicinity to attempt
small snippets of code. You can get the right of entry to it from your laptop's terminal or command
line app. Simplify your workflow with Python IDLE, which launches a Python shell as quickly as you
open i
------------------------------------------------------------------------------------------------------------------
----
Python Data Types
Every value has a datatype, and variables can hold values. Python is a powerfully composed language;
consequently, we don't have to characterize the sort of variable while announcing it. The interpreter
binds the value implicitly to its type.
1. a = 5
We did not specify the type of the variable a, which has the value five from an integer. The Python
interpreter will automatically interpret the variable as an integer.
We can verify the type of the program-used variable thanks to Python. The type() function in Python
returns the type of the passed variable.
Consider the following illustration when defining and verifying the values of various data types.
1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))
www.profajaypashankar.com Page 17 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Output:
<type 'int'>
<type 'str'>
<type 'float'>
--------------------------------------------------------------------------------------------------------------------
----
Standard data types
A variable can contain a variety of values. On the other hand, a person's id must be stored as an
integer, while their name must be stored as a string.
The storage method for each of the standard data types that Python provides is specified by Python.
The following is a list of the Python-defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
The data types will be briefly discussed in this tutorial section. We will talk about every single one of
them exhaustively later in this instructional exercise.
--------------------------------------------------------------------------------------------------------------------
----
Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities have a place
with a Python Numbers datatype. Python offers the type() function to determine a variable's data
type. The instance () capability is utilized to check whether an item has a place with a specific class.
When a number is assigned to a variable, Python generates Number objects. For instance,
1. a = 5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True
Python supports three kinds of numerical data.
www.profajaypashankar.com Page 18 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and so on. An integer
can be any length you want in Python. Its worth has a place with int.
o Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be
accurate to within 15 decimal places.
o Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y
signify the genuine and non-existent parts separately. The complex numbers like
2.14j, 2.0 + 2.3j, etc.
---------------------------------------------------------------------------------------------------------------------
---
Sequence Type
String
The sequence of characters in the quotation marks can be used to describe the string. A string can be
defined in Python using single, double, or triple quotes.
String dealing with Python is a direct undertaking since Python gives worked-in capabilities and
administrators to perform tasks in the string.
When dealing with strings, the operation "hello"+" python" returns "hello python," and the operator + is
used to combine two strings.
Because the operation "Python" *2 returns "Python," the operator * is referred to as a repetition
operator.
The Python string is demonstrated in the following example.
Example - 1
1. str = "string using double quotes"
2. print(str)
3. s = '''''A multiline
4. string'''
5. print(s)
Output:
string using double quotes
A multiline
string
Look at the following illustration of string handling.
Example - 2
1. str1 = 'hello javatpoint' #string str1
2. str2 = ' how are you' #string str2
3. print (str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. print (str1 + str2) #printing the concatenation of str1 and str2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
--------------------------------------------------------------------------------------------------------------------
----
List
Lists in Python are like arrays in C, but lists can contain data of different types. The things put away in
the rundown are isolated with a comma (,) and encased inside square sections [].
To gain access to the list's data, we can use slice [:] operators. Like how they worked with strings, the
list is handled by the concatenation operator (+) and the repetition operator (*).
Look at the following example.
Example:
1. list1 = [1, "hi", "Python", 2]
2. #Checking type of given list
3. print(type(list1))
4.
5. #Printing the list1
6. print (list1)
7.
8. # List slicing
9. print (list1[3:])
10.
www.profajaypashankar.com Page 19 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
11. # List slicing
12. print (list1[0:2])
13.
14. # List Concatenation using + operator
15. print (list1 + list1)
16.
17. # List repetation using * operator
18. print (list1 * 3)
Output:
[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
Tuple
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from various data
types. A parenthetical space () separates the tuple's components from one another.
Because we cannot alter the size or value of the items in a tuple, it is a read-only data structure.
Let's look at a straightforward tuple in action.
Example:
1. tup = ("hi", "Python", 2)
2. # Checking type of tup
3. print (type(tup))
4.
5. #Printing the tuple
6. print (tup)
7.
8. # Tuple slicing
9. print (tup[1:])
10. print (tup[0:1])
11.
12. # Tuple concatenation using + operator
13. print (tup + tup)
14.
15. # Tuple repatation using * operator
16. print (tup * 3)
17.
18. # Adding value to tup. It will throw an error.
19. t[2] = "hi"
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
www.profajaypashankar.com Page 20 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
6. # Accesing value using keys
7. print("1st name is "+d[1])
8. print("2nd name is "+ d[4])
9.
10. print (d.keys())
11. print (d.values())
Output:
1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
Boolean
True and False are the two default values for the Boolean type. These qualities are utilized to decide the
given assertion valid or misleading. The class book indicates this. False can be represented by the 0 or
the letter "F," while true can be represented by any value that is not zero.
Look at the following example.
1. # Python program to check the boolean type
2. print(type(True))
3. print(type(False))
4. print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
--------------------------------------------------------------------------------------------------------------------
---
Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change after creation),
and has remarkable components. The elements of a set have no set order; It might return the
element's altered sequence. Either a sequence of elements is passed through the curly braces and
separated by a comma to create the set or the built-in function set() is used to create the set. It can
contain different kinds of values.
Look at the following example.
1. # Creating Empty set
2. set1 = set()
3.
4. set2 = {'James', 2, 3,'Python'}
5.
6. #Printing Set value
7. print(set2)
8.
9. # Adding element to the set
10.
11. set2.add(10)
12. print(set2)
13.
14. #Removing element from the set
15. set2.remove(2)
16. print(set2)
Output:
{3, 'Python', 'James', 2}
{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}
--------------------------------------------------------------------------------------------------------------------
----
Python Mapping Types:
The mapping objects are used to map hash table values to arbitrary objects. In python there is mapping
type called dictionary. It is mutable.
The keys of the dictionary are arbitrary. As the value, we can use different kind of elements like lists,
integers or any other mutable type objects.
www.profajaypashankar.com Page 21 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Method len(d)
The len() method returns the number of elements in the dictionary.
Operation d[k]
It will return the item of d with the key ‘k’. It may raise KeyError if the key is not mapped.
Method iter(d)
This method will return an iterator over the keys of dictionary. We can also perform this taks by
using iter(d.keys()).
Method get(key[, default])
The get() method will return the value from the key. The second argument is optional. If the key is not
present, it will return the default value.
Method items()
It will return the items using (key, value) pairs format.
Method keys()
Return the list of different keys in the dictionary.
Method values()
Return the list of different values from the dictionary.
Method update(elem)
Modify the element elem in the dictionary.
Example Code
myDict = {'ten' : 10, 'twenty' : 20, 'thirty' : 30, 'forty' : 40}
print(myDict)
print(list(myDict.keys()))
print(list(myDict.values()))
myDict.update({'fifty' : 50})
print(myDict)
Output
{'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40}
['ten', 'twenty', 'thirty', 'forty']
[10, 20, 30, 40]
[('ten', 10), ('twenty', 20), ('thirty', 30), ('forty', 40)]
{'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50}
--------------------------------------------------------------------------------------------------------------------
----
Basic Elements of Python
Python is a versatile and widely-used programming language known for its readability and ease of use.
Here are some of the basic elements of Python:
1. Variables and Data Types
Variables
Variables are used to store data values. In Python, you don't need to declare a variable with a specific
type. The type is inferred from the value assigned to it.
python
Copy code
x=5
y = "Hello"
Data Types
Numbers: int, float, complex
String: str
Boolean: bool
List: list
Tuple: tuple
Set: set
Dictionary: dict
python
Copy code
a = 10 # int
b = 3.14 # float
c = 1 + 2j # complex
d = "Python" # str
e = True # bool
www.profajaypashankar.com Page 22 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
f = [1, 2, 3] # list
g = (4, 5, 6) # tuple
h = {1, 2, 3} # set
i = {"key": "value"} # dict
--------------------------------------------------------------------------------------------------------------------
----
2. Operators
Arithmetic Operators: +, -, *, /, %, **, //
Comparison Operators: ==, !=, >, <, >=, <=
Logical Operators: and, or, not
Assignment Operators: =, +=, -=, *=, /=
Bitwise Operators: &, |, ^, ~, <<, >>
python
Copy code
x=5
y=2
print(x + y) # 7
print(x > y) # True
print(x and y) # 2 (non-zero value is True)
--------------------------------------------------------------------------------------------------------------------
----
3. Control Flow Statements
Conditional Statements
python
Copy code
if x > y:
print("x is greater than y")
elif x == y:
print("x is equal to y")
else:
print("x is less than y")
--------------------------------------------------------------------------------------------------------------------
----
Loops
For Loop: Iterates over a sequence (like a list, tuple, dictionary, set, or string)
While Loop: Repeats as long as a condition is true
python
Copy code
# For loop
for i in range(5):
print(i)
# While loop
i=0
while i < 5:
print(i)
i += 1
--------------------------------------------------------------------------------------------------------------------
----
4. Functions
Functions are blocks of code that perform a specific task and can be reused.
python
Copy code
def greet(name):
return "Hello, " + name
print(greet("Alice"))
--------------------------------------------------------------------------------------------------------------------
----
5. Modules and Packages
Modules are files containing Python code (e.g., mymodule.py), and packages are directories containing
multiple modules.
python
Copy code
www.profajaypashankar.com Page 23 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
# mymodule.py
def greet(name):
return "Hello, " + name
# main.py
import mymodule
print(mymodule.greet("Alice"))
--------------------------------------------------------------------------------------------------------------------
----
6. Exception Handling
Python uses try, except, finally blocks to handle exceptions (errors).
python
Copy code
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This block is always executed")
--------------------------------------------------------------------------------------------------------------------
----
7. Classes and Objects
Python is an object-oriented programming language. You can define your own classes to create objects.
python
Copy code
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return "Hello, my name is " + self.name
p1 = Person("Alice", 30)
print(p1.greet())
--------------------------------------------------------------------------------------------------------------------
----
8. File I/O
Python can read from and write to files.
python
Copy code
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, World!")
print(math.sqrt(16))
These are the basic elements of Python that provide a foundation for writing and understanding Python
code.
www.profajaypashankar.com Page 24 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
--------------------------------------------------------------------------------------------------------------------------
----
Variables, Input Function, Output Statements, and Command Line Arguments:
Variables
Variables in Python are used to store data that can be referenced and manipulated later in the program.
Python is dynamically typed, meaning you don't need to declare the type of a variable explicitly. The type is
inferred from the value assigned to it.
Example:
python
Copy code
# Assigning values to variables
x=5
y = "Hello, World!"
z = 3.14
print("Name:", name)
print("Age:", age)
www.profajaypashankar.com Page 25 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
else:
print("No command line arguments provided.")
To run the script with command line arguments, use the terminal:
sh
Copy code
python script.py arg1 arg2 arg3
Expected Output:
yaml
Copy code
Script Name: script.py
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3
Summary
Variables: Used to store data values.
Input Function: input() is used to get input from the user.
Output Statements: print() is used to display output.
Command Line Arguments: Accessed via the sys.argv list, allowing parameters to be
passed to a script at execution time.
--------------------------------------------------------------------------------------------------------------------------
--
Operators in Python
Operators are special symbols used to perform operations on variables and values. Python supports several
types of operators:
1. Arithmetic Operators
+ (Addition): Adds two operands.
- (Subtraction): Subtracts the second operand from the first.
* (Multiplication): Multiplies two operands.
/ (Division): Divides the first operand by the second.
% (Modulus): Returns the remainder of the division.
** (Exponentiation): Raises the first operand to the power of the second.
// (Floor Division): Divides the first operand by the second and rounds down to the nearest
whole number.
Example:
python
Copy code
a = 10
b=3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.3333333333333335
print(a % b) # 1
print(a ** b) # 1000
print(a // b) # 3
--------------------------------------------------------------------------------------------------------------------------
--
2. Comparison Operators
== (Equal): Checks if two operands are equal.
!= (Not equal): Checks if two operands are not equal.
> (Greater than): Checks if the first operand is greater than the second.
< (Less than): Checks if the first operand is less than the second.
>= (Greater than or equal to): Checks if the first operand is greater than or equal to the
second.
www.profajaypashankar.com Page 26 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
<= (Less than or equal to): Checks if the first operand is less than or equal to the second.
Example:
python
Copy code
a=5
b = 10
print(a == b) # False
print(a != b) # True
print(a > b) # False
print(a < b) # True
print(a >= b) # False
print(a <= b) # True
--------------------------------------------------------------------------------------------------------------------------
--
3. Logical Operators
and: Returns True if both operands are true.
or: Returns True if at least one operand is true.
not: Returns True if the operand is false.
Example:
python
Copy code
a = True
b = False
a += 5
print(a) # 15
a -= 3
print(a) # 12
a *= 2
print(a) # 24
a /= 4
print(a) # 6.0
a %= 5
print(a) # 1.0
a **= 3
www.profajaypashankar.com Page 27 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
print(a) # 1.0
a //= 1
print(a) # 1.0
--------------------------------------------------------------------------------------------------------------------------
--
5. Bitwise Operators
& (AND): Sets each bit to 1 if both bits are 1.
| (OR): Sets each bit to 1 if one of the two bits is 1.
^ (XOR): Sets each bit to 1 if only one of the two bits is 1.
~ (NOT): Inverts all the bits.
<< (Zero fill left shift): Shifts the bits of the first operand left by the number of positions
specified by the second operand.
>> (Signed right shift): Shifts the bits of the first operand right by the number of positions
specified by the second operand.
Example:
python
Copy code
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
www.profajaypashankar.com Page 28 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Right-Associative Example:
python
Copy code
result = 2 ** 3 ** 2 # 2 ** (3 ** 2) = 2 ** 9 = 512
print(result) # 512
Summary
Operators: Symbols that perform operations on variables and values.
Precedence of Operators: Determines the order in which operators are evaluated.
Associativity of Operators: Determines the order in which operators of the same
precedence are evaluated, typically left to right except for exponentiation.
------------------------------------------------------------------------------------------------------------------------
CHAPTER II: CONTROL STATEMENTS
Topics Covered:
: The if statement, The if … else Statement, The if … elif … else Statement, Loop Statement- while loop, for
loop, Infinite loop, Nested loop, The else suite, break statement, continue statement, pass statement,
assert statement, return statement.
-------------------------------------------------------------------------------------------------------------------------
---
Python If ... Else
Elif
The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to
screen that "a and b are equal".
Else
www.profajaypashankar.com Page 29 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also the elif condition is not true, so we
go to the else condition and print to screen that "a is greater than b".
You can also have an else without the elif:
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Example
One line if statement:
if a > b: print("a is greater than b")
And
The and keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
The or keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
www.profajaypashankar.com Page 30 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
print("At least one of the conditions is True")
-------------------------------------------------------------------------------------------------------------------------
----
Not
The not keyword is a logical operator, and is used to reverse the result of the conditional statement:
Example
Test if a is NOT greater than b:
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested If
You can have if statements inside if statements, this is called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
if b > a:
pass
Python assert keyword
Python Assertions in any programming language are the debugging tools that help in the smooth flow of
code. Assertions are mainly assumptions that a programmer knows or always wants to be true and hence
puts them in code so that failure of these doesn’t allow the code to execute further.
Assert Keyword in Python
In simpler terms, we can say that assertion is the boolean expression that checks if the statement is True or
False. If the statement is true then it does nothing and continues the execution, but if the statement is
False then it stops the execution of the program and throws an error.
Flowchart of Python Assert Statement
www.profajaypashankar.com Page 31 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
# initializing number
a=4
b=0
Output:
The value of a / b is :
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Input In [19], in <cell line: 10>()
8 # using assert to check for 0
9 print("The value of a / b is : ")
---> 10 assert b != 0
11 print(a / b)
AssertionError:
Python assert keyword with an error message
This code is trying to demonstrate the use of assert in Python by checking whether the value of b is 0 before
performing a division operation. a is initialized to the value 4, and b is initialized to the value 0. The
www.profajaypashankar.com Page 32 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
program prints the message “The value of a / b is: “.The assert statement checks whether b is not equal to
0. Since b is 0, the assert statement fails and raises an AssertionError with the message “Zero Division
Error”.
Since an exception is raised by the failed assert statement, the program terminates and does not continue
to execute the print statement on the next line.
Assert Inside a Function
The assert statement is used inside a function in this example to verify that a rectangle’s length and width
are positive before computing its area. The assertion raises an AssertionError with the message “Length
and width must be positive” if it is false. If the assertion is true, the function returns the rectangle’s area;
if it is false, it exits with an error. To show how to utilize assert in various situations, the function is called
twice, once with positive inputs and once with negative inputs.
Python3
Output:
AssertionError: Length and widthmust be positive
Assert with boolean Condition
In this example, the assert statement checks whether the boolean condition x < y is true. If the assertion
fails, it raises an AssertionError. If the assertion passes, the program continues and prints the values of x
and y.
Python3
# Initializing variables
x = 10
y = 20
Output:
x = 10
y = 20
Assert Type of Variable in Python
In this example, the assert statements check whether the types of the variables a and b are str and int,
respectively. If any of the assertions fail, it raises an AssertionError. If both assertions pass, the program
continues and prints the values of a and b.
Python3
www.profajaypashankar.com Page 33 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
# Initializing variables
a = "hello"
b = 42
Output:
a = hello
b = 42
Asserting dictionary values
In this example, the assert statements check whether the values associated with the keys “apple”, “banana”,
and “cherry” in the dictionary my_dict are 1, 2, and 3, respectively. If any of the assertions fail, it raises
an AssertionError. If all assertions pass, the program continues and prints the contents of the dictionary.
Python3
# Initializing a dictionary
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
Output:
My dictionary contains the following key-value pairs:
{'apple': 1, 'banana': 2, 'cherry': 3}
Practical Application
This has a much greater utility in the Testing and Quality Assurance roles in any development domain.
Different types of assertions are used depending on the application. Below is a simpler demonstration of a
program that only allows only the batch with all hot food to be dispatched, else rejects the whole batch.
Python3
Output:
40 is O.K
26 is O.K
39 is O.K
30 is O.K
Runtime Exception:
AssertionError: Batch is Rejected
www.profajaypashankar.com Page 34 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Why Use Python Assert Statement?
In Python, the assert statement is a potent debugging tool that can assist in identifying mistakes and
ensuring that your code is operating as intended. Here are several justifications for using assert:
1. Debugging: Assumptions made by your code can be verified with the assert statement.
You may rapidly find mistakes and debug your program by placing assert statements
throughout your code.
2. Documentation: The use of assert statements in your code might act as documentation.
Assert statements make it simpler for others to understand and work with your code since
they explicitly describe the assumptions that your code is making.
3. Testing: In order to ensure that certain requirements are met, assert statements are
frequently used in unit testing. You can make sure that your code is working properly and
that any changes you make don’t damage current functionality by incorporating assert
statements in your tests.
4. Security: You can use assert to check that program inputs comply with requirements and
validate them. By doing so, security flaws like buffer overflows and SQL injection attacks
may be avoided.
www.profajaypashankar.com Page 35 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Output
The new created array is : 1 2 3
www.profajaypashankar.com Page 36 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Now we will see how to use array in Python 3.8 with example.
Adding Elements to a Array
Elements can be added to the Python Array by using built-in insert() function. Insert is used to insert one
or more data elements into an array. Based on the requirement, a new element can be added at
the beginning, end, or any given index of array. append() is also used to add the value mentioned
in its arguments at the end of the Python array.
Below, code first imports the array module as Python import array as arr. Then, it creates an array of
integers named a with elements [1, 2, 3]. In below code Python print array as array is printed
before and after inserting the integer 4 at index 1. Similarly, an array of doubles named b with
elements [2.5, 3.2, 3.3] is created and printed before and after appending the double 4.4 to the
array.
Python
import array as arr
a = arr.array('i', [1, 2, 3])
print("Array before insertion : ", end=" ")
for i in range(0, 3):
print(a[i], end=" ")
print()
a.insert(1, 4)
print("Array after insertion : ", end=" ")
for i in (a):
print(i, end=" ")
print()
b = arr.array('d', [2.5, 3.2, 3.3])
print("Array before insertion : ", end=" ")
for i in range(0, 3):
print(b[i], end=" ")
print()
b.append(4.4)
print("Array after insertion : ", end=" ")
for i in (b):
print(i, end=" ")
print()
www.profajaypashankar.com Page 37 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Output
Array before insertion : 1 2 3
Array after insertion : 1 4 2 3
Array before insertion : 2.5 3.2 3.3
Array after insertion : 2.5 3.2 3.3 4.4
Complexities for Adding elements to the Arrays
Time Complexity: O(1)/O(n) ( O(1) – for inserting elements at the end of the array, O(n) – for inserting
elements at the beginning of the array and to the full array
Auxiliary Space: O(1)
Accessing Elements from the Array
In order to access the array items refer to the index number. Use the index operator [ ] to access an item
in a array in Python. The index must be an integer.
Below, code shows first how to Python import array and use of indexing to access elements in arrays.
The a[0] expression accesses the first element of the array a, which is 1. The a[3] expression
accesses the fourth element of the array a, which is 4. Similarly, the b[1] expression accesses the
second element of the array b, which is 3.2, and the b[2] expression accesses the third element of
the array b, which is 3.3.
Python
import array as arr
a = arr.array('i', [1, 2, 3, 4, 5, 6])
print("Access element is: ", a[0])
print("Access element is: ", a[3])
b = arr.array('d', [2.5, 3.2, 3.3])
print("Access element is: ", b[1])
print("Access element is: ", b[2])
Output
Access element is: 1
Access element is: 4
Access element is: 3.2
Access element is: 3.3
print("\r")
print("The popped element is : ", end="")
print(arr.pop(2))
print("The array after popping is : ", end="")
for i in range(0, 4):
print(arr[i], end=" ")
print("\r")
www.profajaypashankar.com Page 38 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
arr.remove(1)
print("The array after removing is : ", end="")
for i in range(0, 3):
print(arr[i], end=" ")
Output
The new created array is : 1 2 3 1 5
The popped element is : 3
The array after popping is : 1 2 1 5
The array after removing is : 2 1 5
Complexities for Removing elements in the Arrays
Time Complexity: O(1)/O(n) ( O(1) – for removing elements at the end of the array, O(n) – for removing
elements at the beginning of the Python create array and to the full array
Auxiliary Space: O(1)
Slicing of an Array
In Python array, there are multiple ways to print the whole array with all the elements, but to print a
specific range of elements from the array, we use Slice operation. Slice operation is performed on
array with the use of colon(:). To print elements from beginning to a range use [:Index], to print
elements from end use [:-Index], to print elements from specific Index till the end use [Index:], to
print elements within a range, use [Start Index:End Index] and to print whole List with the use of
slicing operation, use [:]. Further, to print whole array in reverse order, use [::-1].
This code employs slicing to extract elements or subarrays from an array. It starts with an initial array of
integers and creates an array from the list. The code slices the array to extract elements from
index 3 to 8, from index 5 to the end, and the entire array and In below code Python print array as
The sliced arrays are then printed to demonstrate the slicing operations.
Python
import array as arr
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = arr.array('i', l)
print("Initial Array: ")
for i in (a):
print(i, end=" ")
Sliced_array = a[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_array)
Sliced_array = a[5:]
print("\nElements sliced from 5th "
"element till the end: ")
print(Sliced_array)
Sliced_array = a[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_array)
Output
Initial Array:
1 2 3 4 5 6 7 8 9 10
Slicing elements in a range 3-8:
array('i', [4, 5, 6, 7, 8])
www.profajaypashankar.com Page 39 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Elements sliced from 5th element till the end:
array('i', [6, 7, 8, 9, 10])
print("\r")
print("The index of 1st occurrence of 2 is : ", end="")
print(arr.index(2))
print("The index of 1st occurrence of 1 is : ", end="")
print(arr.index(1))
Output
The new created array is : 1 2 3 1 2 5
The index of 1st occurrence of 2 is : 1
The index of 1st occurrence of 1 is : 0
Complexities for searching elements in the Arrays
Time Complexity: O(n)
Auxiliary Space: O(1)
Updating Elements in a Array
In order to update an element in the array we simply reassign a new value to the desired index we want to
update.
Example: This code illustrates the functionality of modifying elements within an array using indexing. It
imports the array module, creates an array of integers, and prints the initial array. Then, it
modifies two elements of the array at specific indexes and prints the updated array. This serves to
demonstrate how indexing allows for dynamic manipulation of array contents.
Python
import array
arr = array.array('i', [1, 2, 3, 1, 2, 5])
print("Array before updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
print("\r")
arr[2] = 6
print("Array after updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
print()
arr[4] = 8
print("Array after updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
Output
Array before updation : 1 2 3 1 2 5
Array after updation : 1 2 6 1 2 5
Array after updation : 1 2 6 1 8 5
Complexities for updating elements in the Arrays
Time Complexity: O(1)
Auxiliary Space: O(1)
Different Operations on Python Arrays
www.profajaypashankar.com Page 40 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Counting Elements in a Array
In order to count elements in an array we need to use count method.
Example: The code demonstrates how to determine the frequency of a particular element within an array.
It imports the array module, creates an array of integers, to create arrays in Python and counts
the occurrences of the number 2 using the count() method, and finally prints the result. This code
snippet effectively showcases the ability to analyze the distribution of elements in arrays.
Python
import array
my_array = array.array('i', [1, 2, 3, 4, 2, 5, 2])
count = my_array.count(2)
print("Number of occurrences of 2:", count)
Output
Number of occurrences of 2: 3
Complexities for counting elements in the Arrays
Time Complexity: O(n)
Auxiliary Space: O(1)
Reversing Elements in a Array
In order to reverse elements of an array we need to simply use reverse method.
Example: The presented code demonstrates the functionality of reversing the order of elements within an
array using the reverse() method. It imports the array module, creates an array of integers,
prints the original array, reverses the order of elements using reverse(), and then prints the
reversed array. This effectively illustrates the ability to modify the arrangement of elements in an
array.
Python
import array
my_array = array.array('i', [1, 2, 3, 4, 5])
print("Original array:", *my_array)
my_array.reverse()
print("Reversed array:", *my_array)
Output
Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1
Complexities for reversing elements in the Arrays:
Time Complexity: O(n)
Auxiliary Space: O(1)
Extend Element from Array
In the article, we will cover the python list extend() and try to understand the Python list extend().
What is extend element from array?
In Python, an array is used to store multiple values or elements of the same datatype in a single variable.
The extend() function is simply used to attach an item from iterable to the end of the array. In
simpler terms, this method is used to add an array of values to the end of a given or existing
array.
Syntax of list extend()
The syntax of the extend() method:
list.extend(iterable)
Here, all the element of iterable are added to the end of list1
Example 1:
The provided code demonstrates the capability of extending an array to include additional elements. It
imports the array module using an alias, creates an array of integers, prints the array before
extension, extends the array using the extend() method, and finally prints the extended array.
This concisely illustrates the ability to add elements to an existing array structure
Python
import array as arr
a = arr.array('i', [1, 2, 3,4,5])
print("The before array extend : ", end =" ")
for i in range (0, 5):
print()
a.extend([6,7,8,9,10])
www.profajaypashankar.com Page 41 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
print("\nThe array after extend :",end=" ")
for i in range(0,10):
print(a[i],end=" ")
print()
Output
The before array extend : 1 2 3 4 5
print(a[i],end=" ")
print()
a.extend([7,8,9,10,11,12])
print("\nThe After extend array is :",end=" ")
for i in range(0,12):
print(a[i],end=" ")
print()
b = arr.array('d', [2.1,2.2,2.3,2.4,2.5,2.6])
for i in range(0,6):
print(b[i],end=" ")
print()
b.extend([2.6,2.7,2.8,2.9])
for i in range(0,9+1):
print(b[i],end=" ")
print()
Output
The Before extend array is : 1 2 3 4 5 6
The before extend array is : 2.1 2.2 2.3 2.4 2.5 2.6
www.profajaypashankar.com Page 42 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Time Complexity: O(1)
Auxiliary Space: O(1)
Array in Python | Set 1 (Introduction and Functions)
Last Updated : 19 Sep, 2023
Other than some generic containers like lists, Python in its definition can also handle containers with
specified data types. The array can be handled in Python by a module named “array“. They can be
useful when we have to manipulate only specific data type values.
Properties of Arrays
Each array element is of the same data type and size. For example: For an array of integers
with the int data type, each element of the array will occupy 4 bytes.
Elements of the array are stored in contiguous memory locations.
Operations on Array in Python
Below are some operations that can be performed in an array:
append()
insert()
pop()
remove()
index()
reverse()
array(data type, value list) in Python
This function is used to create an array with data type and value list specified in its arguments. Some data
types are mentioned in the table below.
www.profajaypashankar.com Page 43 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
This function is used to add the value mentioned in its arguments at the end of the array. In this example,
we are adding an element at the end of the array.
Python3
Output
The new created array is : 1 2 3
The appended array is : 1 2 3 4
Array insert(i,x) Method in Python
This function is used to add the value(x) at the ith position specified in its argument. In this example, we
are inserting an element at a specified index in an array.
Python3
arr.insert(2, 5)
print("\r")
Output
The new created array is : 1 2 3
The array after insertion is : 1 2 5 3
Time Complexity: The initialization of the array takes O(n) time, where n is the number of elements in
the array. The for loops used for printing the original array and the appended/inserted array takes
O(n) time each, where n is the number of elements in the array. The append() method takes O(1)
time as it adds the new element at the end of the array in constant time. The insert() method
takes O(n) time in the worst case as it may have to shift all the elements to the right of the given
position by one index, where n is the number of elements in the array. Therefore, the overall time
complexity of the code is O(n) + O(n) + O(1) + O(n) = O(n).
www.profajaypashankar.com Page 44 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Auxiliary Space: The array data structure used for initialization, append() and insert() methods requires a
fixed amount of space for each element in the array. The space used by the print statements is
negligible compared to the space used by the array. Therefore, the auxiliary space complexity of
the code is O(n), where n is the number of elements in the array.
array pop() Method in Python
This function removes the element at the position mentioned in its argument and returns it. In this
example, we are removing an element mentioned at a particular index.
Python3
print("\r")
Output
The new created array is : 1 2 3 1 5
The popped element is : 3
The array after popping is : 1 2 1 5
Array remove() in Python
This function is used to remove the first occurrence of the value mentioned in its arguments. In this
example, we are removing the first occurrence of 1 from a given array.
Python3
print("\r")
Output
The new created array is : 1 2 3 1 5
The array after removing is : 2 3 1 5
Array index() Method
www.profajaypashankar.com Page 45 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
This function returns the index of the first occurrence of the value mentioned in the arguments. In this
example, we are finding the index of 1st occurrence of 2 and printing it.
Python3
print("\r")
Output
The new created array is : 1 2 3 1 2 5
The index of 1st occurrence of 2 is : 1
print("\r")
Output
The new created array is : 1 2 3 1 2 5
The array after reversing is : 5 2 1 3 2 1
Where can arrays be used?
Arrays should be used where the number of elements to be stored is already known.
Arrays are commonly used in computer programs to organize data so that a related set of
values can be easily sorted or searched.
Generally, when we require very fast access times, we usually prefer arrays since they
provide O(1) access times.
Arrays work well when we have to organize data in multidimensional format. We can
declare arrays of as many dimensions as we want.
If the index of the element to be modified is known beforehand, it can be efficiently
modified using arrays due to quick access time and mutability.
www.profajaypashankar.com Page 46 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
-----------------------------------------------------------------------------------------------------------------------
NumPy Array in Python
Python lists are a substitute for arrays, but they fail to deliver the performance required while computing
large sets of numerical data.
To address this issue we use the NumPy library of Python. NumPy offers an array object called ndarray.
They are similar to standard Python sequences but differ in certain key factors.
What is a NumPy Array?
NumPy array is a multi-dimensional data structure that is the core of scientific computing in Python.
All values in an array are homogenous (of the same data type).
They offer automatic vectorization and broadcasting.
They provide efficient memory management, ufuncs(universal functions), support various data types, and
are flexible with Indexing and slicing.
Dimensions in Arrays
NumPy arrays can have multiple dimensions, allowing users to store data in multilayered structures.
Dimensionalities of array:
Name Example
import numpy as np
arr = np.array([1,2,3,4,5,6])
Output
[1,2,3,4,5,6]
or
numpyArr = np.array([1,2,3,4])
The list is passed to the array() method which then returns a array with the same elements.
Example 1: The following example shows how to initialize a array from a list.
Python3
import numpy as np
li = [1, 2, 3, 4]
numpyArr = np.array(li)
print(numpyArr)
Output:
[1 2 3 4]
The resulting array looks the same as a list but is a NumPy object.
www.profajaypashankar.com Page 47 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Example 2: Let’s take an example to check whether the numpyArr is a NumPy object or not. In this
example, we are using the array() function to convert the list into a NumPy array and then check if
it’s a NumPy object or not.
Python3
import numpy as np
li = [1, 2, 3, 4]
numpyArr = np.array(li)
Output:
li = [1, 2, 3, 4] and type(li) = <class 'list'>
numpyArr = [1 2 3 4] and type(numpyArr) = <class 'numpy.ndarray'>
As you can see li is a list object whereas numpyArr is an array object of NumPy.
Create a NumPy Array from a Tuple
You can make ndarray from a tuple using a similar syntax.
tup = (1,2,3,4)
numpyArr = np.array(tup)
or
numpyArr = np.array((1,2,3,4))
The following example illustrates how to create a array from a tuple. Here, we are using the array()
function to convert the tuple to a NumPy array.
Python3
import numpy as np
tup = (1, 2, 3, 4)
numpyArr = np.array(tup)
Output:
tup = (1, 2, 3, 4) and type(tup) = <class 'tuple'>
numpyArr = [1 2 3 4] and type(numpyArr) = <class 'numpy.ndarray'>
Note that the value of numpyArr remains the same for either of the two conversions.
NumPy Arrays vs Inbuilt Python Sequences
Unlike lists, arrays are of fixed size, and changing the size of an array will lead to the
creation of a new array while the original array will be deleted.
All the elements in an array are of the same type.
Arrays are faster, more efficient, and require less syntax than standard Python sequences.
Note: Various scientific and mathematical Python-based packages use Numpy. They might take input as an
inbuilt Python sequence but they are likely to convert the data into a NumPy array to attain faster
processing. This explains the need to understand NumPy.
Why is the Numpy Array so Fast?
Numpy arrays are written mostly in C language. Being written in C, the arrays are stored in contiguous
memory locations which makes them accessible and easier to manipulate. This means that you can
get the performance level of a C code with the ease of writing a Python program.
1. Homogeneous Data: Arrays store elements of the same data type, making them more
compact and memory-efficient than lists.
2. Fixed Data Type: Arrays have a fixed data type, reducing memory overhead by
eliminating the need to store type information for each element.
3. Contiguous Memory: Arrays store elements in adjacent memory locations, reducing
fragmentation and allowing for efficient access.
www.profajaypashankar.com Page 48 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
---------------------------------------------------------------------------------------------------------------------------
www.profajaypashankar.com Page 49 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
CHAPTER IV: FUNCTIONS
Topics Covered:
Functions: Function definition and call, Returning Results, Returning Multiple Values from a Function, Built-in
Functions, Difference between a Function and a Method, Pass Value by Object Reference, Parameters and
Arguments, Recursive Functions, Anonymous or Lambda Functions. Modules in Python.
Python Functions is a block of statements that return the specific task. The idea is to put some commonly
or repeatedly done tasks together and make a function so that instead of writing the same code
again and again for different inputs, we can do the function calls to reuse code contained in it over
and over again.
Some Benefits of Using Functions
Increase Code Readability
Increase Code Reusability
Python Function Declaration
The syntax to declare a function is:
www.profajaypashankar.com Page 50 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
If you have experience in C/C++ or Java then you must be thinking about the return type of the
function and data type of arguments. That is possible in Python as well (specifically for Python 3.5
and above).
Python Function Syntax with Parameters
def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression
The following example uses arguments and parameters that you will learn later in this article so
you can come back to it again if not understood.
Python
def add(num1: int, num2: int) -> int:
"""Add two numbers"""
num3 = num1 + num2
return num3
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Output:
The addition of 5 and 15 results 20.
Note: The following examples are defined using syntax 1, try to convert them in syntax 2 for
practice.
Python
# some more functions
def is_prime(n):
if n in [2, 3]:
return True
if (n == 1) or (n % 2 == 0):
return False
r=3
while r * r <= n:
if n % r == 0:
return False
r += 2
return True
print(is_prime(78), is_prime(79))
Output:
False True
------------------------------------------------------------------------------------------------------
Python Function Arguments
Arguments are the values passed inside the parenthesis of the function. A function can have any
number of arguments separated by a comma.
In this example, we will create a simple function in Python to check whether the number passed
as an argument to the function is even or odd.
Python
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
www.profajaypashankar.com Page 51 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Types of Python Function Arguments
Python supports various types of arguments that can be passed at the time of the function call. In
Python, we have the following function argument types in Python:
Default argument
Keyword arguments (named arguments)
Positional arguments
Arbitrary arguments (variable-length arguments *args and **kwargs)
Let’s discuss each type in detail.
------------------------------------------------------------------------------------------------------
Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided in the
function call for that argument. The following example illustrates Default arguments to write
functions in Python.
Python
# Python program to demonstrate
# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# Keyword arguments
student(firstname='India', lastname='Practice')
student(lastname='Practice', firstname='India')
Output:
India Practice
India Practice
------------------------------------------------------------------------------------------------------
Positional Arguments
We used the Position argument during the function call so that the first argument (or value) is
assigned to name and the second argument (or value) is assigned to age. By changing the position,
or if you forget the order of the positions, the values can be used in the wrong places, as shown
in the Case-2 example below, where 27 is assigned to the name and Suraj is assigned to the age.
Python
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
www.profajaypashankar.com Page 52 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
nameAge(27, "Suraj")
Output:
Case-1:
Hi, I am Suraj
My age is 27
Case-2:
Hi, I am 27
My age is Suraj
------------------------------------------------------------------------------------------------------
Arbitrary Keyword Arguments
In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of
arguments to a function using special symbols. There are two special symbols:
*args in Python (Non-Keyword Arguments)
**kwargs in Python (Keyword Arguments)
Example 1: Variable length non-keywords argument
Python
# Python program to illustrate
# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
# Driver code
myFun(first='India', mid='for', last='India')
Output:
first == India
mid == for
last == India
Docstring
The first string after the function is called the Document string or Docstring in short. This is used
to describe the functionality of the function. The use of docstring in functions is optional but it is
considered a good practice.
The below syntax can be used to print out the docstring of a function.
Syntax: print(function_name.__doc__)
Example: Adding Docstring to the function
Python
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
"""Function to check if the number is even or odd"""
if (x % 2 == 0):
print("even")
else:
www.profajaypashankar.com Page 53 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
print("odd")
def f1():
s = 'I love India'
def f2():
print(s)
f2()
# Driver's code
f1()
Output:
I love India
Anonymous Functions in Python
In Python, an anonymous function means that a function is without a name. As we already know
the def keyword is used to define the normal functions and the lambda keyword is used to create
anonymous functions.
Python
# Python code to illustrate the cube of a number
# using lambda function
def cube(x): return x*x*x
print(cube(7))
print(cube_v2(7))
Output:
343
343
Recursive Functions in Python
Recursion in Python refers to when a function calls itself. There are many instances when you
have to build a recursive function to solve Mathematical and Recursive Problems.
Using a recursive function should be done with caution, as a recursive function can become like a
non-terminating loop. It is better to check your exit statement while creating a recursive function.
Python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(4))
Output
24
Here we have created a recursive function to calculate the factorial of the number. You can see
the end statement for this function is when n is equal to 0.
Return Statement in Python Function
www.profajaypashankar.com Page 54 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
The function return statement is used to exit from a function and go back to the function caller
and return the specified value or data item to the caller. The syntax for the return statement
is:
return [expression_list]
The return statement can consist of a variable, an expression, or a constant which is returned at
the end of the function execution. If none of the above is present with the return statement a None
object is returned.
Example: Python Function Return Statement
Python
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))
Output:
4
16
Pass by Reference and Pass by Value
One important thing to note is, in Python every variable name is a reference. When we pass a
variable to a function Python, a new reference to the object is created. Parameter passing in Python
is the same as reference passing in Java.
Python
# Here x is a new reference to same list lst
def myFun(x):
x[0] = 20
www.profajaypashankar.com Page 55 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
x = 20
# Driver code
x=2
y=3
swap(x, y)
print(x)
print(y)
Output:
2
3
www.profajaypashankar.com Page 56 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Example:
Let’s create a simple calc.py in which we define two functions, one add and another subtract.
Python3
-----------------------------------------------------------------------------------------------------------------------
print(calc.add(10, 2))
Output:
12
-----------------------------------------------------------------------------------------------------------------------
Python Import From Module
Python’s from statement lets you import specific attributes from a module without importing the module as
a whole.
Import Specific Attributes from a Python module
Here, we are importing specific sqrt and factorial attributes from the math module.
Python3
Output:
4.0
720
-----------------------------------------------------------------------------------------------------------------------
Import all Names
The * symbol used with the import statement is used to import all the names from a module to a current
namespace.
Syntax:
from module_name import *
What does import * do in Python?
The use of * has its advantages and disadvantages. If you know exactly what you will be needing from the
module, it is not recommended to use *, else do so.
www.profajaypashankar.com Page 57 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Python3
Output
4.0
720
-----------------------------------------------------------------------------------------------------------------------
Locating Python Modules
Whenever a module is imported in Python the interpreter looks for several locations. First, it will check for
the built-in module, if not found then it looks for a list of directories defined in the sys.path. Python interpreter
searches for the module in the following manner –
First, it searches for the module in the current directory.
If the module isn’t found in the current directory, Python then searches each directory in the
shell variable PYTHONPATH. The PYTHONPATH is an environment variable, consisting of a list
of directories.
If that also fails python checks the installation-dependent list of directories configured at the
time Python is installed.
# importing sys.path
print(sys.path)
Output:
[‘/home/nikhil/Desktop/India’, ‘/usr/lib/python38.zip’, ‘/usr/lib/python3.8’, ‘/usr/lib/python3.8/lib-dynload’,
”, ‘/home/nikhil/.local/lib/python3.8/site-packages’, ‘/usr/local/lib/python3.8/dist-packages’,
‘/usr/lib/python3/dist-packages’, ‘/usr/local/lib/python3.8/dist-packages/IPython/extensions’,
‘/home/nikhil/.ipython’]
-----------------------------------------------------------------------------------------------------------------
Renaming the Python Module
We can rename the module while importing it using the keyword.
Syntax: Import Module_name as Alias_name
Python3
Output
4.0
720
-----------------------------------------------------------------------------------------------------------------------
Python Built-in modules
There are several built-in modules in Python, which you can import whenever you like.
www.profajaypashankar.com Page 58 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Python3
# Sine of 2 radians
print(math.sin(2))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
Output:
5.0
3.14159265359
www.profajaypashankar.com Page 59 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87
-----------------------------------------------------------------------------------------------------------------------
CHAPTER V: STRINGS
Topics covered: Creating Strings, Functions of Strings, working with Strings, Formatting Strings, Finding
the Number of Characters and Words, Inserting Substrings into a String.
-----------------------------------------------------------------------------------------------------------------------
A String is a data structure in Python Programming that represents a sequence of characters. It is an
immutable data type, meaning that once you have created a string, you cannot change it. Python String are
used widely in many different applications, such as storing and manipulating text data, representing names,
addresses, and other types of data that can be represented as text.
Python Programming does not have a character data type, a single character is simply a string with a length
of 1. Now, let’s see the Python string syntax:
Syntax of String Data Type in Python
string_variable = 'Hello, world!'
Example of string data type in Python
Python
string_0 = "A Computer Science portal for geeks"
print(string_0)
print(type(string_0))
Output:
A Computer Science portal for geeks
<class 'str'>
Create a String in Python
Strings in Python can be created using single quotes or double quotes or even triple quotes. Let us see
how we can define a string in Python or how to write string in Python.
Example:
In this example, we will demonstrate different ways to create a Python String. We will create a string using
single quotes (‘ ‘), double quotes (” “), and triple double quotes (“”” “””). The triple quotes can be used to
declare multiline strings in Python.
Python
# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
www.profajaypashankar.com Page 60 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
print("\nCreating a multiline String: ")
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
Creating a multiline String:
Geeks
For
Life
Accessing characters in Python String
In Python Programming tutorials, individual characters of a String can be accessed by using the method of
Indexing. Indexing allows negative address references to access characters from the back of the String, e.g.
-1 refers to the last character, -2 refers to the second last character, and so on.
While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed
as an index, float or other types that will cause a TypeError.
www.profajaypashankar.com Page 61 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
In this example, we will use the string-slicing method to extract a substring of the original string. The [3:12]
indicates that the string slicing will start from the 3rd index of the string to the 12th index, (12th character
not including). We can also use negative indexing in string slicing.
Python
# Creating a String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
gfg = "geeksforgeeks"
print(gfg)
Output:
skeegrofskeeg
Deleting/Updating from a String
In Python, the Updation or deletion of characters from a String is not allowed. This will cause an error because
item assignment or item deletion from a String is not supported. Although deletion of the entire String is
possible with the use of a built-in del keyword. This is because Strings are immutable, hence elements of a
String cannot be changed once assigned. Only new strings can be reassigned to the same name.
Updating a character
A character of a string can be updated in Python by first converting the string into a Python List and then
updating the element in the list. As lists are mutable in nature, we can update the character and then convert
the list back into the String.
Another method is using the string slicing method. Slice the string before the character you want to update,
then add the new character and finally add the other part of the string again by string slicing.
Example:
www.profajaypashankar.com Page 62 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
In this example, we are using both the list and the string slicing method to update a character. We converted
the String1 to a list, changes its value at a particular element, and then converted it back to a string using the
Python string join() method.
In the string-slicing method, we sliced the string up to the character we want to update, concatenated the
new character, and finally concatenate the remaining part of the string.
Python
# Python Program to Update
# character of a String
#2
String3 = String1[0:2] + 'p' + String1[3:]
print(String3)
Output:
Initial String:
Hello, I'm a Geek
Updating character at 2nd Index:
Heplo, I'm a Geek
Heplo, I'm a Geek
Updating Entire String
In Python Programming, As Python strings are immutable in nature, we cannot update the existing string.
We can only assign a completely new value to the variable with the same name.
Example: In this example, we first assign a value to ‘String1’ and then updated it by assigning a completely
different value to it. We simply changed its reference.
Python
# Python Program to Update
# entire String
# Updating a String
String1 = "Welcome to the Geek World"
print("\nUpdated String: ")
print(String1)
Output:
Initial String:
Hello, I'm a Geek
Updated String:
Welcome to the Geek World
Deleting a character
Python strings are immutable, that means we cannot delete a character from it. When we try to delete
thecharacter using the del keyword, it will generate an error.
Python
# Python Program to delete
# character of a String
www.profajaypashankar.com Page 63 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
# Deleting a character
# of the String
String2 = String1[0:2] + String1[3:]
print("\nDeleting character at 2nd Index: ")
print(String2)
Output:
Initial String:
Hello, I'm a Geek
Deleting character at 2nd Index:
Helo, I'm a Geek
Deleting Entire String
In Python Programming, Deletion of the entire string is possible with the use of del keyword. Further, if we
try to print the string, this will produce an error because the String is deleted and is unavailable to be printed.
Python
# Python Program to Delete
# entire String
# Deleting a String
# with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)
Error:
Traceback (most recent call last):
File "/home/e4b8f2170f140da99d2fe57d9d8c6a94.py", line 12, in
print(String1)
NameError: name 'String1' is not defined
Escape Sequencing in Python
While printing Strings with single and double quotes in it causes SyntaxError because String already
contains Single and Double Quotes and hence cannot be printed with the use of either of these. Hence, to print
such a String either Triple Quotes are used or Escape sequences are used to print Strings.
Escape sequences start with a backslash and can be interpreted differently. If single quotes are used to
represent a string, then all the single quotes present in the string must be escaped and the same is done for
Double Quotes.
Python
# Initial String
String1 = '''I'm a "Geek"'''
www.profajaypashankar.com Page 64 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
print("Initial String with use of Triple Quotes: ")
print(String1)
www.profajaypashankar.com Page 65 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
# Using raw String to
# ignore Escape Sequences
String1 = r"This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting Raw String in HEX Format: ")
print(String1)
Output:
Printing in Octal with the use of Escape Sequences:
Hello
Printing Raw String in Octal Format:
This is \110\145\154\154\157
Printing in HEX with the use of Escape Sequences:
This is Geeks in HEX
Printing Raw String in HEX Format:
This is \x47\x65\x65\x6b\x73 in \x48\x45\x58
Python String Formatting
Strings in Python or string data type in Python can be formatted with the use of format() method which is a
very versatile and powerful tool for formatting Strings. Format method in String contains curly braces {} as
placeholders which can hold arguments according to position or keyword to specify the order.
Example 1: In this example, we will declare a string which contains the curly braces {} that acts as a
placeholders and provide them values to see how string declaration position matters.
Python
# Python Program for
# Formatting of Strings
# Default order
String1 = "{} {} {}".format('Geeks', 'For', 'Life')
print("Print String in default order: ")
print(String1)
# Positional Formatting
String1 = "{1} {0} {2}".format('Geeks', 'For', 'Life')
print("\nPrint String in Positional order: ")
print(String1)
# Keyword Formatting
String1 = "{l} {f} {g}".format(g='Geeks', f='For', l='Life')
print("\nPrint String in order of Keywords: ")
print(String1)
Output:
Print String in default order:
Geeks For Life
Print String in Positional order:
For Geeks Life
Print String in order of Keywords:
Life For Geeks
Example 2: Integers such as Binary, hexadecimal, etc., and floats can be rounded or displayed in the
exponent form with the use of format specifiers.
Python
# Formatting of Integers
String1 = "{0:b}".format(16)
print("\nBinary representation of 16 is ")
print(String1)
# Formatting of Floats
String1 = "{0:e}".format(165.6458)
print("\nExponent representation of 165.6458 is ")
print(String1)
www.profajaypashankar.com Page 66 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Binary representation of 16 is
10000
Exponent representation of 165.6458 is
1.656458e+02
one-sixth is :
0.17
Example 3: In String data type in Python , A string can be left, right, or center aligned with the use of format
specifiers, separated by a colon(:). The (<) indicates that the string should be aligned to the left, (>) indicates
that the string should be aligned to the right and (^) indicates that the string should be aligned to the center.
We can also specify the length in which it should be aligned. For example, (<10) means that the string should
be aligned to the left within a field of width of 10 characters.
Python
# String alignment
String1 = "|{:<10}|{:^10}|{:>10}|".format('Geeks',
'for',
'Geeks')
print("\nLeft, center and right alignment with Formatting: ")
print(String1)
Integer1 = 12.3456789
print("Formatting in 3.2f format: ")
print('The value of Integer1 is %3.2f' % Integer1)
print("\nFormatting in 3.4f format: ")
print('The value of Integer1 is %3.4f' % Integer1)
Output:
Formatting in 3.2f format:
The value of Integer1 is 12.35
Formatting in 3.4f format:
The value of Integer1 is 12.3457
Python String constants
Built-In Function Description
www.profajaypashankar.com Page 67 of 68
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR
Built-In Function Description
Returns True if a string ends with the given suffix otherwise returns
String.endswith()
False
Returns True if a string starts with the given prefix otherwise returns
String.startswith()
False
www.profajaypashankar.com Page 68 of 68