0% found this document useful (0 votes)
172 views

Python Basics to Advanced by Sardar Azeem (1)

The document is a comprehensive guide on Python programming, covering topics from basic concepts to advanced techniques. It includes sections on programming languages, algorithms, Python features, and practical exercises. The guide is structured to facilitate learning for beginners and provides insights into various programming paradigms and tools associated with Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
172 views

Python Basics to Advanced by Sardar Azeem (1)

The document is a comprehensive guide on Python programming, covering topics from basic concepts to advanced techniques. It includes sections on programming languages, algorithms, Python features, and practical exercises. The guide is structured to facilitate learning for beginners and provides insights into various programming paradigms and tools associated with Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 122

Sardar Azeem Page 1 of 121 Python Form Basics To Advanced

Python Basics to
Advanced
Compiled By Sardar Azeem
CONTENTS
Introduction to Programming
1.1. What is a program?
1.2. Languages of Programming a computer
1.2.1. Machine Language
1.2.2. Assembly Language
1.2.3. High Level Language
1.3. Algorithm
1.4. Compiler vs Interpreter
1.5. Introduction and Benefits of Python
1.6. History of Python
1.7. Exercise

GETTING STARTED WITH PYTHON


2.1. Downloading and Installation of Python IDE (PyCharm)
2.2. Anatomy of Python Program
2.3. Write your first Hello World! Script
2.4. Guidelines for creating Script
2.4.1. Importance of comments
2.4.2. Spacing
2.5. Programming Errors:
2.5.1. Syntax Error
2.5.2. Runtime Errors
2.5.3. Logical Errors
2.6. Exercise

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 2 of 121 Python Form Basics To Advanced

VARIABLES & OPERATORS


3.1. Variables in Python
3.2. Rules and Guidelines for creating a variable
3.3. Assignment Operator
3.4. Multiple Assignments
3.5. Use of Buit-in function (type)
3.6. Arithmetic Operators (+, -, /, *, **)
3.7. Type Conversion Vs Type Casting
3.8. Boolean Operator
3.9. Logical & Comparison Operators
3.10. Exercise

STRINGS
4.1. Understanding Strings
4.2. Combine vs Repeat Strings
4.3. String’s Buit in Methods
(capitalize (), len (), lower (), upper (), strip (), replace (), startwith(), endswith())
4.4. Exercise

LISTS
5.1. Understanding Lists
5.2. Forward vs Backward Accessing
5.3. Changing, Removing and Adding Element
5.4. Slice a List
5.5. Membership Operator: in vs not in
5.6. Exercise
CONDITIONAL STATEMENT:
6.1. if statement
6.2. else statement
6.3. elif statement
6.4. Exercise

LOOPS:
7.1. for loop
7.2. while loop
7.3. continue vs break
7.4. Exercise

FUNCTIONS

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 3 of 121 Python Form Basics To Advanced

8.1. Understanding functions


8.2. print vs return statement
8.3. Variable scope
8.4. Default arguments
8.5. Exercise

WORKING WITH GRAPHICS


9.1. Introduction to Turtle
9.2. Basic commands
(forward(), back(), left(), right())
9.3. Draw Shapes
(Lines, Square, Rectangle, Circle, Star)
9.4. Working with Excel File using Panda
9.4.1. Reading an Excel file using Python
9.4.2. Writing into an excel file using Python
9.5. Other Useful Python Libraries
9.5.1. Numpy
9.5.2. Matplotlib
9.5.3. Tkinter
9.5.4. Django
9.5.5. Kotlin
9.5.6. Micropython
9.5.7. PyGame

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 4 of 121 Python Form Basics To Advanced

Topic # 1: - What is a program?


A computer program is a set of instructions and as a term it can be used as a verb as
well as a noun. In terms of a verb, it is used as a process of creating a software
program by using programming language. In terms of a noun, an application, program,
or application software is used to perform a specific task on the computer. For
example, Microsoft PowerPoint is an application, which provides a way to create
documents related to the presentation. Furthermore, a browser is also an application,
which allows us to browse any website.

Difference between Applications and programs


All applications can be called a program, but a program cannot be an application. An
application is a collection of programs that are designed to help the end-users to
achieve a purpose. These programs communicate with each other to perform tasks or
activities. It cannot exist without a program and functions to carry out end-user
commands. Whereas, a program is a collection of instructions that describes the
computer what task to perform.

What is the purpose of a program?


The program enables the computer to perform a particular operation. As without
application software (programs), a computer is able to operate with the operating
system, but it cannot perform any specific task. For example, if you want to create a
Word document, you have to install Microsoft Word on your computer. It is a program
or application software that instructs the computer how to create, edit, and save a
document or a file.

Topic # 2: - What is a programming language?


A programming language defines a set of instructions that are compiled together to
perform a specific task by the CPU (Central Processing Unit). The programming
language mainly refers to high-level languages such as C, C++, Pascal, Ada, COBOL,
etc.
Thousands of programming languages have been developed till now, but each language
has its specific purpose. Based on the levels of abstraction, they can be classified into
two categories:
1. Low-level language
2. High-level language
The image which is given below describes the abstraction level from hardware. As we
can observe from the below image that the machine language provides no abstraction,

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 5 of 121 Python Form Basics To Advanced

assembly language provides less abstraction whereas high-level language provides a


higher level of abstraction.

Low-level language
The low-level language is a programming language that provides no abstraction from
the hardware, and it is represented in 0 or 1 forms, which are the machine instructions.
The languages that come under this category are the Machine level language and
Assembly language.

Machine-level language
The machine-level language is a language that consists of a set of instructions that are
in the binary form 0 or 1. As we know that computers can understand only machine
instructions, which are in binary digits, i.e., 0 and 1, so the instructions given to the
computer can be only in binary codes. Creating a program in a machine-level language
is a very difficult task as it is not easy for the programmers to write the program in
machine instructions. It is error-prone as it is not easy to understand, and its
maintenance is also very high. A machine-level language is not portable as each
computer has its machine instructions, so if we write a program in one computer will
no longer be valid in another computer.
The different processor architectures use different machine codes, for example, a
PowerPC processor contains RISC architecture, which requires different code than
intel x86 processor, which has a CISC architecture.

Assembly Language
The assembly language contains some human-readable commands such as mov, add,
sub, etc. The problems which we were facing in machine-level language are reduced to
some extent by using an extended form of machine-level language known as assembly

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 6 of 121 Python Form Basics To Advanced

language. Since assembly language instructions are written in English words like mov,
add, sub, so it is easier to write and understand.
As we know that computers can only understand the machine-level instructions, so we
require a translator that converts the assembly code into machine code. The translator
used for translating the code is known as an assembler.
The assembly language code is not portable because the data is stored in computer
registers, and the computer has to know the different sets of registers.
The assembly code is not faster than machine code because the assembly language
comes above the machine language in the hierarchy, so it means that assembly
language has some abstraction from the hardware while machine language has zero
abstraction.

High-Level Language
The high-level language is a programming language that allows a programmer to write
the programs which are independent of a particular type of computer. The high-level
languages are considered as high-level because they are closer to human languages
than machine-level languages.
When writing a program in a high-level language, then the whole attention needs to be
paid to the logic of the problem.
A compiler is required to translate a high-level language into a low-level language.

Advantages of a high-level language


The high-level language is easy to read, write, and maintain as it is written in English
like words.
The high-level languages are designed to overcome the limitation of low-level
language, i.e., portability. The high-level language is portable; i.e., these languages are
machine-independent.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 7 of 121 Python Form Basics To Advanced

Differences between Low-Level language and High-Level


language

Low-level language High-level language

It is a machine-friendly language, i.e., It is a user-friendly language as this


the computer understands the machine language is written in simple English
language, which is represented in 0 or 1. words, which can be easily understood by
humans.

The low-level language takes more time It executes at a faster pace.


to execute.

It requires the assembler to convert the It requires the compiler to convert the
assembly code into machine code. high-level language instructions into
machine code.

The machine code cannot run on all The high-level code can run all the
machines, so it is not a portable platforms, so it is a portable language.
language.

It is memory efficient. It is less memory efficient.

Debugging and maintenance are not Debugging and maintenance are easier in
easier in a low-level language. a high-level language.

Topic # 3 :- What is an Algorithm


An algorithm is a procedure that describes a set of instructions that must be carried
out in a specific order to get the desired result.
An algorithm may be performed in multiple
computer languages since algorithms are
often designed independently of the underlying
languages. A few properties of an algorithm
are clarity, excellence, efficacy, and language
independence. An algorithm's performance
and scalability are what determine how
important it is.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 8 of 121 Python Form Basics To Advanced

Characteristics of an Algorithm
1. An algorithm needs specific input values. A number other than 0 may be
provided as input to an algorithm.
2. An algorithm will provide one or more outputs when it is finished.
3. Unambiguity: An ideal algorithm has specific instructions, which implies that
they should be simple and obvious.
4. Algorithms must be finite to function. In this context, "finiteness" refers to the
requirement that an algorithm has limited instructions or instructions that can
be counted.
5. Effectiveness: An algorithm should be sufficient since each instruction impacts
the whole procedure.
6. An algorithm must be language-independent, which implies that its instructions
must work the same no matter what language is used to implement them.

Topic # 4 :- What is a Language Processor?


A language processor is a special type of software program that has the potential to
translate the program codes into machine codes
Mostly, high-level languages like Java, C++, Python, and more are used to write the
programs, called source code, as it is very uninteresting work to write a computer
program directly in machine code. These source codes need to translate into machine
language to be executed because they cannot be executed directly by the computer.
Hence, a special translator system, a language processor, is used to convert source
code into machine language.

Types of language processors


There are mainly three kinds of language processors, which are discussed below:

1. Compiler: The language processor allows the computer to run and understand the

program by reading the complete source program in one time, which is written in a
high-level language. The computer can then interpret this code because it is translated
into machine language. In modern times, to compile the program, most of the high-
level languages have toolkits or a compiler. Gcc command for C and C++ and Eclipse
for Java are two popular compilers.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 9 of 121 Python Form Basics To Advanced

2. Assembler: An assembler converts programs written in assembly language into


machine code.

3. Interpreter: An interpreter is a computer program that allows a computer to


interpret or understand what tasks to perform. The programs written with the help of
using one of the many high-level programming languages are directly executed by an
interpreter without previously converting them to an object code or machine code,
which is done line by line or statement by statement.

Topic # 5 :- What is Python


Python is a general-purpose, dynamically typed, high-level, compiled and interpreted,
garbage-collected, and purely object-oriented programming language that supports
procedural, object-oriented, and functional programming.

Features of Python:
Python provides many useful features which make it popular and valuable from the
other programming languages.

1) Easy to Learn and Use


Python is easy to learn as compared to other programming languages. Its syntax is
straightforward and much the same as the English language. There is no use of the
semicolon or curly-bracket, the indentation defines the code block. It is the
recommended programming language for beginners.

2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the
hello world program you simply type print("Hello World"). It will take only one line to
execute, while Java or C takes multiple lines.

3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at
a time. The advantage of being interpreted language, it makes debugging easy and
portable.

4) Cross-platform Language

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 10 of 121 Python Form Basics To Advanced

Python can run equally on different platforms such as Windows, Linux, UNIX, and
Macintosh, etc. So, we can say that Python is a portable language. It enables
programmers to develop the software for several competing platforms by writing a
program only once.

5) Free and Open Source


Python is freely available for everyone. It is freely available on its official
website www.python.org. It has a large community across the world that is dedicatedly
working towards make new python modules and functions. Anyone can contribute to
the Python community. The open-source means, "Anyone can download its source code
without paying any penny."

6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come
into existence. It supports inheritance, polymorphism, and encapsulation, etc. The
object-oriented procedure helps to programmer to write reusable code and develop
applications in less code.

7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and
thus it can be used further in our Python code. It converts the program into byte code,
and any platform can use that byte code.

8) Large Standard Library


It provides a vast range of libraries for the various fields such as machine learning,
web developer, and also for the scripting. There are various machine learning libraries,
such as Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids
are the popular framework for Python web development.

9) GUI Programming Support


Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter,
Kivy are the libraries which are used for developing the web application.

10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code
line by line like C,C++ Java. It makes easy to debug the code.

11. Embeddable

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 11 of 121 Python Form Basics To Advanced

The code of the other programming language can use in the Python source code. We
can use Python source code in another programming language as well. It can embed
other language into our code.

12. Dynamic Memory Allocation


In Python, we don't need to specify the data-type of the variable. When we assign some
value to the variable, it automatically allocates the memory to the variable at run time.
Suppose we are assigned integer value 15 to x, then we don't need to write int x =
15. Just write x = 15.

Topic # 6 :- Python History and Versions


1. Python laid its foundation in the late 1980s.
2. The implementation of Python was started in December 1989 by Guido Van
Rossum at CWI in Netherland.
3. In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
Altisource’s.
4. In 1994, Python 1.0 was released with new features like lambda, map, filter, and
reduce.
5. Python 2.0 added new features such as list comprehensions, garbage collection
systems.
6. On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was
designed to rectify the fundamental flaw of the language.

Why the Name Python?


There is a fact behind choosing the name Python. Guido van Rossum was reading the
script of a popular BBC comedy series "Monty Python's Flying Circus". It was late on-
air 1970s.
Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So
he decided to select naming Python after the "Monty Python's Flying Circus" for their
newly created programming language.
The comedy series was creative and well random. It talks about everything. Thus it is
slow and unpredictable, which made it very interesting.
Python is also versatile and widely used in every technical field, such as Machine
Learning, Artificial Intelligence, Web Development, Mobile Application, Desktop
Application, Scientific Calculation, etc.
Python Version List

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 12 of 121 Python Form Basics To Advanced

Python programming language is being updated regularly with new features and
supports. There are lots of update in Python versions, started from 1994 to current
release.

A list of Python versions with its released date is given below.


Python 1.0 Python 2.4 Python 3.3
Python 1.5 Python 2.5 Python 3.4
Python 1.6 Python 2.6 Python 3.5
Python 2.0 Python 2.7 Python 3.6
Python 2.1 Python 3.0 Python 3.7
Python 2.2 Python 3.1 Python 3.8
Python 2.3 Python 3.2

Topic # 7 :- Python Applications


Python is known for its general-purpose nature that makes it applicable in almost
every domain of software development. Python makes its presence in every emerging
field. It is the fastest-growing programming language and can develop any application.

1) Web Applications
We can use Python to develop web
applications. Python provides many useful
frameworks, and these are given below:
1. Django and Pyramid framework
(Use for heavy applications)
2. Flask and Bottle (Micro-
framework)
3. Plone and Django CMS (Advance
Content management)

2) Desktop GUI Applications


The GUI stands for the Graphical User
Interface, which provides a smooth
interaction to any application. Python provides a Tk GUI library to develop a user
interface. Some popular GUI libraries are given below.
1. Tkinter or Tk
2. wxWidgetM

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 1 of 121 Python Form Basics To Advanced

3. Kivy (used for writing multitouch applications )


4. PyQt or Pyside

3) Console-based Application
Console-based applications run from the command-line or shell. These applications
are computer program which are used commands to execute. This kind of application
was more popular in the old generation of computers.

4) Software Development
Python is useful for the software development process. It works as a support language
and can be used to build control and management, testing, etc.
1. SCons is used to build control.
2. Buildbot and Apache Gumps are used for automated continuous compilation and
testing.
3. Round or Trac for bug tracking and project management.

5) Scientific and Numeric


This is the era of Artificial intelligence where the machine can perform the task the
same as the human. Python language is the most suitable language for Artificial
intelligence or machine learning. It consists of many scientific and mathematical
libraries, which makes easy to solve complex calculations.
Few popular frameworks of machine libraries are given below.
1. SciPy
2. Scikit-learn
3. NumPy
4. Pandas
5. Matplotlib

6) Business Applications
Business Applications differ from standard applications. E-commerce and ERP are an
example of a business application. This kind of application requires extensively,
scalability and readability, and Python provides all these features.
1. Oddo is an example of the all-in-one Python-based application which offers a
range of business applications.
2. Python provides a Tryton platform which is used to develop the business
application.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 2 of 121 Python Form Basics To Advanced

7) Audio or Video-based Applications


Python is flexible to perform multiple tasks and can be used to create multimedia
applications. Some multimedia applications which are made by using Python
are TimPlayer, cplay, etc. The few multimedia libraries are given below.
1. Gstreamer
2. Pyglet
3. QT Phonon

8) 3D CAD Applications
The CAD (Computer-aided design) is used to design engineering related architecture. It
is used to develop the 3D representation of a part of a system. Python can create a 3D
CAD application by using the following functionalities.
1. Fandango (Popular )
2. CAMVOX
3. HeeksCNC
4. AnyCAD
5. RCAM

9) Enterprise Applications
Python can be used to create applications that can be used within an Enterprise or an
Organization. Some real-time applications are
1. OpenERP
2. Tryton
3. Picalo

10) Image Processing Application


Python contains many libraries that are used to work with the image. The image can be
manipulated according to our requirements. Some libraries of image processing are
given below.
1. OpenCV
2. Pillow
3. SimpleITK

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 3 of 121 Python Form Basics To Advanced

Topic # 8 :- How to Install Python


In order to become Python developer, the first step is to learn how to install or update
Python on a local machine or computer.
Installation on Windows
Visit the link https://www.python.org to
download the latest release of Python.
In this process, we will install
Python 3.11.3 on our Windows operating
system. When we click on the above
link, it will bring us the following page.

Step - 1: Select the Python's version to


download.
Click on the download button to
download the exe file of Python.

Step - 2: Click on the Install Now


Double-click the executable file, which is
downloaded.
The following window will open. Click on
the Add Path check box, it will set the
Python path automatically.
Now, Select Customize installation and
proceed. We can also click on the
customize installation to choose desired
location and features. Other important thing is installing launcher for the all user must
be checked.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 4 of 121 Python Form Basics To Advanced

Here, under the advanced options, click on


the checkboxes of " Install Python 3.11 for all
users ", which is previously not checked in.
This will check the other option " Precompile
standard library " automatically. And the
location of the installation will also be
changed. We can change it later, so we leave
the install location default. Then, click on the
install button to finally install.

Step - 3 Installation in Process


The set up is in progress. All the python
libraries, packages, and other python default
files will be installed in our system. Once the
installation is successful, the following page
will appear saying " Setup was successful ".

Step - 4: Verifying the Python Installation


Go to "Start" button, and search " cmd ".
Then type, " python - - version ".
If python is successfully installed, then
we can see the version of the python
installed.
If not installed, then it will print the
error as " 'python' is not recognized as
an internal or external command,
operable program or batch file. ".

Step - 5: Opening idle


Now, to work on our first python program, we
will go the interactive interpreter prompt(idle).
To open this, go to "Start" and type idle. Then,
click on open to start working on idle.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 5 of 121 Python Form Basics To Advanced

Topic # 9 :- First Python Program


Python provides us the two ways to run a program:

1. Using Interactive interpreter prompt


2. Using a script file

Interactive interpreter prompt

Python provides us the feature to execute the Python statement one by one at the interactive prompt. It
is preferable in the case where we are concerned about the output of each line of our Python program.

To open the interactive mode, open the command prompt and type python

After writing the print statement, press the Enter key.

Here, we get the message "Hello World !" printed on the console.

Using a script file (Script Mode Programming)

The interpreter prompt is best to run the single-line statements of the code. However, we cannot write
the code every-time on the terminal. It is not suitable to write multiple lines of code.

Using the script mode, we can write multiple lines code into a file which can be executed later.

1. Open an editor like notepad.


2. Create a file named and save it with .py extension, which stands for "Python". Now, we will
implement the above example using the script mode.
3. To run this file named as first.py, we need to run the following command on the terminal.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 6 of 121 Python Form Basics To Advanced

Step - 1: Open the Python interactive shell, and click "File" then choose "New", it will open a new blank
script in which we can write our code.

Step -2: Now, write the code and press "Ctrl+S" to save the file.

Step - 3: After saving the code, we can run it by clicking "Run" or "Run Module". It will display the output
to the shell.

The output will be shown as follows.

Step - 4: Apart from that, we can also run the file using the operating system terminal. But we should be
aware of the path of the directory where we have saved our file.

1. Write a Program

Multi-line statements are written into the notepad like an editor and saved it with .py extension. In the
following example, we have defined the execution of the multiple code lines using the Python script.

E.g.

name = "Sardar Azeem"

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 7 of 121 Python Form Basics To Advanced

branch = "Computer Science"

age = "35"

print("My name is: ", name, )

print("My age is: ", age)

2. Open the command line prompt and navigate to the directory.

Like C:\Users\SardarAzeem\Desktop>

3. We need to type the python keyword, followed by the file name and hit enter to run the Python
file.

Like C:\Users\SardarAzeem\Desktop>python first.py

Topic # 10 :- What is PyCharm and How To Install PyCharm


JetBrains provides the most popular and a widely used cross-platform IDE PyCharm to run the python
programs.

Installing PyCharm on Windows is very simple. To install PyCharm on Windows operating system, visit
the link https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows to
download the executable installer. Double click the installer (.exe) file and install PyCharm by clicking
next at each step.

To create a first program to Pycharm follows the following step.

Step - 1. Open PyCharm editor. Click on "Create New Project" option to create new project.

Step - 2. Select a location to save the project.

We can save the newly created project at desired memory location or can keep file location as it is but
atleast change the project default name untitled to "FirstProject" or something meaningful name.

After change the name click on the "Create" Button.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 8 of 121 Python Form Basics To Advanced

Step - 3. Click on "File" menu and select "New". By clicking "New" option it will show various file formats.
Select the "Python File".

Step - 4. Now type the name of the Python file and click on "OK". We have written the "FirstProgram".

Step - 5. Now type the first program - print("Hello World") then click on the "Run" menu to run program.

Step - 6. The output will appear at the bottom of the screen.

Topic # 1 1 :- Comments in Python


Comments are essential for defining the code and help us and other to understand the code. By looking
the comment, we can easily understand the intention of every line that we have written in code. We can
also find the error very easily, fix them, and use in other applications.

In Python, we can apply comments using the # hash character. The Python interpreter entirely ignores
the lines followed by a hash character. A good programmer always uses the comments to make code
under stable.

Types of Comments in Python

In Python, there are 3 types of comments.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 9 of 121 Python Form Basics To Advanced

1. Single-Line Comments

Single-line remarks in Python have shown to be effective for providing quick descriptions for parameters,
function definitions, and expressions.

A single-line comment of Python is the one that has a hashtag # at the beginning of it and continues until
the finish of the line.

Example

# This code is to show an example of a single-line comment

print( 'This statement does not have a hashtag before it' )

2. Multi-Line Comments

Python does not provide the facility for multi-line comments. However, there are indeed many ways to
create multi-line comments.

With Multiple Hashtags (#)

In Python, we may use hashtags (#) multiple times to construct multiple lines of comments. Every line
with a (#) before it will be regarded as a single-line comment.

Example

# it is a

# comment

# extending to multiple lines

3. Python Docstring

The strings enclosed in triple quotes that come immediately after the defined function are called Python
docstring. It's designed to link documentation developed for Python modules, methods, classes, and
functions together. It's placed just beneath the function, module, or class to explain what they perform.
The docstring is then readily accessible in Python using the __doc__ attribute.

Example

def add(x, y):

"""This function adds the values of x and y"""

return x + y

# Displaying the docstring of the add function

print( add.__doc__ )

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 10 of 121 Python Form Basics To Advanced

Topic # 12 :- Python Variables


A variable is the name given to a memory location. A value-holding Python variable is
also known as an identifier.
Since Python is an infer language that is smart enough to determine the type of a
variable, we do not need to specify its type in Python.
• Variable names must begin with a letter or an underscore, but they can be a
group of both letters and digits.
• The name of the variable should be written in lowercase. Both Rahul and rahul
are distinct variables.
In Python, factors are an symbolic name that is a reference or pointer to an item. The
factors are utilized to indicate objects by that name.
a = 50
the variable a refers to an integer object.
Suppose we assign the integer value 50 to a new variable b.
a = 50
b=a
Let's assign the new value to b. Now both variables will refer to the different objects.
a = 50
b =100
Python manages memory efficiently if we assign the same variable to two different
values.
Object Identity
Every object created in Python has a unique identifier. Python gives the dependable
that no two items will have a similar identifier. The object identifier is identified using
the built-in id() function.
Example

a = 50
b=a
print(id(a))
print(id(b))

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 11 of 121 Python Form Basics To Advanced

# Reassigned variable a
a = 500
print(id(a))
Variable Names
The process for declaring the valid variable has already been discussed. Variable
names can be any length can have capitalized, lowercase (start to finish, a to z), the
digit (0-9), and highlight character(_).
Example

name = "Sardar Azeem"


age = 35
marks = 90.99
print(name)
print(age)
print(marks)
Example

name = "A"
Name = "B"
naMe = "C"
NAME = "D"
n_a_m_e = "E"
_name = "F"
name_ = "G"
_name_ = "H"
na56me = "I"
print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, na56me)
The multi-word keywords can be created by the following method.

Camel Case - In the camel case, each word or abbreviation in the middle of begins with a
capital letter. There is no intervention of whitespace.
• For example - nameOfStudent, valueOfVaraible, etc.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 12 of 121 Python Form Basics To Advanced

Pascal Case - It is the same as the Camel Case, but here the first word is also capital.

For example - NameOfStudent, etc.


Snake Case - In the snake case, Words are separated by the underscore. For example -
name_of_student, etc.
Multiple Assignment
Multiple assignments, also known as assigning values to multiple variables in a single
statement, is a feature of Python.
1. Assigning single value to multiple variables
Example
x=y=z=50
print(x)
print(y)
print(z)
2. Assigning multiple values to multiple variables:
Example
a,b,c=5,10,15
print a
print b
print c
Python Variable Types
There are two types of variables in Python - Local variable and Global variable. Let's
understand the following variables.
1. Local Variable
The variables that are declared within the function and have scope within the function
are known as local variables.
Example -
# Declaring a function
def add():
# Defining local variables. They has scope only within a function

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 13 of 121 Python Form Basics To Advanced

a = 20
b = 30
c=a+b
print("The sum is:", c)

# Calling a function
add()
2. Global Variables
Global variables can be utilized all through the program, and its extension is in the
whole program. Global variables can be used inside or outside the function.
By default, a variable declared outside of the function serves as the global variable.
Example -
# Declare a variable and initialize it
x = 101
# Global variable in function
def mainFunction():
# printing a global variable
global x
print(x)
# modifying a global variable
x = 'Welcome To PICT Abbottabad'
print(x)
mainFunction()
print(x)

Topic # 13 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.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 14 of 121 Python Form Basics To Advanced

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.
Example -
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
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 following is a list of the Python-defined data types.
➢ Numbers
➢ Sequence Type
➢ Boolean
➢ Set
➢ Dictionary

1. 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.
Example -
a=5
print("The type of a", type(a))

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 15 of 121 Python Form Basics To Advanced

b = 40.5
print("The type of b", type(b))

c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))
Python supports three kinds of numerical data.
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.
Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to
within 15 decimal places.
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.
2. Sequence Type
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.
Example - 1
str = "string using double quotes"
print(str)
s = '''''A multiline
string'''
print(s)

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 16 of 121 Python Form Basics To Advanced

Example - 2
str1 = 'hello javatpoint' #string str1
str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2
3. 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 (*).
Example:
list1 = [1, "hi", "Python", 2]
#Checking type of given list
print(type(list1))
#Printing the list1
print (list1)
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
# List Concatenation using + operator
print (list1 + list1)
# List repetation using * operator
print (list1 * 3)

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 17 of 121 Python Form Basics To Advanced

4. 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.
Example:
tup = ("hi", "Python", 2)
# Checking type of tup
print (type(tup))
#Printing the tuple
print (tup)
# Tuple slicing
print (tup[1:])
print (tup[0:1])
# Tuple concatenation using + operator
print (tup + tup)
# Tuple repatation using * operator
print (tup * 3)
# Adding value to tup. It will throw an error.
t[2] = "hi"
5. Dictionary
A dictionary is a key-value pair set arranged in any order. It stores a specific value for
each key, like an associative array or a hash table. Value is any Python object, while the
key can hold any primitive data type.
The comma (,) and the curly braces are used to separate the items in the dictionary.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 18 of 121 Python Form Basics To Advanced

Example -
d = {1:'Aliya', 2:'Maryam', 3:'Saba', 4:'Aneela'}
# Printing dictionary
print (d)
# Accesing value using keys
print("1st name is "+d[1])
print("2nd name is "+ d[4])
print (d.keys())
print (d.values())
6. 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.
Example -
# Python program to check the boolean type
print(type(True))
print(type(False))
print(false)

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 19 of 121 Python Form Basics To Advanced

Topic # 14 :- Python Keywords


Python keywords are unique words reserved with defined meanings and functions that
we can only apply for those functions. You'll never need to import any keyword into
your program because they're permanently present.
list of Python keywords for the reader's reference.
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

Topic # 15 :- Python Operators


The operator is a symbol that performs a specific operation between two operands,
according to one definition. Operators serve as the foundation upon which logic is
constructed in a program in a particular programming language. In every programming
language, some operators perform several tasks. Same as other languages, Python
also has some operators, and these are given below -
➢ Arithmetic operators
➢ Comparison operators
➢ Assignment Operators
➢ Logical Operators
➢ Bitwise Operators
➢ Membership Operators
➢ Identity Operators
1. Arithmetic Operators
Arithmetic operators used between two operands for a particular operation. There are
many arithmetic operators.
Following table provides a detailed explanation of arithmetic operators.

Operator Description
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b =
20

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 20 of 121 Python Form Basics To Advanced

- (Subtraction) It is used to subtract the second operand from the first operand. If
the first operand is less than the second operand, the value results
negative. For example, if a = 20, b = 5 => a - b = 15
/ (divide) It returns the quotient after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a =
(Multiplication) 20, b = 4 => a * b = 80
% (reminder) It returns the reminder after dividing the first operand by the
second operand. For example, if a = 20, b = 10 => a%b = 0
** (Exponent) As it calculates the first operand's power to the second operand, it
is an exponent operator.
// (Floor It provides the quotient's floor value, which is obtained by dividing
division) the two operands.
Example-
a = 32 # Initialize the value of a
b=6 # Initialize the value of b
print('Addition of two numbers:',a+b)
print('Subtraction of two numbers:',a-b)
print('Multiplication of two numbers:',a*b)
print('Division of two numbers:',a/b)
print('Reminder of two numbers:',a%b)
print('Exponent of two numbers:',a**b)
print('Floor division of two numbers:',a//b)

2. Comparison operator
Comparison operators mainly use for comparison purposes. Comparison operators
compare the values of the two operands and return a true or false Boolean value in
accordance.

Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= The condition is met if the first operand is smaller than or equal to the
second operand.
>= The condition is met if the first operand is greater than or equal to the
second operand.
> If the first operand is greater than the second operand, then the condition
becomes true.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 21 of 121 Python Form Basics To Advanced

< If the first operand is less than the second operand, then the condition
becomes true.
Example -
a = 32 # Initialize the value of a
b=6 # Initialize the value of b
print('Two numbers are equal or not:',a==b)
print('Two numbers are not equal or not:',a!=b)
print('a is less than or equal to b:',a<=b)
print('a is greater than or equal to b:',a>=b)
print('a is greater b:',a>b)
print('a is less than b:',a<b)

3. Assignment Operators
Using the assignment operators, the right expression's value is assigned to the left
operand.

Operator Description
= It assigns the value of the right expression to the left operand.
+= By multiplying the value of the right operand by the value of the left
operand, the left operand receives a changed value. For example, if a = 10,
b = 20 => a+ = b will be equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand
and assigns the modified value back to left operand. For example, if a = 20,
b = 10 => a- = b will be equal to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand
and assigns the modified value back to then the left operand. For
example, if a = 10, b = 20 => a* = b will be equal to a = a* b and therefore, a
= 200.
%= It divides the value of the left operand by the value of the right operand
and assigns the reminder back to the left operand. For example, if a = 20,
b = 10 => a % = b will be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign
4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign
4//3 = 1 to a.

Example-
a = 32 # Initialize the value of a

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 22 of 121 Python Form Basics To Advanced

b=6 # Initialize the value of b


print('a=b:', a==b)
print('a+=b:', a+b)
print('a-=b:', a-b)
print('a*=b:', a*b)
print('a%=b:', a%b)
print('a**=b:', a**b)
print('a//=b:', a//b)
Output:

4. Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators.
For example,
if a = 7
b=6
then, binary (a) = 0111
binary (b) = 0110

hence, a & b = 0011


a | b = 0111
a ^ b = 0100
~ a = 1000

Operator Description
& (binary A 1 is copied to the result if both bits in two operands at the same
and) location are 1. If not, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the
resulting bit will be 1.
^ (binary If the two bits are different, the outcome bit will be 1, else it will be 0.
xor)
~ (negation) The operand's bits are calculated as their negations, so if one bit is 0,
the next bit will be 1, and vice versa.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 23 of 121 Python Form Basics To Advanced

<< (left shift) The number of bits in the right operand is multiplied by the leftward
shift of the value of the left operand.
>> (right The left operand is moved right by the number of bits present in the
shift) right operand.
Example-
a=5 # initialize the value of a
b=6 # initialize the value of b
print('a&b:', a&b)
print('a|b:', a|b)
print('a^b:', a^b)
print('~a:', ~a)
print('a<<b:', a<<b)
print('a>>b:', a>>b)

5. Logical Operators
The assessment of expressions to make decisions typically uses logical operators.

Operator Description
and The condition will also be true if the expression is true. If the two
expressions a and b are the same, then a and b must both be true.
or The condition will be true if one of the phrases is true. If a and b are the
two expressions, then an or b must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
Example -
a=5 # initialize the value of a
print(Is this statement true?:',a > 3 and a < 5)
print('Any one statement is true?:',a > 3 or a < 5)
print('Each statement is true then return False and vice-
versa:',(not(a > 3 and a < 5)))

6. Membership Operators
The membership of a value inside a Python data structure can be verified using Python
membership operators.

Operator Description

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 24 of 121 Python Form Basics To Advanced

in If the first operand cannot be found in the second operand, it is evaluated


to be true (list, tuple, or dictionary).
not in If the first operand is not present in the second operand, the evaluation is
true (list, tuple, or dictionary).
Example -
x = ["Rose", "Lotus"]
print(' Is value Present?', "Rose" in x)
print(' Is value not Present?', "Riya" not in x)

Topic # 16 :- Python If-else statements


Decision making is the most important aspect of almost all the programming
languages. As the name implies, decision making allows us to run a particular block of
code for a particular decision. Here, the decisions are made on the validity of the
particular conditions. Condition checking is the backbone of decision making.

Statement Description
If Statement The if statement is used to test a specific condition. If the condition is
true, a block of code (if-block) will be executed.
If - else The if-else statement is similar to if statement except the fact that, it
Statement also provides the block of the code for the false case of the condition
to be checked. If the condition provided in the if statement is false,
then the else statement will be executed.
Nested if Nested if statements enable us to use if ? else statement inside an
Statement outer if statement.
1. The if statement
The if statement is used to test a particular condition and if the
condition is true, it executes a block of code known as if-block.
The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.
The syntax of the if-statement is given below.
if expression:
statement
Example 1
# Simple Python program to understand the if statement
num = int(input("enter the number:"))
# Here, we are taking an integer num and taking input dynamically

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 25 of 121 Python Form Basics To Advanced

if num%2 == 0:
# Here, we are checking the condition. If the condition is true, we will enter the bl
ock
print("The Given number is an even number")
Example 2 : Program to print the largest of the three numbers.
# Simple Python Program to print the largest of the three numbers.
a = int (input("Enter a: "));
b = int (input("Enter b: "));
c = int (input("Enter c: "));
if a>b and a>c:
# Here, we are checking the condition. If the condition is true, we will enter the bl
ock
print ("From the above three numbers given a is largest");
if b>a and b>c:
# Here, we are checking the condition. If the condition is true, we will enter the bl
ock
print ("From the above three numbers given b is largest");
if c>a and c>b:
# Here, we are checking the condition. If the condition is true, we will enter the bl
ock
print ("From the above three numbers given c is largest");

2. The if-else statement

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 26 of 121 Python Form Basics To Advanced

The if-else statement provides an else block combined


with the if statement which is executed in the false case
of the condition.
If the condition is true, then the if-block is executed.
Otherwise, the else-block is executed.
The syntax of the if-else statement
if condition:
#block of statements
else:
#another block of statements (else-block)
Example 1 : Program to check whether a person is eligible to vote or not.
# Simple Python Program to check whether a person is eligible to vote or not.
age = int (input("Enter your age: "))
# Here, we are taking an integer num and taking input dynamically
if age>=18:
# Here, we are checking the condition. If the condition is true, we will enter the blo
ck
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");
Example 2: Program to check whether a number is even or not.
# Simple Python Program to check whether a number is even or not.
num = int(input("enter the number:"))
# Here, we are taking an integer num and taking input dynamically
if num%2 == 0:
# Here, we are checking the condition. If the condition is true, we will enter the
block
print("The Given number is an even number")
else:

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 27 of 121 Python Form Basics To Advanced

print("The Given Number is an odd number")


3. The elif statement
The elif statement enables us to check multiple conditions
and execute the specific block of statements depending
upon the true condition among them. We can have any
number of elif statements in our program depending upon
our need. However, using elif is optional.
The elif statement works like an if-else-if ladder statement
in C. It must be succeeded by an if statement.
The syntax of the elif statement is given below.
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example 1
# Simple Python program to understand elif statement
number = int(input("Enter the number?"))
# Here, we are taking an integer number and taking input dynamically
if number==10:
# Here, we are checking the condition. If the condition is true, we will enter the block

print("The given number is equals to 10")


elif number==50:
# Here, we are checking the condition. If the condition is true, we will enter the block

print("The given number is equal to 50");

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 28 of 121 Python Form Basics To Advanced

elif number==100:
# Here, we are checking the condition. If the condition is true, we will enter the block

print("The given number is equal to 100");


else:
print("The given number is not equal to 10, 50 or 100");
Example 2
# Simple Python program to understand elif statement
marks = int(input("Enter the marks? "))
# Here, we are taking an integer marks and taking input dynamically
if marks > 85 and marks <= 100:
# Here, we are checking the condition. If the condition is true, we will enter the block

print("Congrats ! you scored grade A ...")


elif marks > 60 and marks <= 85:
# Here, we are checking the condition. If the condition is true, we will enter the block

print("You scored grade B + ...")


elif marks > 40 and marks <= 60:
# Here, we are checking the condition. If the condition is true, we will enter the block

print("You scored grade B ...")


elif (marks > 30 and marks <= 40):
# Here, we are checking the condition. If the condition is true, we will enter the block

print("You scored grade C ...")


else:
print("Sorry you are fail ?")

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 29 of 121 Python Form Basics To Advanced

Topic # 17 :- Python Loops


The following loops are available in Python to fulfil the looping needs.
We can run a single statement or set of statements repeatedly using a loop command.

Sr.No. Name of Loop Type & Description


the loop
1 While loop Repeats a statement or group of statements while a given
condition is TRUE. It tests the condition before executing the
loop body.
2 For loop This type of loop executes a code block multiple times and
abbreviates the code that manages the loop variable.
3 Nested We can iterate a loop inside another loop.
loops
Loop Control Statements
Statements used to control loops and change the course of iteration are called control
statements. All the objects produced within the local scope of the loop are deleted
when execution is completed.
Python provides the following control statements.

Sr.No. Name of the Description


control
statement
1 Break This command terminates the loop's execution and
statement transfers the program's control to the statement next to
the loop.
2 Continue This command skips the current iteration of the loop. The
statement statements following the continue statement are not
executed once the Python interpreter reaches the continue
statement.
3 Pass statement The pass statement is used when a statement is
syntactically necessary, but no code is to be executed.
The for Loop
Pythons for loop is designed to repeatedly execute a code block while iterating through
a list, tuple, dictionary, or other iterable objects of Python.
“The process of traversing a sequence is known as iteration”.
Syntax of the for Loop
for value in sequence:
{ code block }

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 30 of 121 Python Form Basics To Advanced

Example 1
# Python program to show how the for loop works
# Creating a sequence which is a tuple of numbers
numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]
# variable to store the square of the number
square = 0
# Creating an empty list
squares = []
# Creating a for loop
for value in numbers:
square = value ** 2
squares.append(square)
print("The list of squares is", squares)
Using else Statement with for Loop
For loop executes the code block until the sequence element is reached. The statement
is written right after the for loop is executed after the execution of the for loop is
complete.
Only if the execution is complete does the else statement comes into play. It won't be
executed if we exit the loop or if an error is thrown.
Example -2
# Python program to show how if-else statements work
string = "Python Loop"
# Initiating a loop
for s in a string:
# giving a condition in if block
if s == "o":
print("If block")
# if condition is not satisfied then else block will be executed

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 31 of 121 Python Form Basics To Advanced

else:
print(s)
Now similarly, using else with for loop.
Syntax:
for value in sequence:
# executes the statements until sequences are exhausted
else:
# executes these statements when for loop is completed
Example -3
# Python program to show how to use else statement with for loop
# Creating a sequence
tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
# Initiating the loop
for value in tuple_:
if value % 2 != 0:
print(value)
# giving an else statement
else:
print("These are the odd numbers present in the tuple")
The range() Function
With the help of the range() function, we may produce a series of numbers. range(10)
will produce values between 0 and 9. (10 numbers).
We can give specific start, stop, and step size values in the manner range(start, stop,
step size). If the step size is not specified, it defaults to 1.
Since it doesn't create every value it "contains" after we construct it, the range object
can be characterized as being "slow." It does provide in, len, and __getitem__ actions,
but it is not an iterator.
Example- 4
# Python program to show the working of range() function

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 32 of 121 Python Form Basics To Advanced

print(range(15))

print(list(range(15)))

print(list(range(4, 9)))

print(list(range(5, 25, 4)))


To iterate through a sequence of items, we can apply the range() method in for loops.
We can use indexing to iterate through the given sequence by combining it with an
iterable's len() function. Here's an illustration.
Example - 5
# Python program to iterate over a sequence with the help of indexing

tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")

# iterating over tuple_ using range() function


for iterator in range(len(tuple_)):
print(tuple_[iterator].upper())
While Loop
While loops are used in Python to iterate until a specified condition is met. However,
the statement in the program that follows the while loop is executed once the condition
changes to false.
Syntax of the while loop is:
while <condition>:
{ code block }
All the coding statements that follow a structural command define a code block. These
statements are intended with the same number of spaces. Python groups statements
together with indentation.
Example -1

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 33 of 121 Python Form Basics To Advanced

# Python program to show how to use a while loop


counter = 0
# Initiating the loop
while counter < 10: # giving the condition
counter = counter + 3
print("Python Loops")
Using else Statement with while Loops
As discussed earlier in the for loop section, we can use the else statement with the
while loop also. It has the same syntax.
Example -2
#Python program to show how to use else statement with the while loop
counter = 0

# Iterating through the while loop


while (counter < 10):
counter = counter + 3
print("Python Loops") # Executed untile condition is met
# Once the condition of while loop gives False this statement will be executed
else:
print("Code block inside the else statement")
Single statement while Block
The loop can be declared in a single statement, as seen below. This is similar to the if-
else block, where we can write the code block in a single line.
Example -3
# Python program to show how to write a single statement while loop
counter = 0
while (count < 3): print("Python Loops")
Loop Control Statements

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 34 of 121 Python Form Basics To Advanced

Now we will discuss the loop control statements in detail. We will see an example of
each control statement.
Continue Statement
It returns the control to the beginning of the loop.
Example -1
# Python program to show how the continue statement works

# Initiating the loop


for string in "Python Loops":
if string == "o" or string == "p" or string == "t":
continue
print('Current Letter:', string)
Break Statement
It stops the execution of the loop when the break statement is reached.
Example -2
# Python program to show how the break statement works

# Initiating the loop


for string in "Python Loops":
if string == 'L':
break
print('Current Letter: ', string)
Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for
classes, functions, and empty control statements.
Example -3
# Python program to show how the pass statement works
for a string in "Python Loops":

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 35 of 121 Python Form Basics To Advanced

pass
print( 'Last Letter:', string)

Topic # 18 :- Python String


Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes. The computer does not understand the characters; internally,
it stores manipulated character as the combination of the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that
Python strings are also called the collection of Unicode characters.
Syntax:
str = "Hi Python !"
print(type(str)), then it will print a string (str).
Creating String in Python
We can create a string by enclosing the characters in single-quotes or double- quotes.
Python also provides triple-quotes to represent the string, but it is generally used for
multiline string or docstrings.
#Using single quotes
str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)
#Using triple quotes
str3 = '''''Triple quotes are generally used for
represent the multiline or
docstring'''
print(str3)
Strings indexing and splitting
Like other languages, the indexing of the Python strings starts from 0. For example,
The string "HELLO" is indexed as given in the below figure.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 36 of 121 Python Form Basics To Advanced

Example -1
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 37 of 121 Python Form Basics To Advanced

Example -2
# Given String
str = "SARDARAZEEM"
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 38 of 121 Python Form Basics To Advanced

#Starts 4th to 6th index


print(str[4:7])
We can do the negative slicing in the string; it starts from the rightmost character,
which is indicated as -1. The second rightmost index indicates -2, and so on. Consider
the following image.

Example -3
str = 'JAVATPOINT'
print(str[-1])
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
# Reversing the given string
print(str[::-1])
print(str[-12])

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 39 of 121 Python Form Basics To Advanced

Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string
object doesn't support item assignment i.e., A string can only be replaced with new
string since its content cannot be partially replaced. Strings are immutable in Python.
Example -4
str = "PICT"
str[0] = "A"
print(str)
Example -5
str = "HELLO"
print(str)
str = "hello"
print(str)
Deleting the String
As we know that strings are immutable. We cannot delete or remove the characters
from the string. But we can delete the entire string using the del keyword.
str1 = "SARDARAZEEM"
del str1
String Operators

Operator Description
+ It is known as concatenation operator used to join the strings given either
side of the operator.
* It is known as repetition operator. It concatenates the multiple copies of
the same string.
[] It is known as slice operator. It is used to access the sub-strings of a
particular string.
[:] It is known as range slice operator. It is used to access the characters
from the specified range.
in It is known as membership operator. It returns if a particular sub-string is
present in the specified string.
not in It is also a membership operator and does the exact reverse of in. It
returns true if a particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases
where we need to print the actual meaning of escape characters such as

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 40 of 121 Python Form Basics To Advanced

"C://python". To define any string as a raw string, the character r or R is


followed by the string.
% It is used to perform string formatting. It makes use of the format
specifiers used in C programming like %d or %f to map their values in
python. We will discuss how formatting is done in python.
Example -6
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
Python String Formatting By Using Escape Sequence
Let's suppose we need to write the text as - They said, "Hello what's going on?"- the
given statement can be written in single quotes or double quotes but it will raise
the SyntaxError as it contains both single and double-quotes.
Example -7
str = "They said, "Hello what's going on?""
print(str)
The backslash(/) symbol denotes the escape sequence. The backslash can be followed
by a special character and it interpreted differently. The single quotes inside the string
must be escaped. We can apply the same as in the double quotes.
Example - 8
# using triple quotes
print('''''They said, "What's there?"''')

# escaping single quotes

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 41 of 121 Python Form Basics To Advanced

print('They said, "What\'s going on?"')

# escaping double quotes


print("They said, \"What's going on?\"")
The list of an escape sequence is given below:

Sr. Escape Sequence Description Example


1. \newline It ignores the new line. print("Python1 \
Python2 \
Python3")
Output:
Python1 Python2 Python3
2. \\ Backslash print("\\")
Output:
\
3. \' Single Quotes print('\'')
Output:
'
4. \\'' Double Quotes print("\"")
Output:
"
5. \a ASCII Bell print("\a")
6. \b ASCII Backspace(BS) print("Hello \b World")
Output:
Hello World
7. \f ASCII Formfeed print("Hello \f World!")
Hello World!
8. \n ASCII Linefeed print("Hello \n World!")
Output:
Hello
World!
9. \r ASCII Carriege Return(CR) print("Hello \r World!")
Output:
World!
10. \t ASCII Horizontal Tab print("Hello \t World!")
Output:
Hello World!
11. \v ASCII Vertical Tab print("Hello \v World!")
Output:
Hello
World!
12. \ooo Character with octal value print("\110\145\154\154\157")

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 42 of 121 Python Form Basics To Advanced

Output:
Hello
13 \xHH Character with hex value. print("\x48\x65\x6c\x6c\x6f")
Output:
Hello
Example -9
print("C:\\Users\\SardarAzeem\\Python32\\Lib")
print("This is the \n multiline quotes")
print("This is \x48\x45\x58 representation")
Output:
The format() method
The format() method is the most flexible and useful method in formatting strings. The
curly braces {} are used as the placeholder in the string and replaced by
the format() method argument.
Example -10
# Using Curly braces
print("{} and {} both are the best friend".format("Devansh","Abhishek"))
#Positional Argument
print("{1} and {0} best players ".format("Virat","Rohit"))
#Keyword Argument
print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))
Python String Formatting Using % Operator
Python allows us to use the format specifiers used in C's printf statement. The format
specifiers in Python are treated in the same way as they are treated in C. However,
Python provides an additional operator %, which is used as an interface between the
format specifiers and their values. In other words, we can say that it binds the format
specifiers to the values.
Example -11
Integer = 10;
Float = 1.290
String = "SardarAzeem"

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 43 of 121 Python Form Basics To Advanced

print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string ...
My value is %s"%(Integer,Float,String))

Topic # 19 :- Python List


A list is a collection of different kinds of values or items. Since Python lists are
mutable, we can change their elements after forming. The comma (,) and the square
brackets [enclose the List's items] serve as separators.
Although six Python data types can hold sequences, the List is the most common and
reliable form. A list, a type of sequence data, is used to store the collection of data.
Tuples and Strings are two similar data formats for sequences.
Lists written in Python are identical to dynamically scaled arrays defined in other
languages, such as Array List in Java and Vector in C++. A list is a collection of items
separated by commas and denoted by the symbol [].
List Declaration
Example -1
# a simple list
list1 = [1, 2, "Python", "Program", 15.9]
list2 = ["amy", "mari", "samri", "fati"]
# printing the list
print(list1)
print(list2)
# printing the type of list
print(type(list1))
print(type(list2))
Characteristics of Lists
4. The lists are in order.
5. The list element can be accessed via the index.
6. The mutable type of List is
7. The rundowns are changeable sorts.
8. The number of various elements can be stored in a list.
Ordered List Checking

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 44 of 121 Python Form Basics To Advanced

Example # 2
a = [ 1, 2, "Rahim", 3.50, "Rizwan", 5, 6 ]
b = [ 1, 2, 5, "Rashid", 3.50, "Rasheed", 6 ]
a == b
Example # 3
a = [ 1, 2, "Zia", 3.50, "Zafar", 5, 6]
b = [ 1, 2, "Zia", 3.50, "Zafar", 5, 6]
a == b
Example # 4
# list example in detail
emp = [ "Azeem", 102, "USA"]
Dep1 = [ "CS",10]
Dep2 = [ "IT",11]
HOD_CS = [ 10,"Mr.Azeem"]
HOD_IT = [11, "Mr.Aftab"]
print("printing employee data ...")
print(" Name : %s, ID: %d, Country: %s" %(emp[0], emp[1], emp[2]))
print("printing departments ...")
print("Department 1:\nName: %s, ID: %d\n Department 2:\n Name: %s, ID: %s"%( Dep1[0],
Dep2[1], Dep2[0], Dep2[1]))
print("HOD Details ....")
print("CS HOD Name: %s, Id: %d" %(HOD_CS[1], HOD_CS[0]))
print("IT HOD Name: %s, Id: %d" %(HOD_IT[1], HOD_IT[0]))
print(type(emp), type(Dep1), type(Dep2), type(HOD_CS), type(HOD_IT))
List Indexing and Splitting
The indexing procedure is carried out similarly to string processing. The slice operator
[] can be used to get to the List's components.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 45 of 121 Python Form Basics To Advanced

The index ranges from 0 to length -1. The 0th index is where the List's first element is
stored; the 1st index is where the second element is stored, and so on.

We can get the sub-list of the list using the following syntax.
list_varible(start:stop:step)
Example # 5
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default, the index value is 0 so its starts from the 0th element and go for index -
1.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 46 of 121 Python Form Basics To Advanced

print(list[:])
print(list[2:5])
print(list[1:6:2])
The negative indices are counted from the right. The index -1 represents the final
element on the List's right side, followed by the index -2 for the next member on the
left, and so on, until the last element on the left is reached.

Example # 6
# negative indexing example
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])
Updating List Values
Due to their mutability and the slice and assignment operator's ability to update their
values, lists are Python's most adaptable data structure. Python's append() and insert()
methods can also add values to a list.
Example # 7
# updating list values
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second index
list[2] = 10
print(list)

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 47 of 121 Python Form Basics To Advanced

# Adding multiple-element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
The list elements can also be deleted by using the del keyword. Python also provides
us the remove() method if we do not know which element is to be deleted from the list.
Example # 8
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to second index
list[2] = 10
print(list)
# Adding multiple element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
Python List Operations
The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings. The different operations of list are
1 Repetition 3 Length 5 Membership

2 Concatenation 4 Iteration

1. Repetition
The redundancy administrator empowers the rundown components to be rehashed on
different occasions.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 1 of 121 Python Form Basics To Advanced

Example # 9
# repetition of list
# declaring the list
list1 = [12, 14, 16, 18, 20]
# repetition operator *
l = list1 * 2
print(l)
2. Concatenation
It concatenates the list mentioned on either side of the operator.
Example # 10
# concatenation of two lists
# declaring the lists
list1 = [12, 14, 16, 18, 20]
list2 = [9, 10, 32, 54, 86]
# concatenation operator +
l = list1 + list2
print(l)
3. Length
It is used to get the length of the list
Example # 11
# size of the list
# declaring the list
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
# finding length of the list
len(list1)
4. Iteration
The for loop is used to iterate over the list elements.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 2 of 121 Python Form Basics To Advanced

Example # 12
# iteration of the list
# declaring the list
list1 = [12, 14, 16, 39, 40]
# iterating
for i in list1:
print(i)

5. Membership
It returns true if a particular item exists in a particular list otherwise false.
Example # 13
# membership of the list
# declaring the list
list1 = [100, 200, 300, 400, 500]
# true will be printed if value exists
# and false if not
print(600 in list1)
print(700 in list1)
print(1040 in list1)
print(300 in list1)
print(100 in list1)
print(500 in list1)
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings,
which can be iterated as follows.
Example # 14
# iterating a list
list = ["John", "David", "James", "Jonathan"]

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 3 of 121 Python Form Basics To Advanced

for i in list:
# The i variable will iterate over the elements of the List and contains each element i
n each iteration.
print(i)
Adding Elements to the List
The append() function in Python can add a new item to the List. In any case, the annex()
capability can enhance the finish of the rundown.
Consider the accompanying model, where we take the components of the rundown
from the client and print the rundown on the control center.
Example # 15
#Declaring the empty list
l =[]
#Number of elements will be entered by the user
n = int(input("Enter the number of elements in the list:"))
# for loop to take the input
for i in range(0,n):
# The input is taken from the user and added to the list as the item
l.append(input("Enter the item:"))
print("printing the list items..")
# traversal loop to print the list items
for i in l:
print(i, end = " ")
Removing Elements from the List
The remove() function in Python can remove an element from the List. To comprehend
this idea, look at the example that follows.
Example # 16
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 4 of 121 Python Form Basics To Advanced

print(i,end=" ")
list.remove(2)
print("\nprinting the list after the removal of first element...")
for i in list:
print(i,end=" ")
Python List Built-in Functions
Python provides the following built-in functions, which can be used with the lists.
1 len() 3 min()

2 max() 4 len( )

LEN() It is used to calculate the length of the list.


Example # 17
# size of the list
# declaring the list
list1 = [12, 16, 18, 20, 39, 40]
# finding length of the list
len(list1)
Max( ) It returns the maximum element of the list
Example # 18
# maximum of the list
list1 = [103, 675, 321, 782, 200]
# large element in the list
print(max(list1))
Min( ) It returns the minimum element of the list
Example # 19
# minimum of the list
list1 = [103, 675, 321, 782, 200]
# smallest element in the list

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 1 of 121 Python Form Basics To Advanced

print(min(list1))
Example # 20
Create a program to eliminate the List's duplicate items.
list1 = [1,2,2,3,55,98,65,65,13,29]
# Declare an empty list that will store unique values
list2 = []
for i in list1:
if i not in list2:
list2.append(i)
print(list2)
Example # 21
Compose a program to track down the amount of the component in the rundown.
list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)
Example # 22
Compose the program to find the rundowns comprise of somewhere around one
normal component.
Code
list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y:
print("The common element is:",x)

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 2 of 121 Python Form Basics To Advanced

Topic # 20 :- Python Tuples


A comma-separated group of items is called a Python triple. The ordering, settled
items, and reiterations of a tuple are to some degree like those of a rundown, but in
contrast to a rundown, a tuple is unchanging.
The main difference between the two is that we cannot alter the components of a tuple
once they have been assigned. On the other hand, we can edit the contents of a list.
Example
("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.
Features of Python Tuple
1. Tuples are an immutable data type, meaning their elements cannot be changed
after they are generated.
2. Each element in a tuple has a specific order that will never change because
tuples are ordered sequences.
3. Forming a Tuple:
4. All the objects-also known as "elements"-must be separated by a comma,
enclosed in parenthesis (). Although parentheses are not required, they are
recommended.
5. Backward Skip 10sPlay VideoForward Skip 10s
6. Any number of items, including those with various data types (dictionary, string,
float, list, etc.), can be contained in a tuple.
Example # 1
# Python program to show how to create a tuple
# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)

# Creating tuple having integers


int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)

# Creating a tuple having objects of different data types


mixed_tuple = (4, "Python", 9.3)

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 3 of 121 Python Form Basics To Advanced

print("Tuple with different data types: ", mixed_tuple)

# Creating a nested tuple


nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
print("A nested tuple: ", nested_tuple)
Parentheses are not necessary for the construction of multiples. This is known as
triple pressing.
Example # 2
# Python program to create a tuple without using parentheses
# Creating a tuple
tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]
# Displaying the tuple created
print(tuple_)
# Checking the data type of object tuple_
print(type(tuple_) )
# Trying to modify tuple_
try:
tuple_[1] = 4.2
except:
print(TypeError )
The development of a tuple from a solitary part may be complex.
Essentially adding a bracket around the component is lacking. A comma must separate
the element to be recognized as a tuple.
Example # 3
# Python program to show how to create a tuple having a single element
single_tuple = ("Tuple")
print( type(single_tuple) )
# Creating a tuple that has only one element

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 4 of 121 Python Form Basics To Advanced

single_tuple = ("Tuple",)
print( type(single_tuple) )
# Creating tuple without parentheses
single_tuple = "Tuple",
print( type(single_tuple) )
Accessing Tuple Elements
A tuple's objects can be accessed in a variety of ways.
Indexing
Indexing We can use the index operator [] to access an object in a tuple, where the
index starts at 0.
The indices of a tuple with five items will range from 0 to 4. An Index Error will be
raised assuming we attempt to get to a list from the Tuple that is outside the scope of
the tuple record. An index above four will be out of range in this scenario.
Example # 4
# Python program to show how to access tuple elements
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
print(tuple_[0])
print(tuple_[1])
# trying to access element index more than the length of a tuple
try:
print(tuple_[5])
except Exception as e:
print(e)
# trying to access elements through the index of floating data type
try:
print(tuple_[1.0])
except Exception as e:

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 5 of 121 Python Form Basics To Advanced

print(e)
# Creating a nested tuple
nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))

# Accessing the index of a nested tuple


print(nested_tuple[0][3])
print(nested_tuple[1][1])
Negative Indexing
Python's sequence objects support negative indexing.
The last thing of the assortment is addressed by - 1, the second last thing by - 2, etc.
Example # 5
# Python program to show how negative indexing works in Python tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
# Printing elements using negative indices
print("Element at -1 index: ", tuple_[-1])
print("Elements between -4 and -1 are: ", tuple_[-4:-1])
Slicing
Tuple slicing is a common practice in Python and the most common way for
programmers to deal with practical issues. Look at a tuple in Python. Slice a tuple to
access a variety of its elements. Using the colon as a straightforward slicing operator
(:) is one strategy.
Example # 6
# Python program to show how slicing works in Python tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
# Using slicing to access elements of the tuple
print("Elements between indices 1 and 3: ", tuple_[1:3])

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 6 of 121 Python Form Basics To Advanced

# Using negative indexing in slicing


print("Elements between indices 0 and -4: ", tuple_[:-4])
# Printing the entire tuple by using the default start and end values.
print("Entire tuple: ", tuple_[:])
Deleting a Tuple
A tuple's parts can't be modified, as was recently said. We are unable to eliminate or
remove tuple components as a result.
However, the keyword del can completely delete a tuple.
Example # 7
# Python program to show how to delete elements of a Python tuple
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
# Deleting a particular element of the tuple
try:
del tuple_[3]
print(tuple_)
except Exception as e:
print(e)
# Deleting the variable from the global space of the program
del tuple_
# Trying accessing the tuple after deleting it
try:
print(tuple_)
except Exception as e:
print(e)
Repetition Tuples in Python
Example # 8
# Python program to show repetition in tuples

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 7 of 121 Python Form Basics To Advanced

tuple_ = ('Python',"Tuples")
print("Original tuple is: ", tuple_)
# Repeting the tuple elements
tuple_ = tuple_ * 3
print("New tuple is: ", tuple_)
Tuple Methods
The following are some examples of these methods.
Count () Method
The times the predetermined component happens in the Tuple is returned by the count
() capability of the Tuple.
Example # 9
# Creating tuples
T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
# counting the appearance of 3
res = T1.count(2)
print('Count of 2 in T1 is:', res)
# counting the appearance of java
res = T2.count('java')
print('Count of Java in T2 is:', res)
Index() Method:
The Index() function returns the first instance of the requested element from the Tuple.
Parameters:
The thing that must be looked for.
Start: (Optional) the index that is used to begin the final (optional) search: The most
recent index from which the search is carried out
Example # 10
# Creating tuples

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 8 of 121 Python Form Basics To Advanced

Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
res = Tuple_data.index(3)
print('First occurrence of 1 is', res)
# getting the index of 3 after 4th
# index
res = Tuple_data.index(3, 4)
print('First occurrence of 1 after 4th index is:', res)
Tuple Membership Test
Utilizing the watchword, we can decide whether a thing is available in the given Tuple.
Example # 11
# Python program to show how to perform membership test for tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")
# In operator
print('Tuple' in tuple_)
print('Items' in tuple_)
# Not in operator
print('Immutable' not in tuple_)
print('Items' not in tuple_)
Iterating Through a Tuple
A for loop can be used to iterate through each tuple element.
Example # 12
# Python program to show how to iterate over tuple elements
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
# Iterating over tuple elements using a for loop

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 9 of 121 Python Form Basics To Advanced

for item in tuple_:


print(item)
Changing a Tuple
Tuples, instead of records, are permanent articles.
Example # 13
# Python program to show that Python tuples are immutable objects
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", [1,2,3,4])
# Trying to change the element at index 2
try:
tuple_[2] = "Items"
print(tuple_)
except Exception as e:
print( e )
# But inside a tuple, we can change elements of a mutable object
tuple_[-1][2] = 10
print(tuple_)
# Changing the whole tuple
tuple_ = ("Python", "Items")
print(tuple_)
Concatenation
The + operator can be used to combine multiple tuples into one. This phenomenon is
known as concatenation.
We can also repeat the elements of a tuple a predetermined number of times by using
the * operator. This is already demonstrated above.
The aftereffects of the tasks + and * are new tuples.
Example # 14
# Python program to show how to concatenate tuples

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 10 of 121 Python Form Basics To Advanced

# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
# Adding a tuple to the tuple_
print(tuple_ + (4, 5, 6))

Topic # 21 : - Python Set


A Python set is the collection of the unordered items. Each element in the set must be
unique, immutable, and the sets remove the duplicate elements. Sets are mutable
which means we can modify it after its creation.
Unlike other collections in Python, there is no index attached to the elements of the
set, i.e., we cannot directly access any element of the set by the index. However, we can
print them all together, or we can get the list of elements by looping through the set.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the
curly braces {}. Python also provides the set() method, which can be used to create the
set by the passed sequence.
Example # 1: Using curly braces
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}

print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Example # 2: Using set() method
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunda
y"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 11 of 121 Python Form Basics To Advanced

print(i)
It can contain any type of element such as integer, float, tuple etc.
Example # 3
# Creating a set which have immutable elements
set1 = {1,2,3, "JavaTpoint", 20.5, 14}
print(type(set1))
#Creating a set which have mutable element
set2 = {1,2,3,["Javatpoint",4]}
print(type(set2))
Empty Set
Creating an empty set is a bit different because empty curly {} braces are also used to
create a dictionary as well. So Python provides the set() method used without an
argument to create an empty set.
Example # 4
# Empty curly braces will create dictionary
set3 = {}
print(type(set3))

# Empty set using set() function


set4 = set()
print(type(set4))
Adding items to the set
Python provides the add() method and update() method which can be used to add some
particular item to the set.
Example: # 5 - Using add() method
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 12 of 121 Python Form Basics To Advanced

print("\nAdding other months to the set...");


Months.add("July");
Months.add ("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
Example # 6 Using update() function
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nupdating the original set ... ")
Months.update(["July","August","September","October"]);
print("\nprinting the modified set ... ")
print(Months);
Removing items from the set
Python provides the discard() method and remove() method which can be used to
remove the items from the set.
Example # 7 Using discard() method
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.discard("January");
months.discard("May");
print("\nPrinting the modified set...");
print(months)

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 13 of 121 Python Form Basics To Advanced

print("\nlooping through the set elements ... ")


for i in months:
print(i)

Example # 8 Using remove() function


months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.remove("January");
months.remove("May");
print("\nPrinting the modified set...");
print(months)
Python Set Operations
Set can be performed mathematical operation such as union, intersection, difference,
and symmetric difference.
Union of two Sets
To combine two or more sets into one set in
Python, use the union() function. As parameters,
one or more sets may be passed to the union()
function.

Example # 9 : using union | operator


Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1|Days2) #printing the union of the sets
Example # 10 : using union() method
Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
Days2 = {"Friday","Saturday","Sunday"}

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 14 of 121 Python Form Basics To Advanced

print(Days1.union(Days2)) #printing the union of the sets


Example # 11
# Create three sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}

# Find the common elements between the three sets


common_elements = set1.union(set2, set3)

# Print the common elements


print(common_elements)
The intersection of two sets
To discover what is common between two or more sets in
Python, apply the intersection () function. One or more
sets can also be used as the intersection () function
parameters.
Example # 12 : Using & operator
Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday","Tuesday","Sunday", "Friday"}
print(Days1&Days2) #prints the intersection of the two sets
Example # 13: Using intersection() method
set1 = {"Devansh","John", "David", "Martin"}
set2 = {"Steve", "Milan", "David", "Martin"}
print(set1.intersection(set2)) #prints the intersection of the two sets
Example # 14:
set1 = {1,2,3,4,5,6,7}
set2 = {1,2,20,32,5,9}

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 15 of 121 Python Form Basics To Advanced

set3 = set1.intersection(set2)
print(set3)
The intersection_update() method
The intersection_update() method removes the items from the original set that are not
present in both the sets (all the sets if more than one are specified).
Example # 15
a = {"ali", "bilal", "jamal"}
b = {"kamran", "bilal", "sultan"}
c = {"ali”, “bilal", "zia"}

a.intersection_update(b, c)
print(a)
Difference between the two sets
The difference of two sets can be calculated by using
the subtraction (-) operator or intersection() method.

Example # 16 : Using subtraction ( - ) operator


Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}
Example # 7 : Using difference() method
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and Days2

Topic # 22 : - Python Dictionary


Dictionaries are a useful data structure for storing data in Python because they are
capable of imitating real-world data arrangements where a certain value exists for a
given key.
1. The data is stored as key-value pairs using a Python dictionary.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 16 of 121 Python Form Basics To Advanced

2. This data structure is mutable


3. The components of dictionary were made using keys and values.
4. Keys must only have one component.
5. Values can be of any type, including integer, list, and tuple.
Creating the Dictionary
Curly brackets are the simplest way to generate a Python dictionary, although there
are other approaches as well. With many key-value pairs surrounded in curly brackets
and a colon separating each key from its value, the dictionary can be built. (:). The
following provides the syntax for defining the dictionary.
Syntax:
Dict = {"Name": "Gayle", "Age": 25}
Example # 1
Employee = {"Name": "Johnny", "Age": 32, "salary":26000,"Company":"^TCS"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Example # 2
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)

# Creating a Dictionary

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 17 of 121 Python Form Basics To Advanced

# with each item as a Pair


Dict = dict([(4, 'amy'), (2, ‘sardar’)])
print("\nDictionary with each item as a pair: ")
print(Dict)
Accessing the dictionary values
To access data contained in lists and tuples, indexing has been studied. The keys of the
dictionary can be used to obtain the values because they are unique from one another.
Example # 3
Employee = {"Name": "Azeem", "Age": 35, "salary":45000,"Company":"PICT"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
Adding Dictionary Values
The dictionary is a mutable data type, and utilising the right keys allows you to change
its values. Dict[key] = value and the value can both be modified. An existing value can
also be updated using the update() method.
Example # 4:
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements to dictionary one at a time


Dict[0] = 'Ali'
Dict[2] = 'Pasha'

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 18 of 121 Python Form Basics To Advanced

Dict[3] = 'Zaheer'
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Adding set of values


# with a single Key
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[3] = 'PICT'
print("\nUpdated key value: ")
print(Dict)
Deleting Elements using del Keyword
The items of the dictionary can be deleted by using the del keyword as given below.
Example # 5
Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 19 of 121 Python Form Basics To Advanced

print("Deleting the dictionary: Employee");


del Employee
print("Lets try to print it again ");
print(Employee)
Deleting Elements using pop() Method
The pop() method is one of the ways to get rid of elements from a dictionary. In this
post, we'll talk about how to remove items from a Python dictionary using the pop()
method.
Example # 6
# Creating a Dictionary
Dict1 = {1: 'JavaTpoint', 2: 'Educational', 3: 'Website'}
# Deleting a key
# using pop() method
pop_key = Dict1.pop(2)
print(Dict1)
Iterating Dictionary
A dictionary can be iterated using for loop as given below.
Example # 7
# for loop to print all the keys of a dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee:
print(x)
Properties of Dictionary Keys
1. In the dictionary, we cannot store multiple values for the same keys. If we pass more
than one value for a single key, then the value which is last assigned is considered as
the value of the key.
Example #8
Employee={"Name":"John","Age":29,"Salary":25000,"Company":"WIPRO","Name":
"John"}

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 20 of 121 Python Form Basics To Advanced

for x,y in Employee.items():


print(x,y)
2. The key cannot belong to any mutable object in Python. Numbers, strings, or tuples
can be used as the key, however mutable objects like lists cannot be used as the key in
a dictionary.
Example # 9
Employee = {"Name": "Sardar", "Age": 35, "salary":96000,"Company":"Ms",[100,201,301]:"D
epartment ID"}
for x,y in Employee.items():
print(x,y)
Built-in Dictionary Functions
A few of the Python methods can be combined with a Python dictionary.
len()
The dictionary's length is returned via the len() function in Python. The string is
lengthened by one for each key-value pair.
Example # 10
dict = {1: "Ayan", 2: "Aryan", 3: "Sufyan", 4: "Zafran"}
len(dict)
any()
Like how it does with lists and tuples, the any() method returns True indeed if one
dictionary key does have a Boolean expression that evaluates to True.
Example # 11
dict = {1: "Ayan", 2: "Aryan", 3: "Sufyan", 4: "Zafran"}
any({'':'','':'','3':''})
all()
Unlike in any() method, all() only returns True if each of the dictionary's keys contain a
True Boolean value.
Example # 12
dict = {1: "Ayan", 2: "Aryan", 3: "Sufyan", 4: "Zafran"}

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 21 of 121 Python Form Basics To Advanced

all({1:'',2:'','':''})
sorted()
Like it does with lists and tuples, the sorted() method returns an ordered series of the
dictionary's keys. The ascending sorting has no effect on the original Python dictionary.
Example # 13
dict = {5: "Ayan", 4: "Aryan", 3: "Sufyan", 6: "Zafran"}
sorted(dict)
Built-in Dictionary methods
clear()
It is mainly used to delete all the items of the dictionary.
Example # 14
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# clear() method
dict.clear()
print(dict)
copy()
It returns a shallow copy of the dictionary which is created.
Example #15
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# copy() method
dict_demo = dict.copy()
print(dict_demo)
pop()
It mainly eliminates the element using the defined key.
Example # 16
# dictionary methods

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 22 of 121 Python Form Basics To Advanced

dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}


# pop() method
dict_demo = dict.copy()
x = dict_demo.pop(1)
print(x)
popitem()
removes the most recent key-value pair entered
Example # 17
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# popitem() method
dict_demo.popitem()
print(dict_demo)
keys()
It returns all the keys of the dictionary.
Example # 18
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# keys() method
print(dict_demo.keys())
items()
It returns all the key-value pairs as a tuple.
Example # 19
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# items() method
print(dict_demo.items())

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 23 of 121 Python Form Basics To Advanced

get()
It is used to get the value specified for the passed key.
Example # 20
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# get() method
print(dict_demo.get(3))
update()
It mainly updates all the dictionary by adding the key-value pair of dict2 to this
dictionary.
Example # 21
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# update() method
dict_demo.update({3: "TCS"})
print(dict_demo)
values()
It returns all the values of the dictionary with respect to given input.
Example # 22
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# values() method
print(dict_demo.values())

Topic # 23 : - Python Functions


What are Python Functions?
A collection of related assertions that carry out a mathematical, analytical, or
evaluative operation is known as a function.
It aids in maintaining the program's uniqueness, conciseness, and structure.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 24 of 121 Python Form Basics To Advanced

Advantages of Python Functions


1. Pause We can stop a program from repeatedly using the same code block by
including functions.
2. Once defined, Python functions can be called multiple times and from any
location in a program.
3. Our Python program can be broken up into numerous, easy-to-follow functions
if it is significant.
4. The ability to return as many outputs as we want using a variety of arguments is
one of Python's most significant achievements.
Syntax
# An example Python Function
def function_name( parameters ):
# code block
Example # 1
def square( num ):
"""
This function computes the square of the number.
"""
return num**2
object_ = square(6)
print( "The square of the given number is: ", object_ )
Calling a Function
Calling a Function To define a function, use the def keyword to give it a name, specify
the arguments it must receive, and organize the code block.
When the fundamental framework for a function is finished, we can call it from
anywhere in the program. An illustration of how to use the a_function function can be
found below.
Example # 2
# Defining a function
def a_function( string ):
"This prints the value of length of string"

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 25 of 121 Python Form Basics To Advanced

return len(string)

# Calling the function we defined


print( "Length of the string Functions is: ", a_function( "Functions" ) )
print( "Length of the string Python is: ", a_function( "Python" ) )
Pass by Reference vs. Pass by Value
In the Python programming language, all parameters are passed by reference. It shows
that if we modify the worth of contention within a capability, the calling capability will
similarly mirror the change. For instance,
Example # 3
# Example Python Code for Pass by Reference vs. Value
# defining the function
def square( item_list ):
'''''''This function will find the square of items in the list'''
squares = [ ]
for l in item_list:
squares.append( l**2 )
return squares

# calling the defined function


my_list = [17, 52, 8];
my_result = square( my_list )
print( "Squares of the list are: ", my_result )
Function Arguments
The following are the types of arguments that we can use to call a function:
• Default arguments
• Keyword arguments
• Required arguments
• Variable-length arguments

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 26 of 121 Python Form Basics To Advanced

1) Default Arguments
A default contention is a boundary that takes as information a default esteem,
assuming that no worth is provided for the contention when the capability is called. The
following example demonstrates default arguments.
Example # 4
# Python code to demonstrate the use of default arguments
# defining a function
def function( n1, n2 = 20 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling the function and passing only one argument
print( "Passing only one argument" )
function(30)
# Now giving two arguments to the function
print( "Passing two arguments" )
function(50,30)
2) Keyword Arguments
Keyword arguments are linked to the arguments of a called function.
One more method for utilizing watchwords to summon the capability() strategy is as
per the following:
Example # 5
# Python code to demonstrate the use of keyword arguments
# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling function and passing arguments without using keyword
print( "Without using keyword" )

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 27 of 121 Python Form Basics To Advanced

function( 50, 30)


# Calling function and passing arguments using keyword
print( "With using keyword" )
function( n2 = 50, n1 = 30)
3) Required Arguments
Required arguments are those supplied to a function during its call in a predetermined
positional sequence.
Example # 6
# Python code to demonstrate the use of default arguments
# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)

# Calling function and passing two arguments out of order, we need num1 to be 20 and
num2 to be 30
print( "Passing out of order arguments" )
function( 30, 20 )

# Calling function and passing only one argument


print( "Passing only one argument" )
try:
function( 30 )
except:
print( "Function needs two positional arguments" )
4) Variable-Length Arguments
This can be accomplished with one of two types of characters:
"args" and "kwargs" refer to arguments not based on keywords.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 28 of 121 Python Form Basics To Advanced

Example # 7
# Python code to demonstrate the use of variable-length arguments
# Defining a function
def function( *args_list ):
ans = []
for l in args_list:
ans.append( l.upper() )
return ans
# Passing args arguments
object = function('Python', 'Functions', 'tutorial')
print( object )

# defining a function
def function( **kargs_list ):
ans = []
for key, value in kargs_list.items():
ans.append([key, value])
return ans
# Paasing kwargs arguments
object = function(First = "Python", Second = "Functions", Third = "Tutorial")
print(object)
return Statement
When a defined function is called, a return statement is written to exit the function and
return the calculated value.
Syntax:
return < expression to be returned as output >

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 29 of 121 Python Form Basics To Advanced

The return statement can be an argument, a statement, or a value, and it is provided as


output when a particular job or function is finished. A declared function will return an
empty string if no return statement is written.
Example # 8
# Python code to demonstrate the use of return statements
# Defining a function with return statement
def square( num ):
return num**2

# Calling function and passing arguments.


print( "With return statement" )
print( square( 52 ) )

# Defining a function without return statement


def square( num ):
num**2

# Calling function and passing arguments.


print( "Without return statement" )
print( square( 52 ) )
The Anonymous Functions
Since we do not use the def keyword to declare these kinds of Python functions, they
are unknown. The lambda keyword can define anonymous, short, single-output
functions.
Arguments can be accepted in any number by lambda expressions; However, the
function only produces a single value from them. They cannot contain multiple
instructions or expressions. Since lambda needs articulation, a mysterious capability
can't be straightforwardly called to print.
Lambda functions can only refer to variables in their argument list and the global
domain name because they contain their distinct local domain.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 30 of 121 Python Form Basics To Advanced

Syntax
Lambda functions have exactly one line in their syntax:
lambda [argument1 [,argument2... .argumentn]] : expression
Example # 9
# Python code to demonstrate ananymous functions
# Defining a function
lambda_ = lambda argument1, argument2: argument1 + argument2;

# Calling the function and passing values


print( "Value of the function is : ", lambda_( 20, 30 ) )
print( "Value of the function is : ", lambda_( 40, 50 ) )

Topic # 24 :- Scope and Lifetime of Variables


A variable's scope refers to the program's domain wherever it is declared. A
capability's contentions and factors are not external to the characterized capability.
They only have a local domain as a result.
The length of time a variable remains in RAM is its lifespan. The lifespan of a function is
the same as the lifespan of its internal variables. When we exit the function, they are
taken away from us. As a result, the value of a variable in a function does not persist
from previous executions.
Example # 1
# Python code to demonstrate scope and lifetime of variables
#defining a function to print a number.
def number( ):
num = 50
print( "Value of num inside the function: ", num)

num = 10
number()
print( "Value of num outside the function:", num)

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 31 of 121 Python Form Basics To Advanced

Factors past the capability are available inside the capability. The impact of these
variables is global. We can retrieve their values within the function, but we cannot alter
or change them. The value of a variable can be changed outside of the function if it is
declared global with the keyword global.

Topic # 25 :- Python Turtle Programming


Turtle is a Python library which used to create graphics, pictures, and games. It was
developed by Wally Feurzeig, Seymour Parpet and Cynthina Slolomon in 1967. It was a
part of the original Logo programming language.
The Logo programming language was popular among the kids because it enables us to
draw attractive graphs to the screen in the simple way. It is like a little object on the
screen, which can move according to the desired position. Similarly, turtle library
comes with the interactive feature that gives the flexibility to work with Python.
Introduction
Turtle is a pre-installed library in Python that is similar to the virtual canvas that we
can draw pictures and attractive shapes. It provides the onscreen pen that we can use
for drawing.
It is beneficial to the children and for the experienced programmer because it allows
designing unique shapes, attractive pictures, and various games. We can also design
the mini games and animation. In the upcoming section, we will learn to various
functionality of turtle library.
Getting started with turtle
Before working with the turtle library, we must ensure the two most essential things to
do programming.
1. Python Environment - We must be familiar with the working Python
environment. We can use applications such as IDLE or Jupiter Notebook. We can
also use the Python interactive shell.
2. Python Version - We must have Python 3 in our system; if not, then download it
from Python's official website.
3. The turtle is built in library so we don't need to install separately. We just need
to import the library into our Python environment.
4. The Python turtle library consists of all important methods and functions that
we will need to create our designs and images. Import the turtle library using
the following command.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 32 of 121 Python Form Basics To Advanced

import turtle
Now, we can access all methods and functions.
First, we need to create a dedicated window
where we carry out each drawing command.
We can do it by initializing a variable for it.
s = turtle.getscreen()

It will look like an above image and the little


triangle in the middle of the screen is a turtle. If the screen is not appearing in your
computer system, use the below code.
Example # 1
# Creating turtle screen
s = turtle.getscreen()
# To stop the screen to display
turtle.mainloop()

The screen same as the canvas and turtle acts like a pen. You can move the turtle to
design the desired shape. The turtle has certain changeable features such as color,
speed, and size. It can be moved to a specific direction, and move in that direction
unless we tell it otherwise.
Programming with turtle
First, we need to learn to move the turtle all direction as we want. We can customize
the pen like turtle and its environment. Let's learn the couple of commands to perform
a few specific tasks.
Turtle can be moved in four directions.
➢ Forward
➢ Backward
➢ Left
➢ Right

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 33 of 121 Python Form Basics To Advanced

Turtle motion
The turtle can move forward and backward in direction that it's facing. Let's see the
following functions.
forward(distance) or turtle.fd(distance) - It moves the turtle in the forward direction by
a certain distance. It takes one parameter distance, which can be an integer or float.
Example - 2:
import turtle
# Creating turtle screen
t = turtle.Turtle()
# To stop the screen to display

t.forward(100)
turtle.mainloop()

back(distance) or turtle.bk or turtle.backward(distance) - This method moves the turtle


in the opposite direction the turtle is headed. It doesn't change the turtle heading.
Example - 3:
import turtle
# Creating turtle screen
t = turtle.Turtle()
# Move turtle in opposite direction
t.backward(100)
# To stop the screen to display
turtle.mainloop()

right(angle) or turtle.rt(angle) - This method moves the turtle right by angle units.
Example - 4:
import turtle

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 34 of 121 Python Form Basics To Advanced

# Creating turtle screen


t = turtle.Turtle()

t.heading()
# Move turtle in opposite direction
t.right(25)

t.heading()
# To stop the screen to display
turtle.mainloop()
Example -5
import turtle
# Creating turtle screen
t = turtle.Turtle()

t.heading()
# Move turtle in left
t.left(100)

t.heading()
# To stop the screen to display
turtle.mainloop()

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 35 of 121 Python Form Basics To Advanced

Example - 6
import turtle
# Creating turtle screen
t = turtle.Turtle()
# Move turtle with coordinates
t.goto(100, 80)
# To stop the screen to display
turtle.mainloop()

Drawing a Shape
We discussed the movement of the turtle. Now, we learn to move on to making actual
shape. First, we draw the polygon since they all consist of straight lines connected at
the certain angles. Let's understand the following example.
Example - 7
t.fd(100)
t.rt(90)
t.fd(100)
t.rt(90)
t.fd(100)
t.rt(90)
t.fd(100)

Drawing Preset Figures


Suppose you want to draw a circle. If you attempt to draw it in the same way as you
drew the square, it would be extremely tedious, and you'd have to spend a lot of time
just for that one shape. Thankfully, the Python turtle library provides a solution for this.
You can use a single command to draw a circle.
circle( radius, extent = None, steps = an integer ) - It is used to draw the circle to the
screen. It takes three arguments.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 36 of 121 Python Form Basics To Advanced

radius - It can be a number.


extent - It can be a number or None.
steps - It can be an integer.
The circle is drawn with the given radius. The extent determines which part of circle is
drawn and if the extent is not provided or none, then draw the entire circle. Let's
understand the following example.
Example - 8
import turtle
# Creating turtle screen
t = turtle.Turtle()

t.circle(50)

turtle.mainloop()

Example - 9
import turtle
# Creating turtle screen
t = turtle.Turtle()

t.dot(50)

turtle.mainloop()

Changing the Screen Color


By default, the turtle screen is opened with the white background. However, we can
modify the background color of the screen using the following function.
Example - 10

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 37 of 121 Python Form Basics To Advanced

import turtle
# Creating turtle screen
t = turtle.Turtle()

turtle.bgcolor("red")

turtle.mainloop()
Output:

Adding Image to the background


Same as the screen background color, we can add the background image using the
following function.
bgpic (picname=None) - It sets the background image or return name of current
background image. It takes one argument picname which can be a string, name of a
gif-file or "nopic" or "none". If the picname is "nopic", delete the background image.
Let's see the following example.
Example - 11
import turtle
# Creating turtle turtle
t = turtle.Turtle()

turtle.bgpic()

turtle.bgpic(r"C:\Users\DEVANSH SHARMA\Downloads\person.jpg")
turtle.bgpic()

turtle.mainloop()

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 38 of 121 Python Form Basics To Advanced

Changing the Image Size


We can change the image size using the screensize() function. The syntax is given
below.
Syntax -
turtle.screensize(canvwidth = None, canvheight = None, bg = None)
Parameter - It takes three parameters.
canvwidth - It can be a positive number, new canvas width in pixel.
canvheight - It can be a positive number, new height of the canvas in pixel.
bg - It is colorstring or color-tuple. New background color.
Let's understand the following example.
Example - 12
import turtle
# Creating turtle turtle
t = turtle.Turtle()

turtle.screensize()

turtle.screensize(1500,1000)
turtle.screensize()

turtle.mainloop()
Changing the Screen Title
Sometimes, we want to change the title of the screen. By default, it shows the Python
tutorial graphics. We can make it personal such as "My First Turtle
Program" or "Drawing Shape with Python". We can change the title of the screen using
the following function.
turtle.Title("Your Title")
Let's see the example.
Example - 13

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 39 of 121 Python Form Basics To Advanced

import turtle
# Creating turtle
t = turtle.Turtle()

turtle.title("My Turtle Program")

turtle.mainloop()
Output:

Changing the Pen Size


We can increase or decrease the turtle's size according the requirement. Sometimes,
we need thickness in the pen. We can do this using the following example.
Example -14
import turtle
# Creating turtle turtle
t = turtle.Turtle()

t.pensize(4)
t.forward(200)

turtle.mainloop()

Pen Color Control


By default, when we open a new screen, the turtle comes up with the black color and
draws with black ink. We can change it according the two things.
We can change the color of the turtle, which is a fill color.
We can change the pen's color, which basically a change of the outline or the ink color.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 40 of 121 Python Form Basics To Advanced

We can also change both the pen color and turtle color if we want. We suggest
increasing the size of the turtle that changes in the color can be clearly visible. Let's
understand the following code.
Example - 15
import turtle
# Creating turtle turtle
t = turtle.Turtle()

# Increase the turtle size


t.shapesize(3,3,3)

# fill the color


t.fillcolor("blue")

Customization in One line


Suppose we want multiple changes within the turtle; we can do it by using just one line.
Below are a few characteristics of the turtle.
The pen color should be red.
The fill color should be orange.
The pen size should be 10.
The pen speed should 7
The background color should be blue.
Let's see the following example.
Example - 16
import turtle
# Creating turtle
t = turtle.Turtle()

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 41 of 121 Python Form Basics To Advanced

t.pencolor("red")
t.fillcolor("orange")
t.pensize(10)
t.speed(7)
t.begin_fill()
t.circle(75)
turtle.bgcolor("blue")
t.end_fill()

turtle.mainloop()
Change the Pen Direction
By default, the turtle points to the right on the screen. Sometimes, we require moving
the turtle to the other side of the screen itself. To accomplish this, we can use
the penup() method. The pendown() function uses to start drawing again. Consider the
following example.
Example - 17
import turtle
# Creating turtle
t = turtle.Turtle()

t.fd(100)
t.rt(90)
t.penup()
t.fd(100)
t.rt(90)
t.pendown()
t.fd(100)
t.rt(90)

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 42 of 121 Python Form Basics To Advanced

t.penup()
t.fd(100)
t.pendown()

turtle.mainloop()
Clearing Screen
We have covered most of designing concepts of the turtle. Sometimes, we need a clear
screen to draw more designs. We can do it using the following function.
t.clear()
The above method will clear the screen so that we can draw more designs. This
function only removes the existing designs or shapes not make any changes in
variable. The turtle will remain in the same position.
Resetting the Environment
We can also reset the current working using the reset function. It restores
the turle's setting and clears the screen. We just need to use the following function.
t.reset
All tasks will be removed and the turtle back to its home position. The default settings
of turtle, such as color, size, and shape and other features will be restored.
We have learned the basic fundamental of the turtle programming. Now, we will
discuss a few essential and advanced concepts of the turtle library.
Leaving a Stamp
We can leave the stamp of turtle on the screen. The stamp is nothing but an imprint of
the turtle. Let's understand the following example.
Example - 18
import turtle
# Creating turtle
t = turtle.Turtle()
t.stamp()

t.fd(200)

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 43 of 121 Python Form Basics To Advanced

t.stamp()

t.fd(100)

turtle.mainloop()
Cloning of a turtle
Sometimes, we look for the multiple turtle to design a unique shape. It provides the
facility to clone the current working turtle into the environment and we can move both
turtle on the screen. Let's understand the following example.
Example - 19
import turtle
# Creating turtle
t = turtle.Turtle()

c = t.clone()
t.color("blue")
c.color("red")
t.circle(20)
c.circle(30)
for i in range(40, 100, 10):
c.circle(i)

turtle.mainloop()
Example - 20
import turtle
# Creating turtle
t = turtle.Turtle()
s = turtle.Screen()

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 44 of 121 Python Form Basics To Advanced

s.bgcolor("black")

turtle.pensize(2)

# To design curve
def curve():
for i in range(200):
t.right(1)
t.forward(1)

t. speed(3)
t.color("red", "pink")

t.begin_fill()
t.left(140)
t.forward(111.65)
curve()

t.left(120)
curve()
t.forward(111.65)
t.end_fill()
t.hideturtle()

turtle.mainloop()

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 45 of 121 Python Form Basics To Advanced

Topic # 26 :- Python read csv file


A csv stands for "comma separated values", which is defined as a simple file format
that uses specific structuring to arrange tabular data. It stores tabular data such as
spreadsheet or database in plain text and has a common format for data interchange.
A csv file opens into the excel sheet, and the rows and columns data define the
standard format.
Reading CSV files
Python provides various functions to read csv file. Few of them are discussed below as.
To see examples, we must have a csv file. Let's consider an example data in the
python.csv file as

Name Age City

Ram 27 Mumbai

Bheem 29 Pune

Sita 23 Delhi

1. Using csv.reader() function


In Python, the csv.reader() module is used to read the csv file. It takes each row of the
file and makes a list of all the columns.
Example # 1
import csv
def main():
# To Open the CSV file
with open(' python.csv ', newline = '') as csv_file:
csv_read = csv.reader( csv_file, delimiter = ',')

# To Read and display each row


for row in csv_read:
print(row)

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 46 of 121 Python Form Basics To Advanced

if __name__ == '__main__':
main()
2. Read a CSV into a Dictionary
We can also use DictReader() function to read the csv file directly into a dictionary
rather than deal with a list of individual string elements.
Example # 2
import csv
with open('python.csv', mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
line_count = 0

for row in csv_reader:


if line_count == 0:
print( f'The column names are as follows : {", ".join(row)}' )
line_count += 1

print( f'\t{row[ " Name " ]} lives in {row[" City "]} department and is {row[" Age "]} y
ears old. ')
line_count += 1

print(f'Processed {line_count} lines.')


3. Reading csv files with Pandas
The Pandas is defined as an open-source library which is built on the top of the NumPy
library. It provides fast analysis, data cleaning, and preparation of the data for the user.
Reading the csv file into a pandas DataFrame is quick and straight forward. We don't
need to write enough lines of code to open, analyze, and read the csv file in pandas and
it stores the data in DataFrame. Here, we are taking a slightly more complicated file to
read, called hrdata.csv, which contains data of company employees.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 47 of 121 Python Form Basics To Advanced

Example# 3
Code
import pandas as pd
# Read the CSV file into a DataFrame
df = pd.read_csv(' hrdata.csv ')

# Print the DataFrame


print(df)

Topic # 27 :- Python Write CSV File


Python CSV Module Functions
The CSV module work is to handle the CSV files to read/write and get data from
specified columns. There are different types of CSV functions, which are as follows:
• csv.field_size_limit - It returns the current maximum field size allowed by the
parser.
• csv.get_dialect - Returns the dialect associated with a name.
• csv.list_dialects - Returns the names of all registered dialects.
• csv.reader - Read the data from a CSV file
• csv.register_dialect - It associates dialect with a name, and name must be a
string or a Unicode object.
• csv.writer - Write the data to a CSV file
• csv.unregister_dialect - It deletes the dialect, which is associated with the name
from the dialect registry. If a name is not a registered dialect name, then an
error is being raised.
• csv.QUOTE_ALL - It instructs the writer objects to quote all fields.
• csv.QUOTE_MINIMAL - It instructs the writer objects to quote only those fields
which contain special characters such as quotechar, delimiter, etc.
• csv.QUOTE_NONNUMERIC - It instructs the writer objects to quote all the non-
numeric fields.
• csv.QUOTE_NONE - It instructs the writer object never to quote the fields.
• Writing CSV Files

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 48 of 121 Python Form Basics To Advanced

Let's write the following data to a CSV File.


data = [{'Rank': 'B', 'first_name': 'Parker', 'last_name': 'Brian'},
{'Rank': 'A', 'first_name': 'Smith', 'last_name': 'Rodriguez'},
{'Rank': 'C', 'first_name': 'Tom', 'last_name': 'smith'},
{'Rank': 'B', 'first_name': 'Jane', 'last_name': 'Oscar'},
{'Rank': 'A', 'first_name': 'Alex', 'last_name': 'Tim'}]
Example # 1
with open('Python.csv', 'w') as csvfile:
fieldnames = ['first_name', 'last_name', 'Rank']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

writer.writeheader()
writer.writerow({'Rank': 'B', 'first_name': 'Parker', 'last_name': 'Brian'})
writer.writerow({'Rank': 'A', 'first_name': 'Smith',
'last_name': 'Rodriguez'})
writer.writerow({'Rank': 'B', 'first_name': 'Jane', 'last_name': 'Oscar'})
writer.writerow({'Rank': 'B', 'first_name': 'Jane', 'last_name': 'Loive'})

print("Writing complete")
Write a CSV into a Dictionary
We can also use the class DictWriter to write the CSV file directly into a dictionary.
A file named as python.csv contains the following data:
Parker, Accounting, November
Smith, IT, October
Example # 2
import csv
with open('python.csv', mode='w') as csv_file:

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 49 of 121 Python Form Basics To Advanced

fieldnames = ['emp_name', 'dept', 'birth_month']


writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'emp_name': 'Parker', 'dept': 'Accounting', 'birth_month': 'November'})

writer.writerow({'emp_name': 'Smith', 'dept': 'IT', 'birth_month': 'October'})

Writing CSV Files Using Pandas


Pandas is defined as an open source library which is built on the top of Numpy library.
It provides fast analysis, data cleaning and preparation of the data for the user.
It is as easy as reading the CSV file using pandas. You need to create the DataFrame,
which is a two-dimensional, heterogeneous tabular data structure and consists of
three main components- data, columns, and rows. Here, we take a slightly more
complicated file to read, called hrdata.csv, which contains data of company employees.
Name,Hire Date,Salary,Leaves Remaining
John Idle,08/15/14,50000.00,10
Smith Gilliam,04/07/15,65000.00,8
Parker Chapman,02/21/14,45000.00,10
Jones Palin,10/14/13,70000.00,3
Terry Gilliam,07/22/14,48000.00,7
Michael Palin,06/28/13,66000.00,8
Example # 3
import pandas
df = pandas.read_csv('hrdata.csv',
index_col='Employee',
parse_dates=['Hired'],
header=0,
names=['Employee', 'Hired', 'Salary', 'Sick Days'])
df.to_csv('hrdata_modified.csv')

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 50 of 121 Python Form Basics To Advanced

Topic # 28 :- Python read excel file


Excel is a spreadsheet application which is developed by Microsoft. It is an easily
accessible tool to organize, analyze, and store the data in tables.
Excel Documents
An Excel spreadsheet document is called a workbook which is saved in a file
with .xlsx extension.
Reading from an Excel file
First, you need to write a command to install the xlrd module.
pip install xlrd
Creating a Workbook
A workbook contains all the data in the excel file.

Example # 1
# Import the xlrd module
import xlrd

# Define the location of the file


loc = ("path of file")

# To open the Workbook


wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

# For row 0 and column 0

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 51 of 121 Python Form Basics To Advanced

sheet.cell_value(0, 0)
Reading from the Pandas
Pandas is defined as an open-source library which is built on the top of the NumPy
library. It provides fast analysis, data cleaning, and preparation of the data for the user
and supports both xls and xlsx extensions from the URL.
It is a python package which provides a beneficial data structure called a data frame.
Example # 2
import pandas as pd

# Read the file


data = pd.read_csv(".csv", low_memory=False)

# Output the number of rows


print("Total rows: {0}".format(len(data)))

# See which headers are available


print(list(data))
Reading from the openpyxl
First, we need to install an openpyxl module using pip from the command line.
pip install openpyxl
After that, we need to import the module.
Example # 3
import openpyxl
my_wb = openpyxl.Workbook()
my_sheet = my_wb.active
my_sheet_title = my_sheet.title
print("My sheet title: " + my_sheet_title)

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 52 of 121 Python Form Basics To Advanced

Topic # 29 :- Python Write Excel File


The Python write excel file is used to perform the multiple operations on a spreadsheet
using the xlwt module. It is an ideal way to write data and format information to files
with .xls extension.
Write Excel File Using xlsxwriter Module
We can also write the excel file using the xlsxwriter module. It is defined as a Python
module for writing the files in the XLSX file format. It can also be used to write text,
numbers, and formulas to multiple worksheets. Also, it supports features such as
charts, formatting, images, page setup, auto filters, conditional formatting, and many
others.
We need to use the following command to install xlsxwriter module:
pip install xlsxwriter
Write Excel File Using openpyxl Module
It is defined as a package which is generally recommended if you want to read and
write .xlsx, xlsm, xltx, and xltm files. You can check it by running type(wb).
The load_workbook() function takes an argument and returns a workbook object, which
represents the file. Make sure that you are in the same directory where your
spreadsheet is located. Otherwise, you will get an error while importing.
You can easily use a for loop with the help of the range() function to help you to print
out the values of the rows that have values in column 2. If those particular cells are
empty, you will get None.
Writing data to Excel files with xlwt
You can use the xlwt package, apart from the XlsxWriter package to create the
spreadsheets that contain your data. It is an alternative package for writing data,
formatting information, etc. and ideal for writing the data and format information to
files with .xls extension. It can perform multiple operations on the spreadsheet.
It supports features such as formatting, images, charts, page setup, auto filters,
conditional formatting, and many others.
Pandas have excellent methods for reading all kinds of data from excel files. We can
also import the results back to pandas.
Writing Files with pyexcel

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 53 of 121 Python Form Basics To Advanced

You can easily export your arrays back to a spreadsheet by using the save_as()
function and pass the array and name of the destination file to the dest_file_name
argument.
It allows us to specify the delimiter and add dest_delimiter argument. You can pass the
symbol that you want to use as a delimiter in-between " ".
Example # 1
# import xlsxwriter module
import xlsxwriter

book = xlsxwriter.Book('Example2.xlsx')
sheet = book.add_sheet()

# Rows and columns are zero indexed.


row = 0
column = 0

content = ["Parker", "Smith", "John"]

# iterating through the content list


for item in content :

# write operation perform


sheet.write(row, column, item)

# incrementing the value of row by one with each iterations.


row += 1

book.close()

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 54 of 121 Python Form Basics To Advanced

Topic # 30 :- Python IDEs


The term "IDE" refers for "Integrated Development Environment," which is a coding tool
that aids in automating the editing, compiling, testing, and other steps of an SDLC while
making it simple for developers to execute, write, and debug code.
It is specifically made for software development and includes a number of tools that
are used in the creation and testing of the software.
There are some Python IDEs which are as follows:

PyCharm
Spyder
PyDev
Atom
Wing
Jupyter Notebook
Thonny
Rodeo
Microsoft Visual Studio
Eric
PyCharm
The Jet Brains created PyCharm, a cross-platform
Integrated Development Environment (IDE) created
specifically for Python. It is the most popular IDE and is
accessible in both a premium and a free open-source
version. By handling everyday duties, a lot of time is saved.
It is a full-featured Python IDE with a wealth of features
including auto code completion, easy project navigation, quick error checking and
correction, support for remote development, database accessibility, etc.
Features
1. Smart code navigation
2. Errors Highlighting
3. Powerful debugger

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 55 of 121 Python Form Basics To Advanced

4. Supports Python web development frameworks, i.e., Angular JS, Javascript


Spyder

Spyder is a well-known open-source IDE that is best suited


for data research and has a high level of recognition in the
industry. Scientific Python Development Environment is
Spyder's full name. It supports all popular operating systems,
including Windows, MacOS X, and Linux.
A number of features are offered by it, including a localised
code editor, a document viewer, a variable explorer, an
integrated console, etc. It also supports a number of scientific modules, including SciPy
and NumPy.
Features
1. Proper syntax highlighting and auto code completion
2. Integrates strongly with IPython console
3. Performs well in multi-language editor and auto code completion mode
PyDev

As an external plugin for Eclipse, PyDev is one of the most


popular Python IDEs. The Python programmers who have a
background in Java naturally gravitate towards this Python
interpreter because it is so well-liked by users.
In 2003-2004, Aleksandar Totic, who is well known for his
work on the Mosaic browser, contributed to the Pydev
project.
Django integration, code auto-completion, smart and block indents, among other
features, are features of Pydev.
Features
1. Strong Parameters like refactoring, debugging, code analysis, and code
coverage function.
2. It supports virtual environments, Mypy, and black formatter.
3. Also supports PyLint integration, remote debugger, Unit test integration, etc.

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 56 of 121 Python Form Basics To Advanced

Atom

GitHub, a company that was first founded as an open-source,


cross-platform project, is the company that creates Atom. It is
built on the Electron framework, which enables cross-platform
desktop applications utilising Chromium and Node.js and is
dubbed the "Hackable Text Editor for the 21st Century."
Features
1. Visualize the results on Atom without open any other
window.
2. A plugin named "Markdown Preview Plus" provides built-in support for editing
and visualizing Markdown files.
Wing

It's described as a cross-platform IDE with a tonne of useful


features and respectable development support. It is free to
use in its personal edition. The 30-day trial period for the
pro version is provided for the benefit of the developers.
Features
1. Customizable and can have extensions as well.
2. Supports remote development, test-driven development along with the unit test.
Jupyter Notebook

Jupyter is one of the most used Python notebook editors that is


used across the Data Science industry. You can create and edit
notebook documents using this web application, which is based on
the server-client architecture. It utilises Python's interpretive
nature to its fullest potential.
Features
1. Supports markdowns
2. Easy creation and editing of codes
3. Ideal for beginners in data science

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 57 of 121 Python Form Basics To Advanced

Thonny

Thonny is a Python IDE (Integrated Development Environment)


that is open-source, free, and geared towards beginners.
Since its initial release in 2016, it has grown to be a well-liked
option for novice Python coders.
Thonny's user-friendly interface is one of its most
distinguishing qualities. It makes it simple for beginners to
learn Python and debug their programmes because it incorporates a code editor,
debugger, and REPL (Read-Eval-Print-Loop) in a single window. To assist users with
writing proper code, Thonny also has tools like code completion, syntax highlighting,
and error highlighting.
Thonny IDE that works well for teaching and learning programming is Thonny. Software
that highlights syntax problems and aids code completion was created at the
University of Tartu.
Features
1. Simple debugger
2. Supports highlighting errors and auto code completion
Rodeo

When it comes to gathering data and information from many


sources for data science projects, Rodeo is considered one of
the top Python IDEs.
It offers code auto-completion and cross-platform capability.
Features
1. Allows the functions for comparing data, interact, plot, and inspect data.
2. Auto code completion, syntax highlighter, visual file navigator, etc.
Microsoft Visual Studio
Microsoft Visual Studio is an open-source code editor which was
best suited for development and debugging of latest web and
cloud projects. It has its own marketplace for extensions.
An integrated development environment (IDE) called Microsoft
Visual Studio is used to create software for the Windows, Android,

Pict Academy Contact No: - 03135879331


Sardar Azeem Page 58 of 121 Python Form Basics To Advanced

and iOS operating systems. Since its initial release in 1997, it has grown to be a well-
liked software development tool.
Features
1. Supports Python Coding in Visual studio
2. Available in both paid and free version
Eric Python

The Eric Python is a Python-based editor that may be used


for both professional and non-professional tasks.
Since its initial release in 2000, Eric IDE (Integrated
Development Environment) has been a free and open-source
Python IDE. It offers programmers a setting in which to
efficiently write, test, and debug Python programmes since it
is user-friendly and simple to use.
Python 2 and 3 are among the Python versions that are supported by Eric IDE, which
also offers features like code highlighting, code completion, and syntax checking.
Additionally, it contains an integrated debugger that enables programmers to
effectively debug their programmes.
The Eric IDE's plugin system, which enables developers to increase its capabilities, is
one of its primary features. An integrated version control system, a database browser,
and a Python profiler are just a few of the plugins that are available for the Eric IDE.
Features
1. Provides customizable editors, source code folding, and window layouts.
2. Advanced version control and project management capabilities
3. Built-in debugger and task management support.

Pict Academy Contact No: - 03135879331

You might also like