SlideShare a Scribd company logo
1 of 330
Python programming
UNIT-1
What is Python
• Python is a general-purpose, dynamic, high-level,
and interpreted programming language. It supports
Object Oriented programming approach to develop
applications. It is simple and easy to learn and
provides lots of high-level data structures.
• Python is an easy-to-learn yet powerful and versatile
scripting language, which makes it attractive for
Application Development.
• With its interpreted nature, Python's syntax and
dynamic typing make it an ideal language for
scripting and rapid application development.
• Python supports multiple programming patterns,
including object-oriented, imperative, and functional
or procedural programming styles.
• Python is not intended to work in a particular area,
such as web programming. It is a multipurpose
programming language because it can be used with
web, enterprise, 3D CAD, etc.
• We don't need to use data types to declare variable
because it is dynamically typed, so we can write a=10
to assign an integer value in an integer variable.
• Python makes development and debugging fast
because no compilation step is included in Python
development, and the edit-test-debug cycle is very
fast.
• Python has many web-based assets, open-source
projects, and a vibrant community. Learning the
language, working together on projects, and
contributing to the Python ecosystem are all made
very easy for developers.
• Because of its straightforward language framework,
Python is easier to understand and write code in. This
makes it a fantastic programming language for
novices. Additionally, it assists seasoned
programmers in writing clearer, error-free code.
• Python is an open-source, cost-free programming
language. It is utilized in several sectors and
disciplines as a result.
• In Python, code readability and maintainability are
important. As a result, even if the code was
developed by someone else, it is easy to understand
and adapt by some other developer.
• Python has many third-party libraries that can be
used to make its functionality easier. These libraries
cover many domains, for example, web development,
scientific computing, data analysis, and more.
Python Basic Syntax
• There is no use of curly braces or semicolon in Python programming
language. It is English-like language. But Python uses the indentation to
define a block of code. Indentation is nothing but adding whitespace
before the statement when it is needed. For example -
def func():
statement 1
statement 2
…………………
…………………
statement N
• In the above example, the statements that are the same level to the
right belong to the function. Generally, we can use four whitespaces to
define indentation.
• Instead of Semicolon as used in other languages, Python ends its
statements with a NewLine character.
• Python is a case-sensitive language, which means that uppercase and
lowercase letters are treated differently. For example, 'name' and
'Name' are two different variables in Python.
• In Python, comments can be added using the '#'
symbol. Any text written after the '#' symbol is
considered a comment and is ignored by the
interpreter. This trick is useful for adding notes to
the code or temporarily disabling a code block. It
also helps in understanding the code better by some
other developers.
• 'If', 'otherwise', 'for', 'while', 'try', 'except', and
'finally' are a few reserved keywords in Python that
cannot be used as variable names. These terms are
used in the language for particular reasons and have
fixed meanings. If you use these keywords, your
code may include errors, or the interpreter may
reject them as potential new Variables.
Why learn Python?
• Python provides many useful features to the programmer. These
features make it the most popular and widely used language.
We have listed belo
• Easy to use and Learn: Python has a simple and easy-to-
understand syntax, unlike traditional languages like C, C++, Java,
etc., making it easy for beginners to learn.
• Expressive Language: It allows programmers to express complex
concepts in just a few lines of code or reduces Developer's Time.
• Interpreted Language: Python does not require compilation,
allowing rapid development and testing. It uses Interpreter
instead of Compiler.
• Object-Oriented Language: It supports object-oriented
programming, making writing reusable and modular code easy.
• Open Source Language: Python is open source and free to use,
distribute and modify.
• Extensible: Python can be extended with modules written in C,
C++, or other languages.
• Learn Standard Library: Python's standard library contains many
modules and functions that can be used for various tasks, such as
string manipulation, web programming, and more.
• GUI Programming Support: Python provides several GUI frameworks,
such as Tkinter and PyQt, allowing developers to create desktop
applications easily.
• Integrated: Python can easily integrate with other languages and
technologies, such as C/C++, Java, and . NET.
• Embeddable: Python code can be embedded into other applications as
a scripting language.
• Dynamic Memory Allocation: Python automatically manages memory
allocation, making it easier for developers to write complex programs
without worrying about memory management.
• Wide Range of Libraries and Frameworks: Python has a vast collection
of libraries and frameworks, such as NumPy, Pandas, Django, and Flask,
that can be used to solve a wide range of problems.
• Versatility: Python is a universal language in various domains such as
web development, machine learning, data analysis, scientific
computing, and more.
• Large Community: Python has a vast and active community of
developers contributing to its development and offering support. This
makes it easy for beginners to get help and learn from experienced
developers.
• Career Opportunities: Python is a highly popular language in the job
market. Learning Python can open up several career opportunities in
data science, artificial intelligence, web development, and more.
• High Demand: With the growing demand for automation and digital
transformation, the need for Python developers is rising. Many
industries seek skilled Python developers to help build their digital
infrastructure.
• Increased Productivity: Python has a simple syntax and powerful
libraries that can help developers write code faster and more
efficiently. This can increase productivity and save time for developers
and organizations.
• Big Data and Machine Learning: Python has become the go-to
language for big data and machine learning. Python has become
popular among data scientists and machine learning engineers with
libraries like NumPy, Pandas, Scikit-learn, TensorFlow, and more.
Where is Python used?
• Python is a general-purpose, popular programming language, and it is
used in almost every technical field. The various areas of Python use are
given below.
• Data Science: Data Science is a vast field, and Python is an important
language for this field because of its simplicity, ease of use, and
availability of powerful data analysis and visualization libraries like
NumPy, Pandas, and Matplotlib.
• Desktop Applications: PyQt and Tkinter are useful libraries that can be
used in GUI - Graphical User Interface-based Desktop Applications.
There are better languages for this field, but it can be used with other
languages for making Applications.
• Console-based Applications: Python is also commonly used to create
command-line or console-based applications because of its ease of use
and support for advanced features such as input/output redirection and
piping.
• Mobile Applications: While Python is not commonly used for creating
mobile applications, it can still be combined with frameworks like Kivy
or BeeWare to create cross-platform mobile applications.
• Software Development: Python is considered one of the best
software-making languages. Python is easily compatible with
both from Small Scale to Large Scale software.
• Artificial Intelligence: AI is an emerging Technology, and Python
is a perfect language for artificial intelligence and machine
learning because of the availability of powerful libraries such as
TensorFlow, Keras, and PyTorch.
• Web Applications: Python is commonly used in web
development on the backend with frameworks like Django and
Flask and on the front end with tools like JavaScript and HTML.
• Enterprise Applications: Python can be used to develop large-
scale enterprise applications with features such as distributed
computing, networking, and parallel processing.
• 3D CAD Applications: Python can be used for 3D computer-
aided design (CAD) applications through libraries such as
Blender.
• Machine Learning: Python is widely used for machine learning
due to its simplicity, ease of use, and availability of powerful
machine learning libraries.
• Computer Vision or Image Processing Applications: Python can
be used for computer vision and image processing applications
through powerful libraries such as OpenCV and Scikit-image.
• Speech Recognition: Python can be used for speech recognition
applications through libraries such as SpeechRecognition and
PyAudio.
• Scientific computing: Libraries like NumPy, SciPy, and Pandas
provide advanced numerical computing capabilities for tasks
like data analysis, machine learning, and more.
• Education: Python's easy-to-learn syntax and availability of
many resources make it an ideal language for teaching
programming to beginners.
• Testing: Python is used for writing automated tests, providing
frameworks like unit tests and pytest that help write test cases
and generate reports.
• Gaming: Python has libraries like Pygame, which provide a
platform for developing games using Python.
• IoT: Python is used in IoT for developing scripts and applications
for devices like Raspberry Pi, Arduino, and others.
• Networking: Python is used in networking for
developing scripts and applications for network
automation, monitoring, and management.
• DevOps: Python is widely used in DevOps for
automation and scripting of infrastructure
management, configuration management, and
deployment processes.
• Finance: Python has libraries like Pandas, Scikit-learn,
and Statsmodels for financial modeling and analysis.
• Audio and Music: Python has libraries like Pyaudio,
which is used for audio processing, synthesis, and
analysis, and Music21, which is used for music
analysis and generation.
• Writing scripts: Python is used for writing utility
scripts to automate tasks like file operations, web
scraping, and data processing.
Python Popular Frameworks and
Libraries
• Python has wide range of libraries and frameworks widely
used in various fields such as machine learning, artificial
intelligence, web applications, etc. We define some popular
frameworks and libraries of Python as follows.
• Web development (Server-side) - Django Flask, Pyramid,
CherryPy
• GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.
• Machine Learning - TensorFlow, PyTorch, Scikit-learn,
Matplotlib, Scipy, etc.
• Mathematics - Numpy, Pandas, etc.
• BeautifulSoup: a library for web scraping and parsing HTML
and XML
• Requests: a library for making HTTP requests
• SQLAlchemy: a library for working with SQL databases
• Kivy: a framework for building multi-touch
applications
• Pygame: a library for game development
• Pytest: a testing framework for Python
• Django REST framework: a toolkit for building
RESTful APIs
• FastAPI: a modern, fast web framework for
building APIs
• Streamlit: a library for building interactive web
apps for machine learning and data science
• NLTK: a library for natural language processing
Python Features
• Python provides many useful features which make it popular and
valuable from the other programming languages. It supports object-
oriented programming, procedural programming approaches and
provides dynamic memory allocation. We have listed below a few
essential features.
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
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
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.
Python History and Versions
• Python laid its foundation in the late 1980s.
• The implementation of Python was started in December 1989
by Guido Van Rossum at CWI in Netherland.
• In February 1991, Guido Van Rossum published the code
(labeled version 0.9.0) to alt.sources.
• In 1994, Python 1.0 was released with new features like lambda,
map, filter, and reduce.
• Python 2.0 added new features such as list comprehensions,
garbage collection systems.
• On December 3, 2008, Python 3.0 (also called "Py3K") was
released. It was designed to rectify the fundamental flaw of the
language.
• ABC programming language is said to be the predecessor of
Python language, which was capable of Exception Handling and
interfacing with the Amoeba Operating System.
• The following programming languages influence Python:
– ABC language.
– Modula-3
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
• 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 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.
• Here, we are specifying application areas where Python can be applied.
1) Web Applications
We can use Python to develop web applications. It provides
libraries to handle internet protocols such as HTML and
XML, JSON, Email processing, request, beautifulSoup,
Feedparser, etc. One of Python web-framework named
Django is used on Instagram. Python provides many useful
frameworks, and these are given below:
• Django and Pyramid framework(Use for heavy
applications)
• Flask and Bottle (Micro-framework)
• 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.
• Tkinter or Tk
• wxWidgetM
• Kivy (used for writing multitouch applications )
• 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. Python can
develop this kind of application very effectively. It is famous for
having REPL, which means the Read-Eval-Print Loop that makes
it the most suitable language for the command-line
applications.
Python provides many free library or module which helps to build
the command-line apps. The necessary IO libraries are used to
read and write. It helps to parse argument and create console
help text out-of-the-box. There are also advance libraries that
can develop independent console apps.
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.
SCons is used to build control.
Buildbot and Apache Gumps are used for automated continuous compilation and
testing.
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.
Implementing machine learning algorithms require complex mathematical
calculation. Python has many libraries for scientific and numeric such as Numpy,
Pandas, Scipy, Scikit-learn, etc. If you have some basic knowledge of Python, you
need to import libraries on the top of the code. Few popular frameworks of
machine libraries are given below.
SciPy
Scikit-learn
NumPy
Pandas
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.
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.
Gstreamer
Pyglet
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.
Fandango (Popular )
CAMVOX
HeeksCNC
AnyCAD
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
OpenERP, Tryton, Picalo, etc.
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.
OpenCV
Pillow
SimpleITK
How to Install Python
• Installing Python on Windows:
• Download Python:
– Visit the official Python website at https://www.python.org/downloads/windows/.
– Click on the "Downloads" tab.
– Download the latest Python installer for Windows. Choose the installer that corresponds to your system
architecture (32-bit or 64-bit).
• Run the Installer:
– Locate the downloaded installer file (e.g., python-3.x.x.exe) and double-click it to run the installer.
• Customize Installation (Optional):
– You can customize the installation by clicking the "Customize installation" button. However, the default
settings are usually sufficient for most users.
• Installation Options:
– Make sure to check the box that says "Add Python X.X to PATH." This allows you to use Python from the
command line without needing to specify the full path.
• Installation:
– Click the "Install Now" button to begin the installation process.
• Completing the Installation:
– Once the installation is complete, you should see a screen that says "Setup was successful." You can now
close the installer.
• Verify Installation:
– Open the Command Prompt by searching for "cmd" in the Windows Start Menu.
– Type python and press Enter. You should see the Python version information. This confirms that Python is
installed.
• Installing Python on Ubuntu:
• Open the Terminal:
– Press Ctrl+Alt+T to open a terminal window.
• Update Package List:
– Before installing Python, it's a good practice to update
the package list to ensure you're getting the latest
version of Python and its dependencies. Run the
following command:
• sudo apt update
• sudo apt install python3
• python3 --version
• This should display the Python version installed.
First Python Program
• In Python, the most basic program is one that prints a
message to the screen. Here's a "Hello, World!"
program:
• print("Hello, World!")
• Now, let's break it down:
• 1. `print()`: `print` is a Python function used to output
text or data to the console (the terminal or command
prompt). In this case, it's used to print the message
"Hello, World!" to the screen.
• 2. `"Hello, World!"`: This is a string. In Python, strings
are sequences of characters enclosed in either single
(`'`) or double (`"`) quotes. In this case, we're using
double quotes.
• So, when you run this Python program, it will simply
display "Hello, World!" in the console.
• Here's how you can run the program:
1. Save the code in a file with a `.py` extension, like
`hello.py`.
2. Open a terminal or command prompt.
3. Navigate to the directory where you saved the
`hello.py` file.
4. Run the program by typing `python hello.py` and
pressing Enter.
You should see the output:
Hello, World!
Python Variables
• Variable is a name that is used to refer to
memory location. Python variable is also known
as an identifier and used to hold value.
• In Python, we don't need to specify the type of
variable because Python is a infer language and
smart enough to get variable type.
• Variable names can be a group of both the letters
and digits, but they have to begin with a letter or
an underscore.
• It is recommended to use lowercase letters for
the variable name. Rahul and rahul both are two
different variables.
Python Variables
• Variable is a name that is used to refer to
memory location. Python variable is also known
as an identifier and used to hold value.
• In Python, we don't need to specify the type of
variable because Python is a infer language and
smart enough to get variable type.
• Variable names can be a group of both the letters
and digits, but they have to begin with a letter or
an underscore.
• It is recommended to use lowercase letters for
the variable name. Rahul and rahul both are two
different variables.
Identifier Naming:
• Variables are the example of identifiers. An Identifier is
used to identify the literals used in the program. The rules
to name an identifier are given below.
• The first character of the variable must be an alphabet or
underscore ( _ ).
• All the characters except the first character may be an
alphabet of lower-case(a-z), upper-case (A-Z), underscore,
or digit (0-9).
• Identifier name must not contain any white-space, or
special character (!, @, #, %, ^, &, *).
• Identifier name must not be similar to any keyword
defined in the language.
• Identifier names are case sensitive; for example, my name,
and MyName is not the same.
• Examples of valid identifiers: a123, _n, n_9, etc.
• Examples of invalid identifiers: 1a, n%4, n 9, etc.
Declaring Variable and Assigning Values
• Python does not bind us to declare a variable before using
it in the application. It allows us to create a variable at the
required time.
• We don't need to declare explicitly variable in Python.
When we assign any value to the variable, that variable is
declared automatically.
• The equal (=) operator is used to assign value to a
variable.
• Object References
• It is necessary to understand how the Python interpreter
works when we declare a variable. The process of treating
variables is somewhat different from many other
programming languages.
• Python is the highly object-oriented programming
language; that's why every data item belongs to a specific
type of class. Consider the following example.
print("John")
Output:
John
• The Python object creates an integer object and displays it to
the console. In the above print statement, we have created a
string object. Let's check the type of it using the Python built-
in type() function.
type("John")
Output:
<class 'str'>
• In Python, variables are a symbolic name that is a reference or
pointer to an object. The variables are used to denote objects
by that name.
• Let's understand the following example
a = 50
• In the above image, the variable a refers to an integer object.
• Suppose we assign the integer value 50 to a new variable b.
a = 50
b = a
• The variable b refers to the same object that a
points to because Python does not create
another object.
• 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
• In Python, every created object identifies uniquely in Python. Python
provides the guaranteed that no two objects will have the same
identifier. The built-in id() function, is used to identify the object
identifier. Consider the following example.
a = 50
b = a
print(id(a))
print(id(b))
# Reassigned variable a
a = 500
print(id(a))
Output:
140734982691168
140734982691168
2822056960944
• We assigned the b = a, a and b both point to the same object. When we
checked by the id() function it returned the same number. We
reassign a to 500; then it referred to the new object identifier.
Variable Names
• We have already discussed how to declare the valid
variable. Variable names can be any length can have
uppercase, lowercase (A to Z, a to z), the digit (0-9), and
underscore character(_). Consider the following example
of valid variables names.
name = "Devansh"
age = 20
marks = 80.50
print(name)
print(age)
print(marks)
Output:
Devansh
20
80.5
• Consider the following valid variables name.
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)
Output:
A B C D E D E F G F I
• In the above example, we have declared a few valid variable names such
as name, _name_ , etc. But it is not recommended because when we try
to read code, it may create confusion. The variable name should be
descriptive to make code more readable.
• 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.
• 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
• Python allows us to assign a value to multiple variables in
a single statement, which is also known as multiple
assignments.
• We can apply multiple assignments in two ways, either by
assigning a single value to multiple variables or assigning
multiple values to multiple variables. Consider the
following example.
1. Assigning single value to multiple variables
Eg:
x=y=z=50
print(x)
print(y)
print(z)
Output:
50 50 50
2. Assigning multiple values to multiple variables:
Eg:
a,b,c=5,10,15
print a
print b
print c
Output:
5 10 15
• The values will be assigned in the order in which
variables appear.
Python Variable Types
• There are two types of variables in Python - Local variable and Global
variable. Let's understand the following variables.
Local Variable
• Local variables are the variables that declared inside the function and
have scope within the function. Let's understand the following example.
Example -
# Declaring a function
def add():
# Defining local variables. They has scope only within a function
a = 20
b = 30
c = a + b
print("The sum is:", c)
# Calling a function
add()
Output:
The sum is: 50
Explanation:
• In the above code, we declared a function
named add() and assigned a few variables within the
function. These variables will be referred to as the local
variables which have scope only inside the function. If we
try to use them outside the function, we get a following
error.
add()
# Accessing local variable outside the function
print(a)
• Output:
The sum is: 50 print(a) NameError: name 'a' is not defined
• We tried to use local variable outside their scope; it
threw the NameError.
Global Variables
• Global variables can be used throughout the program,
and its scope is in the entire program. We can use
global variables inside or outside the function.
• A variable declared outside the function is the global
variable by default. Python provides
the global keyword to use global variable inside the
function. If we don't use the global keyword, the
function treats it as a local variable. Let's understand
the following example.
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 Javatpoint'
print(x)
mainFunction()
print(x)
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:
• In the above code, we declare a global
variable x and assign a value to it. Next, we
defined a function and accessed the declared
variable using the global keyword inside the
function. Now we can modify its value. Then, we
assigned a new string value to the variable x.
• Now, we called the function and proceeded to
print x. It printed the as newly assigned value of
x.
Delete a variable:
• We can delete the variable using the del keyword. The syntax is given
below.
• Syntax –
• del <variable_name>
• In the following example, we create a variable x and assign value to it. We
deleted variable x, and print it, we get the error "variable x is not
defined". The variable x will no longer use in future.
Example -
# Assigning a value to x
x = 6
print(x)
# deleting a variable.
del x
print(x)
Output:
6
Traceback (most recent call last): File "C:/Users/DEVANSH
SHARMA/PycharmProjects/Hello/multiprocessing.py", line 389, in print(x)
NameError: name 'x' is not defined
Maximum Possible Value of an Integer in Python
• Unlike the other programming languages, Python doesn't have long int
or float data types. It treats all integer values as an int data type. Here,
the question arises. What is the maximum possible value can hold by the
variable in Python? Consider the following example.
• Example –
# A Python program to display that we can store
# large numbers in Python
a = 10000000000000000000000000000000000000000000
a = a + 1
print(type(a))
print (a)
Output:
<class 'int'>
10000000000000000000000000000000000000000001
• As we can see in the above example, we assigned a large integer value
to variable x and checked its type. It printed class <int> not long int.
Hence, there is no limitation number by bits and we can expand to the
limit of our memory.
• Python doesn't have any special data type to store larger numbers.
Print Single and Multiple Variables in Python
• We can print multiple variables within the single print statement. Below
are the example of single and multiple printing values.
Example - 1 (Printing Single Variable)
# printing single value
a = 5
print(a)
print((a))
Output:
5 5
Example - 2 (Printing Multiple Variables)
a = 5
b = 6
# printing multiple variables
print(a,b)
# separate the variables by the comma
Print(1, 2, 3, 4, 5, 6, 7, 8)
Output:
5 6 1 2 3 4 5 6 7 8
Basic Fundamentals:
This section contains the fundamentals of Python, such
as:
i)Tokens and their types.
ii) Comments
a)Tokens:
• The tokens can be defined as a punctuator mark,
reserved words, and each word in a statement.
• The token is the smallest unit inside the given
program.
There are following tokens in Python:
Keywords.
Identifiers.
Literals.
Operators.
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.
a = 5
• We did not specify the type of the variable a, which
has the value five from an integer. The Python
interpreter will automatically interpret the variable as
an integer.
• We can verify the type of the program-used variable
thanks to Python. The type() function in Python
returns the type of the passed variable.
• Consider the following illustration when defining and
verifying the values of various data types.
Program:
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<type 'int'> <type 'str'> <type 'float'>
Standard data types:
• A variable can contain a variety of values. On the
other hand, a person's id must be stored as an
integer, while their name must be stored as a string.
• The storage method for each of the standard data
types that Python provides is specified by Python.
The following is a list of the Python-defined data
types.
Numbers
Sequence Type
Boolean
Set
Dictionary
• The data types will be briefly discussed in this
tutorial section. We will talk about every single
one of them exhaustively later in this
instructional exercise.
Numbers:
• Numeric values are stored in numbers. The
whole number, float, and complex qualities have
a place with a Python Numbers datatype. Python
offers the type() function to determine a
variable's data type. The instance () capability is
utilized to check whether an item has a place
with a specific class.
• When a number is assigned to a variable, Python
generates Number objects. For instance,
Program:
a = 5
print("The type of a", type(a))
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)
)
Output:
The type of a <class 'int'> The type of b <class 'float'>
The type of c <class 'complex'> c is complex number:
True
Python supports three kinds of numerical data.
• 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.
Sequence Type
String
• The sequence of characters in the quotation marks can be
used to describe the string. A string can be defined in
Python using single, double, or triple quotes.
• String dealing with Python is a direct undertaking since
Python gives worked-in capabilities and administrators to
perform tasks in the string.
• When dealing with strings, the operation "hello"+" python"
returns "hello python," and the operator + is used to
combine two strings.
• Because the operation "Python" *2 returns "Python," the
operator * is referred to as a repetition operator.
• The Python string is demonstrated in the following
example.
Example - 1
str = "string using double quotes"
print(str)
s = '''''A multiline
string'''
print(s)
Output:
string using double quotes A multiline string
Look at the following illustration of string handling.
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 a
nd str2
Output:
he o hello javatpointhello javatpoint hello javatpoint
how are you
• List:
• Lists in Python are like arrays in C, but lists can
contain data of different types. The things put
away in the rundown are isolated with a comma
(,) and encased inside square sections [].
• To gain access to the list's data, we can use slice
[:] operators. Like how they worked with strings,
the list is handled by the concatenation operator
(+) and the repetition operator (*).
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)
Output:
[1, 'hi', 'Python', 2] [2] [1, 'hi'] [1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
Tuple:
• In many ways, a tuple is like a list. Tuples, like
lists, also contain a collection of items from
various data types. A parenthetical space ()
separates the tuple's components from one
another.
• Because we cannot alter the size or value of the
items in a tuple, it is a read-only data structure.
• Let's look at a straightforward tuple in action.
Example:
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"
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
Traceback (most recent call last):
File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item
assignment
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.
• Look at the following example.
d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
# 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())
• Output:
1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
Boolean:
• True and False are the two default values for the Boolean
type. These qualities are utilized to decide the given
assertion valid or misleading. The class book indicates this.
False can be represented by the 0 or the letter "F," while
true can be represented by any value that is not zero.
Look at the following example.
# Python program to check the boolean type
print(type(True))
print(type(False))
print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set:
• The data type's unordered collection is Python
Set. It is iterable, mutable(can change after
creation), and has remarkable components. The
elements of a set have no set order; It might
return the element's altered sequence. Either a
sequence of elements is passed through the curly
braces and separated by a comma to create the
set or the built-in function set() is used to create
the set. It can contain different kinds of values.
• Look at the following example.
Program:
# Creating Empty set
set1 = set()
set2 = {'James', 2, 3,'Python'}
#Printing Set value
print(set2)
# Adding element to the set
set2.add(10)
print(set2)
#Removing element from the set
set2.remove(2)
print(set2)
Output:
{3, 'Python', 'James', 2}
{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}
Python Keywords
• Every scripting language has designated words or
keywords, with particular definitions and usage guidelines.
Python is no exception. The fundamental constituent
elements of any Python program are Python keywords.
• This tutorial will give you a basic overview of all Python
keywords and a detailed discussion of some important
keywords that are frequently used.
Introducing 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.
• Python's built-in methods and classes are not the same as
the keywords. Built-in methods and classes are constantly
present; however, they are not as limited in their
application as keywords.
• Assigning a particular meaning to Python
keywords means you can't use them for other
purposes in our code. You'll get a message of
SyntaxError if you attempt to do the same. If you
attempt to assign anything to a built-in method
or type, you will not receive a SyntaxError
message; however, it is still not a smart idea.
• Python contains thirty-five keywords in the most
recent version, i.e., Python 3.8. Here we have
shown a complete list of Python keywords for the
reader's reference.
in distinct versions of Python, the preceding keywords might be changed. Some extras
may be introduced, while others may be deleted. By writing the following statement
into the coding window, you can anytime retrieve the collection of keywords in the
version you are working on.
Code:
# Python program to demonstrate the application of iskeyword()
# importing keyword library which has lists
import keyword
# displaying the complete list using "kwlist()."
print("The set of keywords in this version is: ")
print( keyword.kwlist )
Output:
The set of keywords in this version is : ['False', 'None', 'True',
'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue',
'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global',
'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass',
'raise', 'return', 'try', 'while', 'with', 'yield']
By calling help(), you can retrieve a list of currently offered
keywords:
Code
help("keywords")
Python Literals
Python Literals can be defined as data that is given
in a variable or constant.
• Python supports the following literals:
1. String literals:
• String literals can be formed by enclosing a text
in the quotes. We can use both single as well as
double quotes to create a string.
Example:
"Aman" , '12345'
Types of Strings:
There are two types of Strings supported in Python:
a) Single-line String- Strings that are terminated within a
single-line are known as Single line Strings.
Example:
text1='hello'
b) Multi-line String - A piece of text that is written in multiple
lines is known as multiple lines string.
There are two ways to create multiline strings:
Adding black slash at the end of each line.
Example:
text1='hello
user'
print(text1)
'hellouser'
2) Using triple quotation marks:-
Example:
str2='''''welcome
to
SSSIT'''
print str2
Output:
welcome to SSSIT
II. Numeric literals:
Numeric Literals are immutable. Numeric literals
can belong to following four different numerical
types.
Example - Numeric Literals
x = 0b10100 #Binary Literals
y = 100 #Decimal Literal
z = 0o215 #Octal Literal
u = 0x12d #Hexadecimal Literal
#Float Literal
float_1 = 100.5
float_2 = 1.5e2
#Complex Literal
a = 5+3.14j
print(x, y, z, u)
print(float_1, float_2)
print(a, a.imag, a.real)
Output:
20 100 141 301
100.5 150.0
(5+3.14j) 3.14 5.0
III. Boolean literals:
• A Boolean literal can have any of the two values: True or False.
Example - Boolean Literals
x = (1 == True)
y = (2 == False)
z = (3 == True)
a = True + 10
b = False + 10
print("x is", x)
print("y is", y)
print("z is", z)
print("a:", a)
print("b:", b)
Output:
x is True
y is False
z is False
a: 11
b: 10
IV. Special literals:
• Python contains one special literal i.e., None.
• None is used to specify to that field that is not created. It is also used for
the end of lists in Python.
Example - Special Literals
val1=10
val2=None
print(val1)
print(val2)
Output:
10
None
V. Literal Collections.
• Python provides the four types of literal
collection such as List literals, Tuple literals, Dict
literals, and Set literals.
List:
• List contains items of different data types. Lists
are mutable i.e., modifiable.
• The values stored in List are separated by
comma(,) and enclosed within square
brackets([]). We can store different types of data
in a List.
Example - List literals
list=['John',678,20.4,'Peter']
list1=[456,'Andrew']
print(list)
print(list + list1)
Output:
['John', 678, 20.4, 'Peter']
['John', 678, 20.4, 'Peter', 456, 'Andrew']
• Dictionary:
• Python dictionary stores the data in the key-value
pair.
• It is enclosed by curly-braces {} and each pair is
separated by the commas(,).
Example
dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}
print(dict)
Output:
{'name': 'Pater', 'Age': 18, 'Roll_nu': 101}
Tuple:
Python tuple is a collection of different data-type. It is
immutable which means it cannot be modified after
creation.
It is enclosed by the parentheses () and each element is
separated by the comma(,).
Example
tup = (10,20,"Dev",[2,3,4])
print(tup)
Output:
(10, 20, 'Dev', [2, 3, 4])
Set:
Python set is the collection of the unordered
dataset.
It is enclosed by the {} and each element is
separated by the comma(,).
Example: - Set Literals
set = {'apple','grapes','guava','papaya'}
print(set)
Output:
{'guava', 'apple', 'papaya', 'grapes'}
Python Operators
Introduction:
• 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
• Arithmetic Operators
Arithmetic Operators:
• Arithmetic operators used between two
operands for a particular operation. There are
many arithmetic operators. It includes the
exponent (**) operator as well as the +
(addition), - (subtraction), * (multiplication), /
(divide), % (reminder), and // (floor division)
operators.
• Consider the following table for a detailed
explanation of arithmetic operators.
Program Code:
• Now we give code examples of arithmetic operators
in Python. The code is given below -
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)
• Output:
• Now we compile the above code in Python, and
after successful compilation, we run it. Then the
output is given below -
Addition of two numbers: 38
Subtraction of two numbers: 26
Multiplication of two numbers: 192
Division of two numbers: 5.333333333333333
Reminder of two numbers: 2
Exponent of two numbers: 1073741824
Floor division of two numbers: 5
• 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. The
example of comparison operators are ==, !=, <=, >=, >, <. In the
below table, we explain the works of the operators.
• Program Code:
• Now we give code examples of Comparison
operators in Python. The code is given below -
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)
• Output:
• Now we compile the above code in Python, and
after successful compilation, we run it. Then the
output is given below -
Two numbers are equal or not: False
Two numbers are not equal or not: True
a is less than or equal to b: False
a is greater than or equal to b: True
a is greater b: True
a is less than b: False
• Assignment Operators:
• Using the assignment operators, the right
expression's value is assigned to the left
operand. There are some examples of
assignment operators like =, +=, -=, *=, %=, **=,
//=. In the below table, we explain the works of
the operators.
Program Code:
Now we give code examples of Assignment operators
in Python. The code is given below -
a = 32 # 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*=b:', a*b)
print('a%=b:', a%b)
print('a**=b:', a**b)
print('a//=b:', a//b)
Output:
• Now we compile the above code in Python, and
after successful compilation, we run it. Then the
output is given below –
a=b: False
a+=b: 38
a-=b: 26
a*=b: 192
a%=b: 2
a**=b: 1073741824
a//=b: 5
Bitwise Operators:
• The two operands' values are processed bit by bit by the bitwise operators. The examples of Bitwise
operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left shift (<<), and Right shift
(>>). Consider the case below.
• 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
Let, Binary of x = 0101
Binary of y = 1000
Bitwise OR = 1101
8 4 2 1
1 1 0 1 = 8 + 4 + 1 = 13
Bitwise AND = 0000
0000 = 0
Bitwise XOR = 1101
8 4 2 1
1 1 0 1 = 8 + 4 + 1 = 13
Negation of x = ~x = (-x) - 1 = (-5) - 1 = -6
~x = -6
• In the below table, we are explaining the works of
the bitwise operators.
Program Code:
Now we give code examples of Bitwise operators in
Python. The code is given below -
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)
Output:
Now we compile the above code in Python, and
after successful compilation, we run it. Then the
output is given below -
a&b: 4
a|b: 7
a^b: 3
~a: -6
a<>b: 0
Logical Operators
• The assessment of expressions to make decisions
typically uses logical operators. The examples of
logical operators are and, or, and not. In the case
of logical AND, if the first one is 0, it does not
depend upon the second one. In the case of
logical OR, if the first one is 1, it does not depend
on the second one. Python supports the
following logical operators. In the below table,
we explain the works of the logical operators.
Program Code:
Now we give code examples of arithmetic operators in
Python. The code is given below -
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)))
Output:
Now we give code examples of Bitwise operators in
Python. The code is given below -
Is this statement true?: False
Any one statement is true?: True
Each statement is true then return False and vice-versa:
True
Membership Operators:
• The membership of a value inside a Python data
structure can be verified using Python
membership operators. The result is true if the
value is in the data structure; otherwise, it
returns false.
Program Code:
Now we give code examples of Membership
operators in Python. The code is given below -
x = ["Rose", "Lotus"]
print(' Is value Present?', "Rose" in x)
print(' Is value not Present?', "Riya" not in x)
Output:
Now we compile the above code in Python, and
after successful compilation, we run it. Then the
output is given below -
Is value Present? True
Is value not Present? True
Identity Operators
Program Code:
Now we give code examples of Identity operators
in Python. The code is given below -
a = ["Rose", "Lotus"]
b = ["Rose", "Lotus"]
c = a
print(a is c)
print(a is not c)
print(a is b)
print(a is not b)
print(a == b)
print(a != b)
Output:
Now we compile the above code in python, and
after successful compilation, we run it. Then the
output is given below -
True
False
False
True
True
False
Operator Precedence:
• The order in which the operators are examined is
crucial to understand since it tells us which
operator needs to be considered first. Below is a
list of the Python operators' precedence tables.
Python Comments
• Introduction to Python Comments
• We may wish to describe the code we develop. We might wish
to take notes of why a section of script functions, for instance.
We leverage the remarks to accomplish this. Formulas,
procedures, and sophisticated business logic are typically
explained with comments. The Python interpreter overlooks the
remarks and solely interprets the script when running a
program. Single-line comments, multi-line comments, and
documentation strings are the 3 types of comments in Python.
• Advantages of Using Comments
• Our code is more comprehensible when we use comments in it.
It assists us in recalling why specific sections of code were
created by making the program more understandable.
• Aside from that, we can leverage comments to overlook specific
code while evaluating other code sections. This simple
technique stops some lines from running or creates a fast
pseudo-code for the program.
• Below are some of the most common uses for comments:
• Readability of the Code
• Restrict code execution
• Provide an overview of the program or project metadata
• To add resources to the code
• Types of Comments in Python
• In Python, there are 3 types of comments. They are described
below:
• 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. If the comment continues
to the next line, add a hashtag to the subsequent line and
resume the conversation. Consider the accompanying code
snippet, which shows how to use a single line comment:
Code
# This code is to show an example of a single-line comment
print( 'This statement does not have a hashtag before it' )
Output:
This statement does not have a hashtag before it
The following is the comment:
• # This code is to show an example of a single-line comment
The Python compiler ignores this line.
• Everything following the # is omitted. As a result, we may put
the program mentioned above in one line as follows:
Code
print( 'This is not a comment' ) # this code is to show an example o
f a single-line comment
Output:
This is not a comment
• This program's output will be identical to the example above.
The computer overlooks all content following #.
• 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.
Code:
# it is a
# comment
# extending to multiple lines
• In this case, each line is considered a comment, and
they are all omitted.
• Using String Literals:
• Because Python overlooks string expressions that aren't
allocated to a variable, we can utilize them as comments.
Code:
'it is a comment extending to multiple lines'
• We can observe that on running this code, there will be no
output; thus, we utilize the strings inside triple quotes(""")
as multi-line comments.
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.
Code:
# Code to show how we use docstrings in Python
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__ )
Output:
This function adds the values of x and y
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.
• In python, decision making is performed by the
following statements.
Indentation in Python
• For the ease of programming and to achieve
simplicity, python doesn't allow the use of
parentheses for the block level code. In Python,
indentation is used to declare a block. If two
statements are at the same indentation level, then
they are the part of the same block.
• Generally, four spaces are given to indent the
statements which are a typical amount of
indentation in python.
• Indentation is the most used part of the python
language since it declares the block of code. All the
statements of one block are intended at the same
level indentation. We will see how the actual
indentation takes place in decision making and other
stuff in python.
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 dyna
mically
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")
Output:
enter the number: 10 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");
Output:
Enter a: 100
Enter b: 120
Enter c: 130
From the above three numbers given c is largest
The if-else statement
• 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 is given below.
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 t
o vote or not.
age = int (input("Enter your age: "))
# Here, we are taking an integer num and taking input dynamica
lly
if age>=18:
# Here, we are checking the condition. If the condition is true, w
e will enter the block
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");
Output:
Enter your age: 90
You are eligible to vote !!
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 dynamica
lly
if num%2 == 0:
# Here, we are checking the condition. If the condition is true, w
e will enter the block
print("The Given number is an even number")
else:
print("The Given Number is an odd number")
Output:
enter the number: 10
The Given number is even number
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 th
e 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 th
e block
print("The given number is equal to 50");
elif number==100:
# Here, we are checking the condition. If the condition is true, we will enter th
e block
print("The given number is equal to 100");
else:
print("The given number is not equal to 10, 50 or 100");
Output:
Enter the number?15
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 bloc
k
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 bloc
k
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 bloc
k
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 bloc
k
print("You scored grade C ...")
else:
print("Sorry you are fail ?")
Output:
Enter the marks? 89
Congrats ! you scored grade A ...
Python Loops
• The following loops are available in Python to
fulfil the looping needs. Python offers 3 choices
for running the loops. The basic functionality of all
the techniques is the same, although the syntax
and the amount of time required for checking the
condition differ.
• We can run a single statement or set of
statements repeatedly using a loop command.
• The following sorts of loops are available in the
Python programming language.
• 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. We will discuss them later in
detail.
• Let us quickly go over the definitions of these
loop control statements.
The for Loop
• Python's 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 }
• In this case, the variable value is used to hold the
value of every item present in the sequence before
the iteration begins until this particular iteration is
completed.
• Loop iterates until the final item of the sequence are
reached.
Code:
# 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)
Output:
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
Using else Statement with for Loop:
As already said, a 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.
Here is a code to better understand if-else
statements.
Code:
# 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 e
xecuted
else:
print(s)
Output:
P
y
t
h
If block
n
L
If block
If block p
Now similarly, using else with for loop.
Syntax:
for value in sequence:
# executes the statements until sequences ar
e exhausted
else:
# executes these statements when for loop is
completed
Code:
# Python program to show how to use else statement with fo
r 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")
Output:
3
9
3
9
7 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.
The example that follows will make this clear.
Code:
# Python program to show the working of range() functio
n
print(range(15))
print(list(range(15)))
print(list(range(4, 9)))
print(list(range(5, 25, 4)))
Output:
range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]
• 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.
Code:
# Python program to iterate over a sequence with the hel
p of indexing
tuple_ = ("Python", "Loops", "Sequence", "Condition", "R
ange")
# iterating over tuple_ using range() function
for iterator in range(len(tuple_)):
print(tuple_[iterator].upper())
Output:
PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE
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.
Code
# 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")
Output:
Python Loops
Python Loops
Python Loops
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.
Code
#Python program to show how to use else statement with th
e 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")
Output:
Python Loops
Python Loops
Python Loops
Python Loops
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.
Code:
# Python program to show how to write a single statem
ent while loop
counter = 0
while (count < 3): print("Python Loops")
Loop Control Statements
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.
Code:
# Python program to show how the continue statement work
s
# Initiating the loop
for string in "Python Loops":
if string == "o" or string == "p" or string == "t":
continue
print('Current Letter:', string)
Output:
Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s
Break Statement:
It stops the execution of the loop when the break
statement is reached.
Code:
# 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)
Output:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:
Pass Statement:
Pass statements are used to create empty loops.
Pass statement is also employed for classes,
functions, and empty control statements.
Code:
# Python program to show how the pass statement
works
for a string in "Python Loops":
pass
print( 'Last Letter:', string)
Output:
Last Letter: s
Python Functions
• A collection of related assertions that carry out a
mathematical, analytical, or evaluative operation is
known as a function. An assortment of
proclamations called Python Capabilities returns the
specific errand. Python functions are necessary for
intermediate-level programming and are easy to
define. Function names meet the same standards as
variable names do. The objective is to define a
function and group-specific frequently performed
actions. Instead of repeatedly creating the same
code block for various input variables, we can call
the function and reuse the code it contains with
different variables.
• Client-characterized and worked-in capabilities are
the two primary classes of capabilities in Python. It
aids in maintaining the program's uniqueness,
conciseness, and structure.
• Advantages of Python Functions
• Pause We can stop a program from repeatedly using
the same code block by including functions.
• Once defined, Python functions can be called
multiple times and from any location in a program.
• Our Python program can be broken up into
numerous, easy-to-follow functions if it is significant.
• The ability to return as many outputs as we want
using a variety of arguments is one of Python's most
significant achievements.
• However, Python programs have always incurred
overhead when calling functions.
• However, calling functions has always been overhead
in a Python program.
Syntax:
# An example Python Function
def function_name( parameters ):
# code block
The accompanying components make up to characterize a capability, as seen
previously.
• The start of a capability header is shown by a catchphrase called def.
• function_name is the function's name, which we can use to distinguish it
from other functions. We will utilize this name to call the capability later in
the program. Name functions in Python must adhere to the same guidelines
as naming variables.
• Using parameters, we provide the defined function with arguments.
Notwithstanding, they are discretionary.
• A colon (:) marks the function header's end.
• We can utilize a documentation string called docstring in the short structure
to make sense of the reason for the capability.
• Several valid Python statements make up the function's body. The entire
code block's indentation depth-typically four spaces-must be the same.
• A return expression can get a value from a defined function.
• Illustration of a User-Defined Function
• We will define a function that returns the argument
number's square when called.
# Example Python Code for User-Defined function
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_ )
Output:
The square of the given number is: 36
• 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 Python Code for calling a function
# Defining a function
def a_function( string ):
"This prints the value of length of string"
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" ) )
Output:
Length of the string Functions is: 9
Length of the string Python is: 6
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,
Code
# 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 )
Output:
Squares of the list are: [289, 2704, 64]
Function Arguments
The following are the types of arguments that we can
use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments
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.
Code:
# Python code to demonstrate the use of default argum
ents
# 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)
Output:
Passing only one argument
number 1 is: 30
number 2 is: 20
Passing two arguments
number 1 is: 50
number 2 is: 30
• Keyword Arguments
• Keyword arguments are linked to the arguments
of a called function. While summoning a
capability with watchword contentions, the client
might tell whose boundary esteem it is by looking
at the boundary name.
• We can eliminate or orchestrate specific
contentions in an alternate request since the
Python translator will interface the furnished
watchwords to connect the qualities with its
boundaries. One more method for utilizing
watchwords to summon the capability() strategy
is as per the following:
Code:
# 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" )
function( 50, 30)
# Calling function and passing arguments using keyword
print( "With using keyword" )
function( n2 = 50, n1 = 30)
Output:
Without using keyword
number 1 is: 50
number 2 is: 30
With using keyword
number 1 is: 30
number 2 is: 50
• 3) Required Arguments
• Required arguments are those supplied to a
function during its call in a predetermined
positional sequence. The number of arguments
required in the method call must be the same as
those provided in the function's definition.
• We should send two contentions to the
capability() all put together; it will return a
language structure blunder, as seen beneath.
Code:
# 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" )
Output:
Passing out of order arguments
number 1 is: 30
number 2 is: 20
Passing only one argument
Function needs two positional arguments
4) Variable-Length Arguments:
• We can involve unique characters in Python
capabilities to pass many contentions. However,
we need a capability. This can be accomplished
with one of two types of characters:
• "args" and "kwargs" refer to arguments not based
on keywords.
• To help you understand arguments of variable
length, here's an example.
Code:
# 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)
Output:
['PYTHON', 'FUNCTIONS', 'TUTORIAL']
[['First', 'Python'], ['Second', 'Functions'], ['Third',
'Tutorial']]
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 >
• 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.
• A return statement in Python functions is
depicted in the following example.
Code:
# 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 ) )
• Output:
With return statement
2704
Without return statement None
Standard Type built in functions
• Python provides a wide range of built-in functions
to work with standard data types. Here are some
of the commonly used built-in functions for
various standard data types:
1. Numeric Types:
• int(): Converts a value to an integer.
• float(): Converts a value to a floating-point
number.
• abs(): Returns the absolute value of a number.
• round(): Rounds a floating-point number to the
nearest integer.
• 2. Strings:
• str(): Converts a value to a string.
• len(): Returns the length of a string.
• upper(): Converts a string to uppercase.
• lower(): Converts a string to lowercase.
• strip(): Removes leading and trailing whitespace from
a string.
• split(): Splits a string into a list of substrings based on
a delimiter.
• join(): Joins a list of strings into a single string using a
delimiter.
• find(): Searches for a substring within a string and
returns its index.
• replace(): Replaces occurrences of a substring in a
string with another substring.
• 3. Lists:
• list(): Converts an iterable (e.g., tuple, string) to a list.
• len(): Returns the number of elements in a list.
• append(): Adds an element to the end of a list.
• extend(): Appends the elements of an iterable to a list.
• insert(): Inserts an element at a specific index in a list.
• remove(): Removes the first occurrence of a specified
value from a list.
• pop(): Removes and returns an element at a specified
index.
• index(): Returns the index of the first occurrence of a
specified value.
• count(): Returns the number of occurrences of a specified
value in a list.
• sort(): Sorts the elements of a list in ascending order.
• reverse(): Reverses the order of elements in a list.
• 4. Tuples:
• tuple(): Converts an iterable (e.g., list, string) to a tuple.
• len(): Returns the number of elements in a tuple.
• index(): Returns the index of the first occurrence of a specified value.
• count(): Returns the number of occurrences of a specified value in a
tuple.
• 5. Dictionaries:
• dict(): Creates a new dictionary or converts an iterable of key-value
pairs to a dictionary.
• len(): Returns the number of key-value pairs in a dictionary.
• keys(): Returns a list of keys in the dictionary.
• values(): Returns a list of values in the dictionary.
• items(): Returns a list of key-value pairs as tuples.
• get(): Returns the value associated with a key, or a default value if the
key is not found.
• pop(): Removes and returns the value associated with a key.
• update(): Updates a dictionary with key-value pairs from another
dictionary.
Unsupported types in python
Following are some of the types that are not supported by python
Charcter type (char):
In python there is no character data type, in python character is a string of length
one, it is represented by class str.
Pointers:
No, we don't have any kind of Pointer in Python language. In C and C++, a pointer
is a variable that holds a memory address, but we don't have any kind of
Pointer in Python , if you want to find address of any object then you need to
use id() function.
Program:
a=10
print(id(a)) #id() function is used to find address output:
9789280
long int and short int:
In c programming for long size integer values and short size integer values we use
long int data type and short int data type but python do not support long int
and short int , in python for both long and short size integers we use type int.
double data type:
We use double data type for long size float values ,but python do not support
double type. In python even for long size float values you can use float data
type.python float is actually C’s double data type
lambda function
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but
can only have one expression.
Syntax
lambda arguments : expression
The expression is executed and the result is returned:
Example
Add 10 to argument a, and return the result:
x = lambda a: a + 10
print(x(5))
output:
15
•
Python Function Recursion:
Python also accepts function recursion, which means a
defined function can call itself.
Function which calls itself is know as recursion. This has
the benefit of meaning that you can loop through data
to reach a result.
Example:
def name():
print(“my name is nagendra”) name()
name()
name()
output:
my name is nagendra
my name is nagendra
my name is nagendra
my name is nagendra
:
:
:
• in above example I written name() function inside name()
function, which means function name() calls itself , so it
keep on repeating same code again and again, so we can
loop statements by using recursion
Following is an example of a recursive function to find the
factorial of an integer.
• Factorial of a number is the product of all the integers from
1 to that number. For example, the factorial of 6 (denoted
as 6!) is 1*2*3*4*5*6= 720
Example of a recursive function
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
n = 5
print("The factorial of", n, "is", factorial(n))
output:
The factorial of 5 is 120
Built-In Functions
Python has a set of built-in functions.
input()
Input() Python built-in functions, reads an input.
Example:
a=int(input(“enter no:”)) print(a)
output:
enter no: 10
10
eval()
Eval( ) function will accept any data type values that you enter.
Example:
a=eval(input(“enter no:”)) print(a)
output:
enter no: 10
10
exec()
exec() runs Python code dynamically.
>>> exec('a=2;b=3;print(a+b)')
Output
5
hex()
Hex() Python built-in functions, converts an
integer to hexadecimal.
>>> hex(16) Output ‘0x10’
id()
id() returns an object’s identity(address).
>>> id(orange) Output 100218832
len()
We’ve seen len() so many times by now. It returns the length of an
object.
Example:
a=(1,2,3,4,5,6,7)
print(len(a)) output:
7
max()
max() returns the item, in a sequence, with the highest value of all.
Example:
a=(1,2,3,4,5,6,7)
print(max(a)) output:
7
min()
min() returns the item, in a sequence, with the smallest value of all.
Example: a=(1,2,3,4,5,6,7)
print(min(a)) output:
1
pow()
pow() takes two arguments- say, x and y. It then returns the
value of x to the power of y.
>>> pow(3,4)
Output
81
print()
We don’t think we need to explain this anymore. We’ve been
seeing this function since the beginning.
>>> print("hi”)
output:
hi
repr()
repr() returns a representable string of an object.
>>> repr("Hello")
Output
“‘Hello'”
range()
we use range ( ) function in order to print values in sequence
example:
>>> for i in range(1,6):
print(i)
Output
1
2
3
4
5
sorted()
Like we’ve seen before, sorted() prints out a sorted version of an iterable. It does not,
however, alter the iterable.
>>> sorted('Python')
Output
[‘P’, ‘h’, ‘n’, ‘o’, ‘t’, ‘y’]
sum()
The function sum() takes an iterable as an argument, and returns the sum of all values.
>>> sum([3,4,5],3)
Output
15
type()
We have been seeing the type() function to
check the type of object we’re dealing with.
>>> type(10)
Output
<class ‘int’>
other built in functions :
int(), float(), str(), complex( ), list ( ) , tuple ( ) , set ( ) .
• print(int(10.5)) #converting float value to int
print(int("10")) #converting string to int
• print(float(10)) #converting int to float
print(float("10.5")) #converting string to float
print(str(10)) #converting int to str
• print(str(10.5)) #converting float to str
• print(complex(1,2.3))#converting int and float numbers
to complex print(list((1,2.4,"btech")))
#converting tuple to list print(tuple([1,2.4,"btech"]))
#converting list to tuple print(set([1,2.4,"btech"]))
#converting list to set
output:
10
10
10.0
10.5
10
10.5 (1+2.3j)
[1, 2.4, 'btech']
(1, 2.4, 'btech')
{'btech', 1, 2.4}
Python object
• Python is an object-oriented programming
language. Everything is in Python treated as an
object, including variable, function, list, tuple,
dictionary, set, etc. Every object belongs to its
class. For example - An integer variable belongs to
integer class. An object is a real-life entity. An
object is the collection of various data and
functions that operate on those data. An object
contains the following properties.
Value:
data item that is represented by an object
Example:
a=10 #here 10 is value print(a)
output:
10
Type:
an object’s type indicates what kind of values an object can
hold. what operations can be applied to such objects.
type ( ) function is used to find type of object
Example:
a=10
print(type(a)) output:
<class ‘int’>
Identity :
Each object contains unique identity that
differentiates from all other objects. And you can
check id of an object by using id ( ) function.
Example:
a=10
print(id(a)) output:
9789280
literals and types of literal constants
literal is a raw data given to variable or constant
in python there are various types of literals they are
numberic literals :
3 types – integer, float, complex
Example:
a=10
b=10.5
c=1+2j
print(a)
print(b)
print(c)
output:
10
10.5
1+2j
string literals :
Example:
a=”hello”
print(a)
output:
Hello
special literals :
None
if you dont want to give any value to the variable then you can use
None
Example:
a=None
print(a)
output:
here you will not get any output because None means nothing
python - Type conversion
• type conversion is the process of converting data
of one type to another. For example: converting
integer data to string.
There are two types of type conversion in Python.
Implicit Conversion - automatic type conversion
Explicit Conversion - manual type conversion
Implicit Type Conversion:
• In certain situations, Python automatically converts
one data type to another. This is known as implicit type
conversion.
• Python always converts smaller data types to larger
data types to avoid the loss of data.
• Integer is smaller than float and float is smaller than
string
Example:
a=10
b=10.5
c=a+b
print(c)
output:
20.5
• In the above example, I took a value as 10 which
is integer and b value as 10.5 which is float
.though i given one value as integer and other
value as float , i got output as float value because
Python always converts smaller data types to
larger data types to avoid the loss of data. In this
example integer value is smaller than float value,
so integer value 10 is automatically converted
into float value,so i got output 20.5 which is float
value.
Explicit Type Conversion:
• In Explicit Type Conversion, Python cannot
automatically converts one data type to another
so, users converts one data type to another
manually .
• We use the built-in functions like int(),
float(), str(), complex( ), list ( ) , tuple ( ) , set ( )
to perform explicit type conversion.
• This type of conversion is also called typecasting
because the user casts (changes) the data type
of the objects.
Example:
• print(int(10.5)) #converting float value to int
print(int("10")) #converting string to int
• print(float(10)) #converting int to float
print(float("10.5")) #converting string to float
print(str(10)) #converting int to str
• print(str(10.5)) #converting float to str
• print(complex(1,2.3))#converting int and float
numbers to complex print(list((1,2.4,"btech")))
#converting tuple to list
print(tuple([1,2.4,"btech"])) #converting list to
tuple print(set([1,2.4,"btech"]))
#converting list to set
output:
10
10
10.0
10.5
10
10.5 (1+2.3j)
[1, 2.4, 'btech']
(1, 2.4, 'btech')
{'btech', 1, 2.4}
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1
PYTHON UNIT 1

More Related Content

Similar to PYTHON UNIT 1

Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonSoba Arjun
 
Machine learning session 1
Machine learning session 1Machine learning session 1
Machine learning session 1NirsandhG
 
How to start Python? - lesson 1
How to start Python? - lesson 1How to start Python? - lesson 1
How to start Python? - lesson 1Shohel Rana
 
Migration of Applications to Python is the most prudent Decision
Migration of Applications to Python is the most prudent DecisionMigration of Applications to Python is the most prudent Decision
Migration of Applications to Python is the most prudent DecisionMindfire LLC
 
PHP vs Python Which is Best for Web Development.pdf
PHP vs Python Which is Best for Web Development.pdfPHP vs Python Which is Best for Web Development.pdf
PHP vs Python Which is Best for Web Development.pdfchristiemarie4
 
Python programming
Python programmingPython programming
Python programmingMegha V
 
Top Five Reasons for Choosing Python Programming
Top Five Reasons for Choosing Python Programming  Top Five Reasons for Choosing Python Programming
Top Five Reasons for Choosing Python Programming Lesa Cote
 
Presentation (1).pdf
Presentation (1).pdfPresentation (1).pdf
Presentation (1).pdfnaganeparth06
 
IRJET- Python: Simple though an Important Programming Language
IRJET- Python: Simple though an Important Programming LanguageIRJET- Python: Simple though an Important Programming Language
IRJET- Python: Simple though an Important Programming LanguageIRJET Journal
 
Python Programming Unit1_Aditya College of Engg & Tech
Python Programming Unit1_Aditya College of Engg & TechPython Programming Unit1_Aditya College of Engg & Tech
Python Programming Unit1_Aditya College of Engg & TechRamanamurthy Banda
 
Know This Before You Get Python Assignment Help.pptx
Know This Before You Get Python Assignment Help.pptxKnow This Before You Get Python Assignment Help.pptx
Know This Before You Get Python Assignment Help.pptxLeena Rose
 
Python presentation by Monu Sharma
Python presentation by Monu SharmaPython presentation by Monu Sharma
Python presentation by Monu SharmaMayank Sharma
 
PYTHON COURSE IN KHANNA
PYTHON COURSE IN KHANNAPYTHON COURSE IN KHANNA
PYTHON COURSE IN KHANNAtanukashyap18
 
Machine learning libraries with python
Machine learning libraries with pythonMachine learning libraries with python
Machine learning libraries with pythonVishalBisht9217
 
Advantage of Phyton Language for Development.pdf
Advantage of Phyton Language for Development.pdfAdvantage of Phyton Language for Development.pdf
Advantage of Phyton Language for Development.pdfvegasystemsusa
 
introduction to Python (for beginners)
introduction to Python (for beginners)introduction to Python (for beginners)
introduction to Python (for beginners)guobichrng
 
Why Python in required in Civil Engineering
Why Python in required in Civil EngineeringWhy Python in required in Civil Engineering
Why Python in required in Civil EngineeringRushikesh Kolhe
 
Python Course in Delhi.pdf
Python Course in Delhi.pdfPython Course in Delhi.pdf
Python Course in Delhi.pdftarun
 

Similar to PYTHON UNIT 1 (20)

Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Machine learning session 1
Machine learning session 1Machine learning session 1
Machine learning session 1
 
How to start Python? - lesson 1
How to start Python? - lesson 1How to start Python? - lesson 1
How to start Python? - lesson 1
 
Migration of Applications to Python is the most prudent Decision
Migration of Applications to Python is the most prudent DecisionMigration of Applications to Python is the most prudent Decision
Migration of Applications to Python is the most prudent Decision
 
PHP vs Python Which is Best for Web Development.pdf
PHP vs Python Which is Best for Web Development.pdfPHP vs Python Which is Best for Web Development.pdf
PHP vs Python Which is Best for Web Development.pdf
 
Python programming
Python programmingPython programming
Python programming
 
Top Five Reasons for Choosing Python Programming
Top Five Reasons for Choosing Python Programming  Top Five Reasons for Choosing Python Programming
Top Five Reasons for Choosing Python Programming
 
Python
PythonPython
Python
 
Presentation (1).pdf
Presentation (1).pdfPresentation (1).pdf
Presentation (1).pdf
 
IRJET- Python: Simple though an Important Programming Language
IRJET- Python: Simple though an Important Programming LanguageIRJET- Python: Simple though an Important Programming Language
IRJET- Python: Simple though an Important Programming Language
 
Python Programming Unit1_Aditya College of Engg & Tech
Python Programming Unit1_Aditya College of Engg & TechPython Programming Unit1_Aditya College of Engg & Tech
Python Programming Unit1_Aditya College of Engg & Tech
 
Know This Before You Get Python Assignment Help.pptx
Know This Before You Get Python Assignment Help.pptxKnow This Before You Get Python Assignment Help.pptx
Know This Before You Get Python Assignment Help.pptx
 
Python presentation by Monu Sharma
Python presentation by Monu SharmaPython presentation by Monu Sharma
Python presentation by Monu Sharma
 
Python training Course in Mohali
Python training Course in MohaliPython training Course in Mohali
Python training Course in Mohali
 
PYTHON COURSE IN KHANNA
PYTHON COURSE IN KHANNAPYTHON COURSE IN KHANNA
PYTHON COURSE IN KHANNA
 
Machine learning libraries with python
Machine learning libraries with pythonMachine learning libraries with python
Machine learning libraries with python
 
Advantage of Phyton Language for Development.pdf
Advantage of Phyton Language for Development.pdfAdvantage of Phyton Language for Development.pdf
Advantage of Phyton Language for Development.pdf
 
introduction to Python (for beginners)
introduction to Python (for beginners)introduction to Python (for beginners)
introduction to Python (for beginners)
 
Why Python in required in Civil Engineering
Why Python in required in Civil EngineeringWhy Python in required in Civil Engineering
Why Python in required in Civil Engineering
 
Python Course in Delhi.pdf
Python Course in Delhi.pdfPython Course in Delhi.pdf
Python Course in Delhi.pdf
 

Recently uploaded

IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 

PYTHON UNIT 1

  • 2. What is Python • Python is a general-purpose, dynamic, high-level, and interpreted programming language. It supports Object Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of high-level data structures. • Python is an easy-to-learn yet powerful and versatile scripting language, which makes it attractive for Application Development. • With its interpreted nature, Python's syntax and dynamic typing make it an ideal language for scripting and rapid application development. • Python supports multiple programming patterns, including object-oriented, imperative, and functional or procedural programming styles.
  • 3. • Python is not intended to work in a particular area, such as web programming. It is a multipurpose programming language because it can be used with web, enterprise, 3D CAD, etc. • We don't need to use data types to declare variable because it is dynamically typed, so we can write a=10 to assign an integer value in an integer variable. • Python makes development and debugging fast because no compilation step is included in Python development, and the edit-test-debug cycle is very fast. • Python has many web-based assets, open-source projects, and a vibrant community. Learning the language, working together on projects, and contributing to the Python ecosystem are all made very easy for developers.
  • 4. • Because of its straightforward language framework, Python is easier to understand and write code in. This makes it a fantastic programming language for novices. Additionally, it assists seasoned programmers in writing clearer, error-free code. • Python is an open-source, cost-free programming language. It is utilized in several sectors and disciplines as a result. • In Python, code readability and maintainability are important. As a result, even if the code was developed by someone else, it is easy to understand and adapt by some other developer. • Python has many third-party libraries that can be used to make its functionality easier. These libraries cover many domains, for example, web development, scientific computing, data analysis, and more.
  • 5. Python Basic Syntax • There is no use of curly braces or semicolon in Python programming language. It is English-like language. But Python uses the indentation to define a block of code. Indentation is nothing but adding whitespace before the statement when it is needed. For example - def func(): statement 1 statement 2 ………………… ………………… statement N • In the above example, the statements that are the same level to the right belong to the function. Generally, we can use four whitespaces to define indentation. • Instead of Semicolon as used in other languages, Python ends its statements with a NewLine character. • Python is a case-sensitive language, which means that uppercase and lowercase letters are treated differently. For example, 'name' and 'Name' are two different variables in Python.
  • 6. • In Python, comments can be added using the '#' symbol. Any text written after the '#' symbol is considered a comment and is ignored by the interpreter. This trick is useful for adding notes to the code or temporarily disabling a code block. It also helps in understanding the code better by some other developers. • 'If', 'otherwise', 'for', 'while', 'try', 'except', and 'finally' are a few reserved keywords in Python that cannot be used as variable names. These terms are used in the language for particular reasons and have fixed meanings. If you use these keywords, your code may include errors, or the interpreter may reject them as potential new Variables.
  • 7. Why learn Python? • Python provides many useful features to the programmer. These features make it the most popular and widely used language. We have listed belo • Easy to use and Learn: Python has a simple and easy-to- understand syntax, unlike traditional languages like C, C++, Java, etc., making it easy for beginners to learn. • Expressive Language: It allows programmers to express complex concepts in just a few lines of code or reduces Developer's Time. • Interpreted Language: Python does not require compilation, allowing rapid development and testing. It uses Interpreter instead of Compiler. • Object-Oriented Language: It supports object-oriented programming, making writing reusable and modular code easy. • Open Source Language: Python is open source and free to use, distribute and modify. • Extensible: Python can be extended with modules written in C, C++, or other languages.
  • 8. • Learn Standard Library: Python's standard library contains many modules and functions that can be used for various tasks, such as string manipulation, web programming, and more. • GUI Programming Support: Python provides several GUI frameworks, such as Tkinter and PyQt, allowing developers to create desktop applications easily. • Integrated: Python can easily integrate with other languages and technologies, such as C/C++, Java, and . NET. • Embeddable: Python code can be embedded into other applications as a scripting language. • Dynamic Memory Allocation: Python automatically manages memory allocation, making it easier for developers to write complex programs without worrying about memory management. • Wide Range of Libraries and Frameworks: Python has a vast collection of libraries and frameworks, such as NumPy, Pandas, Django, and Flask, that can be used to solve a wide range of problems. • Versatility: Python is a universal language in various domains such as web development, machine learning, data analysis, scientific computing, and more.
  • 9. • Large Community: Python has a vast and active community of developers contributing to its development and offering support. This makes it easy for beginners to get help and learn from experienced developers. • Career Opportunities: Python is a highly popular language in the job market. Learning Python can open up several career opportunities in data science, artificial intelligence, web development, and more. • High Demand: With the growing demand for automation and digital transformation, the need for Python developers is rising. Many industries seek skilled Python developers to help build their digital infrastructure. • Increased Productivity: Python has a simple syntax and powerful libraries that can help developers write code faster and more efficiently. This can increase productivity and save time for developers and organizations. • Big Data and Machine Learning: Python has become the go-to language for big data and machine learning. Python has become popular among data scientists and machine learning engineers with libraries like NumPy, Pandas, Scikit-learn, TensorFlow, and more.
  • 10. Where is Python used? • Python is a general-purpose, popular programming language, and it is used in almost every technical field. The various areas of Python use are given below. • Data Science: Data Science is a vast field, and Python is an important language for this field because of its simplicity, ease of use, and availability of powerful data analysis and visualization libraries like NumPy, Pandas, and Matplotlib. • Desktop Applications: PyQt and Tkinter are useful libraries that can be used in GUI - Graphical User Interface-based Desktop Applications. There are better languages for this field, but it can be used with other languages for making Applications. • Console-based Applications: Python is also commonly used to create command-line or console-based applications because of its ease of use and support for advanced features such as input/output redirection and piping. • Mobile Applications: While Python is not commonly used for creating mobile applications, it can still be combined with frameworks like Kivy or BeeWare to create cross-platform mobile applications.
  • 11. • Software Development: Python is considered one of the best software-making languages. Python is easily compatible with both from Small Scale to Large Scale software. • Artificial Intelligence: AI is an emerging Technology, and Python is a perfect language for artificial intelligence and machine learning because of the availability of powerful libraries such as TensorFlow, Keras, and PyTorch. • Web Applications: Python is commonly used in web development on the backend with frameworks like Django and Flask and on the front end with tools like JavaScript and HTML. • Enterprise Applications: Python can be used to develop large- scale enterprise applications with features such as distributed computing, networking, and parallel processing. • 3D CAD Applications: Python can be used for 3D computer- aided design (CAD) applications through libraries such as Blender. • Machine Learning: Python is widely used for machine learning due to its simplicity, ease of use, and availability of powerful machine learning libraries.
  • 12. • Computer Vision or Image Processing Applications: Python can be used for computer vision and image processing applications through powerful libraries such as OpenCV and Scikit-image. • Speech Recognition: Python can be used for speech recognition applications through libraries such as SpeechRecognition and PyAudio. • Scientific computing: Libraries like NumPy, SciPy, and Pandas provide advanced numerical computing capabilities for tasks like data analysis, machine learning, and more. • Education: Python's easy-to-learn syntax and availability of many resources make it an ideal language for teaching programming to beginners. • Testing: Python is used for writing automated tests, providing frameworks like unit tests and pytest that help write test cases and generate reports. • Gaming: Python has libraries like Pygame, which provide a platform for developing games using Python. • IoT: Python is used in IoT for developing scripts and applications for devices like Raspberry Pi, Arduino, and others.
  • 13. • Networking: Python is used in networking for developing scripts and applications for network automation, monitoring, and management. • DevOps: Python is widely used in DevOps for automation and scripting of infrastructure management, configuration management, and deployment processes. • Finance: Python has libraries like Pandas, Scikit-learn, and Statsmodels for financial modeling and analysis. • Audio and Music: Python has libraries like Pyaudio, which is used for audio processing, synthesis, and analysis, and Music21, which is used for music analysis and generation. • Writing scripts: Python is used for writing utility scripts to automate tasks like file operations, web scraping, and data processing.
  • 14. Python Popular Frameworks and Libraries • Python has wide range of libraries and frameworks widely used in various fields such as machine learning, artificial intelligence, web applications, etc. We define some popular frameworks and libraries of Python as follows. • Web development (Server-side) - Django Flask, Pyramid, CherryPy • GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc. • Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc. • Mathematics - Numpy, Pandas, etc. • BeautifulSoup: a library for web scraping and parsing HTML and XML • Requests: a library for making HTTP requests • SQLAlchemy: a library for working with SQL databases
  • 15. • Kivy: a framework for building multi-touch applications • Pygame: a library for game development • Pytest: a testing framework for Python • Django REST framework: a toolkit for building RESTful APIs • FastAPI: a modern, fast web framework for building APIs • Streamlit: a library for building interactive web apps for machine learning and data science • NLTK: a library for natural language processing
  • 16. Python Features • Python provides many useful features which make it popular and valuable from the other programming languages. It supports object- oriented programming, procedural programming approaches and provides dynamic memory allocation. We have listed below a few essential features. 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.
  • 17. 4) Cross-platform Language 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.
  • 18. 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 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.
  • 19. Python History and Versions • Python laid its foundation in the late 1980s. • The implementation of Python was started in December 1989 by Guido Van Rossum at CWI in Netherland. • In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to alt.sources. • In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce. • Python 2.0 added new features such as list comprehensions, garbage collection systems. • On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify the fundamental flaw of the language. • ABC programming language is said to be the predecessor of Python language, which was capable of Exception Handling and interfacing with the Amoeba Operating System. • The following programming languages influence Python: – ABC language. – Modula-3
  • 20. 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.
  • 21. Python Version List • 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.
  • 22.
  • 23.
  • 24. 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. • Here, we are specifying application areas where Python can be applied.
  • 25. 1) Web Applications We can use Python to develop web applications. It provides libraries to handle internet protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser, etc. One of Python web-framework named Django is used on Instagram. Python provides many useful frameworks, and these are given below: • Django and Pyramid framework(Use for heavy applications) • Flask and Bottle (Micro-framework) • 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.
  • 26. • Tkinter or Tk • wxWidgetM • Kivy (used for writing multitouch applications ) • 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. Python can develop this kind of application very effectively. It is famous for having REPL, which means the Read-Eval-Print Loop that makes it the most suitable language for the command-line applications. Python provides many free library or module which helps to build the command-line apps. The necessary IO libraries are used to read and write. It helps to parse argument and create console help text out-of-the-box. There are also advance libraries that can develop independent console apps.
  • 27. 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. SCons is used to build control. Buildbot and Apache Gumps are used for automated continuous compilation and testing. 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. Implementing machine learning algorithms require complex mathematical calculation. Python has many libraries for scientific and numeric such as Numpy, Pandas, Scipy, Scikit-learn, etc. If you have some basic knowledge of Python, you need to import libraries on the top of the code. Few popular frameworks of machine libraries are given below. SciPy Scikit-learn NumPy Pandas Matplotlib
  • 28. 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. 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. Gstreamer Pyglet QT Phonon
  • 29. 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. Fandango (Popular ) CAMVOX HeeksCNC AnyCAD 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 OpenERP, Tryton, Picalo, etc. 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. OpenCV Pillow SimpleITK
  • 30. How to Install Python • Installing Python on Windows: • Download Python: – Visit the official Python website at https://www.python.org/downloads/windows/. – Click on the "Downloads" tab. – Download the latest Python installer for Windows. Choose the installer that corresponds to your system architecture (32-bit or 64-bit). • Run the Installer: – Locate the downloaded installer file (e.g., python-3.x.x.exe) and double-click it to run the installer. • Customize Installation (Optional): – You can customize the installation by clicking the "Customize installation" button. However, the default settings are usually sufficient for most users. • Installation Options: – Make sure to check the box that says "Add Python X.X to PATH." This allows you to use Python from the command line without needing to specify the full path. • Installation: – Click the "Install Now" button to begin the installation process. • Completing the Installation: – Once the installation is complete, you should see a screen that says "Setup was successful." You can now close the installer. • Verify Installation: – Open the Command Prompt by searching for "cmd" in the Windows Start Menu. – Type python and press Enter. You should see the Python version information. This confirms that Python is installed.
  • 31. • Installing Python on Ubuntu: • Open the Terminal: – Press Ctrl+Alt+T to open a terminal window. • Update Package List: – Before installing Python, it's a good practice to update the package list to ensure you're getting the latest version of Python and its dependencies. Run the following command: • sudo apt update • sudo apt install python3 • python3 --version • This should display the Python version installed.
  • 32. First Python Program • In Python, the most basic program is one that prints a message to the screen. Here's a "Hello, World!" program: • print("Hello, World!") • Now, let's break it down: • 1. `print()`: `print` is a Python function used to output text or data to the console (the terminal or command prompt). In this case, it's used to print the message "Hello, World!" to the screen. • 2. `"Hello, World!"`: This is a string. In Python, strings are sequences of characters enclosed in either single (`'`) or double (`"`) quotes. In this case, we're using double quotes.
  • 33. • So, when you run this Python program, it will simply display "Hello, World!" in the console. • Here's how you can run the program: 1. Save the code in a file with a `.py` extension, like `hello.py`. 2. Open a terminal or command prompt. 3. Navigate to the directory where you saved the `hello.py` file. 4. Run the program by typing `python hello.py` and pressing Enter. You should see the output: Hello, World!
  • 34. Python Variables • Variable is a name that is used to refer to memory location. Python variable is also known as an identifier and used to hold value. • In Python, we don't need to specify the type of variable because Python is a infer language and smart enough to get variable type. • Variable names can be a group of both the letters and digits, but they have to begin with a letter or an underscore. • It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two different variables.
  • 35. Python Variables • Variable is a name that is used to refer to memory location. Python variable is also known as an identifier and used to hold value. • In Python, we don't need to specify the type of variable because Python is a infer language and smart enough to get variable type. • Variable names can be a group of both the letters and digits, but they have to begin with a letter or an underscore. • It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two different variables.
  • 36. Identifier Naming: • Variables are the example of identifiers. An Identifier is used to identify the literals used in the program. The rules to name an identifier are given below. • The first character of the variable must be an alphabet or underscore ( _ ). • All the characters except the first character may be an alphabet of lower-case(a-z), upper-case (A-Z), underscore, or digit (0-9). • Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *). • Identifier name must not be similar to any keyword defined in the language. • Identifier names are case sensitive; for example, my name, and MyName is not the same. • Examples of valid identifiers: a123, _n, n_9, etc. • Examples of invalid identifiers: 1a, n%4, n 9, etc.
  • 37. Declaring Variable and Assigning Values • Python does not bind us to declare a variable before using it in the application. It allows us to create a variable at the required time. • We don't need to declare explicitly variable in Python. When we assign any value to the variable, that variable is declared automatically. • The equal (=) operator is used to assign value to a variable. • Object References • It is necessary to understand how the Python interpreter works when we declare a variable. The process of treating variables is somewhat different from many other programming languages. • Python is the highly object-oriented programming language; that's why every data item belongs to a specific type of class. Consider the following example.
  • 38. print("John") Output: John • The Python object creates an integer object and displays it to the console. In the above print statement, we have created a string object. Let's check the type of it using the Python built- in type() function. type("John") Output: <class 'str'> • In Python, variables are a symbolic name that is a reference or pointer to an object. The variables are used to denote objects by that name. • Let's understand the following example a = 50 • In the above image, the variable a refers to an integer object. • Suppose we assign the integer value 50 to a new variable b.
  • 39. a = 50 b = a • The variable b refers to the same object that a points to because Python does not create another object. • 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.
  • 40. Object Identity • In Python, every created object identifies uniquely in Python. Python provides the guaranteed that no two objects will have the same identifier. The built-in id() function, is used to identify the object identifier. Consider the following example. a = 50 b = a print(id(a)) print(id(b)) # Reassigned variable a a = 500 print(id(a)) Output: 140734982691168 140734982691168 2822056960944 • We assigned the b = a, a and b both point to the same object. When we checked by the id() function it returned the same number. We reassign a to 500; then it referred to the new object identifier.
  • 41. Variable Names • We have already discussed how to declare the valid variable. Variable names can be any length can have uppercase, lowercase (A to Z, a to z), the digit (0-9), and underscore character(_). Consider the following example of valid variables names. name = "Devansh" age = 20 marks = 80.50 print(name) print(age) print(marks) Output: Devansh 20 80.5
  • 42. • Consider the following valid variables name. 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) Output: A B C D E D E F G F I • In the above example, we have declared a few valid variable names such as name, _name_ , etc. But it is not recommended because when we try to read code, it may create confusion. The variable name should be descriptive to make code more readable.
  • 43. • 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. • 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.
  • 44. Multiple Assignment • Python allows us to assign a value to multiple variables in a single statement, which is also known as multiple assignments. • We can apply multiple assignments in two ways, either by assigning a single value to multiple variables or assigning multiple values to multiple variables. Consider the following example. 1. Assigning single value to multiple variables Eg: x=y=z=50 print(x) print(y) print(z) Output: 50 50 50
  • 45. 2. Assigning multiple values to multiple variables: Eg: a,b,c=5,10,15 print a print b print c Output: 5 10 15 • The values will be assigned in the order in which variables appear.
  • 46. Python Variable Types • There are two types of variables in Python - Local variable and Global variable. Let's understand the following variables. Local Variable • Local variables are the variables that declared inside the function and have scope within the function. Let's understand the following example. Example - # Declaring a function def add(): # Defining local variables. They has scope only within a function a = 20 b = 30 c = a + b print("The sum is:", c) # Calling a function add() Output: The sum is: 50
  • 47. Explanation: • In the above code, we declared a function named add() and assigned a few variables within the function. These variables will be referred to as the local variables which have scope only inside the function. If we try to use them outside the function, we get a following error. add() # Accessing local variable outside the function print(a) • Output: The sum is: 50 print(a) NameError: name 'a' is not defined • We tried to use local variable outside their scope; it threw the NameError.
  • 48. Global Variables • Global variables can be used throughout the program, and its scope is in the entire program. We can use global variables inside or outside the function. • A variable declared outside the function is the global variable by default. Python provides the global keyword to use global variable inside the function. If we don't use the global keyword, the function treats it as a local variable. Let's understand the following example. Example - # Declare a variable and initialize it x = 101
  • 49. # Global variable in function def mainFunction(): # printing a global variable global x print(x) # modifying a global variable x = 'Welcome To Javatpoint' print(x) mainFunction() print(x) Output: 101 Welcome To Javatpoint Welcome To Javatpoint
  • 50. Explanation: • In the above code, we declare a global variable x and assign a value to it. Next, we defined a function and accessed the declared variable using the global keyword inside the function. Now we can modify its value. Then, we assigned a new string value to the variable x. • Now, we called the function and proceeded to print x. It printed the as newly assigned value of x.
  • 51. Delete a variable: • We can delete the variable using the del keyword. The syntax is given below. • Syntax – • del <variable_name> • In the following example, we create a variable x and assign value to it. We deleted variable x, and print it, we get the error "variable x is not defined". The variable x will no longer use in future. Example - # Assigning a value to x x = 6 print(x) # deleting a variable. del x print(x) Output: 6 Traceback (most recent call last): File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py", line 389, in print(x) NameError: name 'x' is not defined
  • 52. Maximum Possible Value of an Integer in Python • Unlike the other programming languages, Python doesn't have long int or float data types. It treats all integer values as an int data type. Here, the question arises. What is the maximum possible value can hold by the variable in Python? Consider the following example. • Example – # A Python program to display that we can store # large numbers in Python a = 10000000000000000000000000000000000000000000 a = a + 1 print(type(a)) print (a) Output: <class 'int'> 10000000000000000000000000000000000000000001 • As we can see in the above example, we assigned a large integer value to variable x and checked its type. It printed class <int> not long int. Hence, there is no limitation number by bits and we can expand to the limit of our memory. • Python doesn't have any special data type to store larger numbers.
  • 53. Print Single and Multiple Variables in Python • We can print multiple variables within the single print statement. Below are the example of single and multiple printing values. Example - 1 (Printing Single Variable) # printing single value a = 5 print(a) print((a)) Output: 5 5 Example - 2 (Printing Multiple Variables) a = 5 b = 6 # printing multiple variables print(a,b) # separate the variables by the comma Print(1, 2, 3, 4, 5, 6, 7, 8) Output: 5 6 1 2 3 4 5 6 7 8
  • 54. Basic Fundamentals: This section contains the fundamentals of Python, such as: i)Tokens and their types. ii) Comments a)Tokens: • The tokens can be defined as a punctuator mark, reserved words, and each word in a statement. • The token is the smallest unit inside the given program. There are following tokens in Python: Keywords. Identifiers. Literals. Operators.
  • 55. 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. a = 5 • We did not specify the type of the variable a, which has the value five from an integer. The Python interpreter will automatically interpret the variable as an integer. • We can verify the type of the program-used variable thanks to Python. The type() function in Python returns the type of the passed variable. • Consider the following illustration when defining and verifying the values of various data types.
  • 56. Program: a=10 b="Hi Python" c = 10.5 print(type(a)) print(type(b)) print(type(c)) Output: <type 'int'> <type 'str'> <type 'float'>
  • 57. Standard data types: • A variable can contain a variety of values. On the other hand, a person's id must be stored as an integer, while their name must be stored as a string. • The storage method for each of the standard data types that Python provides is specified by Python. The following is a list of the Python-defined data types. Numbers Sequence Type Boolean Set Dictionary
  • 58.
  • 59. • The data types will be briefly discussed in this tutorial section. We will talk about every single one of them exhaustively later in this instructional exercise. Numbers: • Numeric values are stored in numbers. The whole number, float, and complex qualities have a place with a Python Numbers datatype. Python offers the type() function to determine a variable's data type. The instance () capability is utilized to check whether an item has a place with a specific class. • When a number is assigned to a variable, Python generates Number objects. For instance,
  • 60. Program: a = 5 print("The type of a", type(a)) 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) ) Output: The type of a <class 'int'> The type of b <class 'float'> The type of c <class 'complex'> c is complex number: True Python supports three kinds of numerical data.
  • 61. • 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.
  • 62. Sequence Type String • The sequence of characters in the quotation marks can be used to describe the string. A string can be defined in Python using single, double, or triple quotes. • String dealing with Python is a direct undertaking since Python gives worked-in capabilities and administrators to perform tasks in the string. • When dealing with strings, the operation "hello"+" python" returns "hello python," and the operator + is used to combine two strings. • Because the operation "Python" *2 returns "Python," the operator * is referred to as a repetition operator. • The Python string is demonstrated in the following example.
  • 63. Example - 1 str = "string using double quotes" print(str) s = '''''A multiline string''' print(s) Output: string using double quotes A multiline string Look at the following illustration of string handling.
  • 64. 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 a nd str2 Output: he o hello javatpointhello javatpoint hello javatpoint how are you
  • 65. • 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 (*).
  • 66. 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) Output: [1, 'hi', 'Python', 2] [2] [1, 'hi'] [1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2] [1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
  • 67. Tuple: • In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from various data types. A parenthetical space () separates the tuple's components from one another. • Because we cannot alter the size or value of the items in a tuple, it is a read-only data structure. • Let's look at a straightforward tuple in action.
  • 68. 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"
  • 69. Output: <class 'tuple'> ('hi', 'Python', 2) ('Python', 2) ('hi',) ('hi', 'Python', 2, 'hi', 'Python', 2) ('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2) Traceback (most recent call last): File "main.py", line 14, in <module> t[2] = "hi"; TypeError: 'tuple' object does not support item assignment
  • 70. 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. • Look at the following example. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'} # 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())
  • 71. • Output: 1st name is Jimmy 2nd name is mike {1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'} dict_keys([1, 2, 3, 4]) dict_values(['Jimmy', 'Alex', 'john', 'mike'])
  • 72. Boolean: • True and False are the two default values for the Boolean type. These qualities are utilized to decide the given assertion valid or misleading. The class book indicates this. False can be represented by the 0 or the letter "F," while true can be represented by any value that is not zero. Look at the following example. # Python program to check the boolean type print(type(True)) print(type(False)) print(false) Output: <class 'bool'> <class 'bool'> NameError: name 'false' is not defined
  • 73. Set: • The data type's unordered collection is Python Set. It is iterable, mutable(can change after creation), and has remarkable components. The elements of a set have no set order; It might return the element's altered sequence. Either a sequence of elements is passed through the curly braces and separated by a comma to create the set or the built-in function set() is used to create the set. It can contain different kinds of values. • Look at the following example.
  • 74. Program: # Creating Empty set set1 = set() set2 = {'James', 2, 3,'Python'} #Printing Set value print(set2) # Adding element to the set set2.add(10) print(set2) #Removing element from the set set2.remove(2) print(set2) Output: {3, 'Python', 'James', 2} {'Python', 'James', 3, 2, 10} {'Python', 'James', 3, 10}
  • 75. Python Keywords • Every scripting language has designated words or keywords, with particular definitions and usage guidelines. Python is no exception. The fundamental constituent elements of any Python program are Python keywords. • This tutorial will give you a basic overview of all Python keywords and a detailed discussion of some important keywords that are frequently used. Introducing 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. • Python's built-in methods and classes are not the same as the keywords. Built-in methods and classes are constantly present; however, they are not as limited in their application as keywords.
  • 76. • Assigning a particular meaning to Python keywords means you can't use them for other purposes in our code. You'll get a message of SyntaxError if you attempt to do the same. If you attempt to assign anything to a built-in method or type, you will not receive a SyntaxError message; however, it is still not a smart idea. • Python contains thirty-five keywords in the most recent version, i.e., Python 3.8. Here we have shown a complete list of Python keywords for the reader's reference.
  • 77. in distinct versions of Python, the preceding keywords might be changed. Some extras may be introduced, while others may be deleted. By writing the following statement into the coding window, you can anytime retrieve the collection of keywords in the version you are working on.
  • 78. Code: # Python program to demonstrate the application of iskeyword() # importing keyword library which has lists import keyword # displaying the complete list using "kwlist()." print("The set of keywords in this version is: ") print( keyword.kwlist ) Output: The set of keywords in this version is : ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] By calling help(), you can retrieve a list of currently offered keywords: Code help("keywords")
  • 79. Python Literals Python Literals can be defined as data that is given in a variable or constant. • Python supports the following literals: 1. String literals: • String literals can be formed by enclosing a text in the quotes. We can use both single as well as double quotes to create a string. Example: "Aman" , '12345'
  • 80. Types of Strings: There are two types of Strings supported in Python: a) Single-line String- Strings that are terminated within a single-line are known as Single line Strings. Example: text1='hello' b) Multi-line String - A piece of text that is written in multiple lines is known as multiple lines string. There are two ways to create multiline strings: Adding black slash at the end of each line. Example: text1='hello user' print(text1) 'hellouser'
  • 81. 2) Using triple quotation marks:- Example: str2='''''welcome to SSSIT''' print str2 Output: welcome to SSSIT II. Numeric literals: Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.
  • 82. Example - Numeric Literals x = 0b10100 #Binary Literals y = 100 #Decimal Literal z = 0o215 #Octal Literal u = 0x12d #Hexadecimal Literal #Float Literal float_1 = 100.5 float_2 = 1.5e2 #Complex Literal a = 5+3.14j print(x, y, z, u) print(float_1, float_2) print(a, a.imag, a.real)
  • 83. Output: 20 100 141 301 100.5 150.0 (5+3.14j) 3.14 5.0 III. Boolean literals: • A Boolean literal can have any of the two values: True or False. Example - Boolean Literals x = (1 == True) y = (2 == False) z = (3 == True) a = True + 10 b = False + 10 print("x is", x) print("y is", y) print("z is", z) print("a:", a) print("b:", b)
  • 84. Output: x is True y is False z is False a: 11 b: 10 IV. Special literals: • Python contains one special literal i.e., None. • None is used to specify to that field that is not created. It is also used for the end of lists in Python. Example - Special Literals val1=10 val2=None print(val1) print(val2) Output: 10 None
  • 85. V. Literal Collections. • Python provides the four types of literal collection such as List literals, Tuple literals, Dict literals, and Set literals. List: • List contains items of different data types. Lists are mutable i.e., modifiable. • The values stored in List are separated by comma(,) and enclosed within square brackets([]). We can store different types of data in a List.
  • 86. Example - List literals list=['John',678,20.4,'Peter'] list1=[456,'Andrew'] print(list) print(list + list1) Output: ['John', 678, 20.4, 'Peter'] ['John', 678, 20.4, 'Peter', 456, 'Andrew'] • Dictionary: • Python dictionary stores the data in the key-value pair. • It is enclosed by curly-braces {} and each pair is separated by the commas(,).
  • 87. Example dict = {'name': 'Pater', 'Age':18,'Roll_nu':101} print(dict) Output: {'name': 'Pater', 'Age': 18, 'Roll_nu': 101} Tuple: Python tuple is a collection of different data-type. It is immutable which means it cannot be modified after creation. It is enclosed by the parentheses () and each element is separated by the comma(,). Example tup = (10,20,"Dev",[2,3,4]) print(tup) Output: (10, 20, 'Dev', [2, 3, 4])
  • 88. Set: Python set is the collection of the unordered dataset. It is enclosed by the {} and each element is separated by the comma(,). Example: - Set Literals set = {'apple','grapes','guava','papaya'} print(set) Output: {'guava', 'apple', 'papaya', 'grapes'}
  • 89. Python Operators Introduction: • 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 • Arithmetic Operators
  • 90. Arithmetic Operators: • Arithmetic operators used between two operands for a particular operation. There are many arithmetic operators. It includes the exponent (**) operator as well as the + (addition), - (subtraction), * (multiplication), / (divide), % (reminder), and // (floor division) operators. • Consider the following table for a detailed explanation of arithmetic operators.
  • 91.
  • 92. Program Code: • Now we give code examples of arithmetic operators in Python. The code is given below - 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)
  • 93. • Output: • Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - Addition of two numbers: 38 Subtraction of two numbers: 26 Multiplication of two numbers: 192 Division of two numbers: 5.333333333333333 Reminder of two numbers: 2 Exponent of two numbers: 1073741824 Floor division of two numbers: 5
  • 94. • 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. The example of comparison operators are ==, !=, <=, >=, >, <. In the below table, we explain the works of the operators.
  • 95. • Program Code: • Now we give code examples of Comparison operators in Python. The code is given below - 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)
  • 96. • Output: • Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - Two numbers are equal or not: False Two numbers are not equal or not: True a is less than or equal to b: False a is greater than or equal to b: True a is greater b: True a is less than b: False
  • 97. • Assignment Operators: • Using the assignment operators, the right expression's value is assigned to the left operand. There are some examples of assignment operators like =, +=, -=, *=, %=, **=, //=. In the below table, we explain the works of the operators.
  • 98.
  • 99. Program Code: Now we give code examples of Assignment operators in Python. The code is given below - a = 32 # 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*=b:', a*b) print('a%=b:', a%b) print('a**=b:', a**b) print('a//=b:', a//b)
  • 100. Output: • Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below – a=b: False a+=b: 38 a-=b: 26 a*=b: 192 a%=b: 2 a**=b: 1073741824 a//=b: 5
  • 101. Bitwise Operators: • The two operands' values are processed bit by bit by the bitwise operators. The examples of Bitwise operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left shift (<<), and Right shift (>>). Consider the case below. • 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 Let, Binary of x = 0101 Binary of y = 1000 Bitwise OR = 1101 8 4 2 1 1 1 0 1 = 8 + 4 + 1 = 13 Bitwise AND = 0000 0000 = 0 Bitwise XOR = 1101 8 4 2 1 1 1 0 1 = 8 + 4 + 1 = 13 Negation of x = ~x = (-x) - 1 = (-5) - 1 = -6 ~x = -6
  • 102. • In the below table, we are explaining the works of the bitwise operators.
  • 103. Program Code: Now we give code examples of Bitwise operators in Python. The code is given below - 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)
  • 104. Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - a&b: 4 a|b: 7 a^b: 3 ~a: -6 a<>b: 0
  • 105. Logical Operators • The assessment of expressions to make decisions typically uses logical operators. The examples of logical operators are and, or, and not. In the case of logical AND, if the first one is 0, it does not depend upon the second one. In the case of logical OR, if the first one is 1, it does not depend on the second one. Python supports the following logical operators. In the below table, we explain the works of the logical operators.
  • 106.
  • 107. Program Code: Now we give code examples of arithmetic operators in Python. The code is given below - 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))) Output: Now we give code examples of Bitwise operators in Python. The code is given below - Is this statement true?: False Any one statement is true?: True Each statement is true then return False and vice-versa: True
  • 108. Membership Operators: • The membership of a value inside a Python data structure can be verified using Python membership operators. The result is true if the value is in the data structure; otherwise, it returns false.
  • 109. Program Code: Now we give code examples of Membership operators in Python. The code is given below - x = ["Rose", "Lotus"] print(' Is value Present?', "Rose" in x) print(' Is value not Present?', "Riya" not in x) Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - Is value Present? True Is value not Present? True
  • 110. Identity Operators Program Code: Now we give code examples of Identity operators in Python. The code is given below - a = ["Rose", "Lotus"] b = ["Rose", "Lotus"] c = a print(a is c) print(a is not c) print(a is b) print(a is not b) print(a == b) print(a != b)
  • 111. Output: Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below - True False False True True False
  • 112. Operator Precedence: • The order in which the operators are examined is crucial to understand since it tells us which operator needs to be considered first. Below is a list of the Python operators' precedence tables.
  • 113.
  • 114. Python Comments • Introduction to Python Comments • We may wish to describe the code we develop. We might wish to take notes of why a section of script functions, for instance. We leverage the remarks to accomplish this. Formulas, procedures, and sophisticated business logic are typically explained with comments. The Python interpreter overlooks the remarks and solely interprets the script when running a program. Single-line comments, multi-line comments, and documentation strings are the 3 types of comments in Python. • Advantages of Using Comments • Our code is more comprehensible when we use comments in it. It assists us in recalling why specific sections of code were created by making the program more understandable. • Aside from that, we can leverage comments to overlook specific code while evaluating other code sections. This simple technique stops some lines from running or creates a fast pseudo-code for the program.
  • 115. • Below are some of the most common uses for comments: • Readability of the Code • Restrict code execution • Provide an overview of the program or project metadata • To add resources to the code • Types of Comments in Python • In Python, there are 3 types of comments. They are described below: • 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. If the comment continues to the next line, add a hashtag to the subsequent line and resume the conversation. Consider the accompanying code snippet, which shows how to use a single line comment:
  • 116. Code # This code is to show an example of a single-line comment print( 'This statement does not have a hashtag before it' ) Output: This statement does not have a hashtag before it The following is the comment: • # This code is to show an example of a single-line comment The Python compiler ignores this line. • Everything following the # is omitted. As a result, we may put the program mentioned above in one line as follows: Code print( 'This is not a comment' ) # this code is to show an example o f a single-line comment Output: This is not a comment • This program's output will be identical to the example above. The computer overlooks all content following #.
  • 117. • 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. Code: # it is a # comment # extending to multiple lines • In this case, each line is considered a comment, and they are all omitted.
  • 118. • Using String Literals: • Because Python overlooks string expressions that aren't allocated to a variable, we can utilize them as comments. Code: 'it is a comment extending to multiple lines' • We can observe that on running this code, there will be no output; thus, we utilize the strings inside triple quotes(""") as multi-line comments. 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.
  • 119. Code: # Code to show how we use docstrings in Python 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__ ) Output: This function adds the values of x and y
  • 120. 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. • In python, decision making is performed by the following statements.
  • 121.
  • 122. Indentation in Python • For the ease of programming and to achieve simplicity, python doesn't allow the use of parentheses for the block level code. In Python, indentation is used to declare a block. If two statements are at the same indentation level, then they are the part of the same block. • Generally, four spaces are given to indent the statements which are a typical amount of indentation in python. • Indentation is the most used part of the python language since it declares the block of code. All the statements of one block are intended at the same level indentation. We will see how the actual indentation takes place in decision making and other stuff in python.
  • 123. 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.
  • 124.
  • 125. 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 dyna mically 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") Output: enter the number: 10 The Given number is an even number
  • 126. 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"); Output: Enter a: 100 Enter b: 120 Enter c: 130 From the above three numbers given c is largest
  • 127. The if-else statement • 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 is given below. if condition: #block of statements else: #another block of statements (else-block)
  • 128.
  • 129. Example 1 : Program to check whether a person is eligible to vote or not. # Simple Python Program to check whether a person is eligible t o vote or not. age = int (input("Enter your age: ")) # Here, we are taking an integer num and taking input dynamica lly if age>=18: # Here, we are checking the condition. If the condition is true, w e will enter the block print("You are eligible to vote !!"); else: print("Sorry! you have to wait !!"); Output: Enter your age: 90 You are eligible to vote !!
  • 130. 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 dynamica lly if num%2 == 0: # Here, we are checking the condition. If the condition is true, w e will enter the block print("The Given number is an even number") else: print("The Given Number is an odd number") Output: enter the number: 10 The Given number is even number
  • 131. 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.
  • 132. if expression 1: # block of statements elif expression 2: # block of statements elif expression 3: # block of statements else: # block of statements
  • 133.
  • 134. 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 th e 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 th e block print("The given number is equal to 50"); elif number==100: # Here, we are checking the condition. If the condition is true, we will enter th e block print("The given number is equal to 100"); else: print("The given number is not equal to 10, 50 or 100");
  • 135. Output: Enter the number?15 The given number is not equal to 10, 50 or 100
  • 136. 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 bloc k 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 bloc k 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 bloc k 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 bloc k print("You scored grade C ...") else: print("Sorry you are fail ?")
  • 137. Output: Enter the marks? 89 Congrats ! you scored grade A ...
  • 138. Python Loops • The following loops are available in Python to fulfil the looping needs. Python offers 3 choices for running the loops. The basic functionality of all the techniques is the same, although the syntax and the amount of time required for checking the condition differ. • We can run a single statement or set of statements repeatedly using a loop command. • The following sorts of loops are available in the Python programming language.
  • 139.
  • 140. • 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. We will discuss them later in detail. • Let us quickly go over the definitions of these loop control statements.
  • 141.
  • 142. The for Loop • Python's 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 } • In this case, the variable value is used to hold the value of every item present in the sequence before the iteration begins until this particular iteration is completed. • Loop iterates until the final item of the sequence are reached.
  • 143. Code: # 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) Output: The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
  • 144. Using else Statement with for Loop: As already said, a 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. Here is a code to better understand if-else statements.
  • 145. Code: # 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 e xecuted else: print(s)
  • 147. Now similarly, using else with for loop. Syntax: for value in sequence: # executes the statements until sequences ar e exhausted else: # executes these statements when for loop is completed
  • 148. Code: # Python program to show how to use else statement with fo r 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")
  • 149. Output: 3 9 3 9 7 These are the odd numbers present in the tuple
  • 150. 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. The example that follows will make this clear.
  • 151. Code: # Python program to show the working of range() functio n print(range(15)) print(list(range(15))) print(list(range(4, 9))) print(list(range(5, 25, 4))) Output: range(0, 15) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] [4, 5, 6, 7, 8] [5, 9, 13, 17, 21] • 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.
  • 152. Code: # Python program to iterate over a sequence with the hel p of indexing tuple_ = ("Python", "Loops", "Sequence", "Condition", "R ange") # iterating over tuple_ using range() function for iterator in range(len(tuple_)): print(tuple_[iterator].upper()) Output: PYTHON LOOPS SEQUENCE CONDITION RANGE
  • 153. 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.
  • 154. Code # 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") Output: Python Loops Python Loops Python Loops Python Loops
  • 155. 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. Code #Python program to show how to use else statement with th e 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")
  • 156. Output: Python Loops Python Loops Python Loops Python Loops 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. Code: # Python program to show how to write a single statem ent while loop counter = 0 while (count < 3): print("Python Loops")
  • 157. Loop Control Statements 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. Code: # Python program to show how the continue statement work s # Initiating the loop for string in "Python Loops": if string == "o" or string == "p" or string == "t": continue print('Current Letter:', string)
  • 158. Output: Current Letter: P Current Letter: y Current Letter: h Current Letter: n Current Letter: Current Letter: L Current Letter: s
  • 159. Break Statement: It stops the execution of the loop when the break statement is reached. Code: # 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)
  • 160. Output: Current Letter: P Current Letter: y Current Letter: t Current Letter: h Current Letter: o Current Letter: n Current Letter:
  • 161. Pass Statement: Pass statements are used to create empty loops. Pass statement is also employed for classes, functions, and empty control statements. Code: # Python program to show how the pass statement works for a string in "Python Loops": pass print( 'Last Letter:', string) Output: Last Letter: s
  • 162. Python Functions • A collection of related assertions that carry out a mathematical, analytical, or evaluative operation is known as a function. An assortment of proclamations called Python Capabilities returns the specific errand. Python functions are necessary for intermediate-level programming and are easy to define. Function names meet the same standards as variable names do. The objective is to define a function and group-specific frequently performed actions. Instead of repeatedly creating the same code block for various input variables, we can call the function and reuse the code it contains with different variables. • Client-characterized and worked-in capabilities are the two primary classes of capabilities in Python. It aids in maintaining the program's uniqueness, conciseness, and structure.
  • 163. • Advantages of Python Functions • Pause We can stop a program from repeatedly using the same code block by including functions. • Once defined, Python functions can be called multiple times and from any location in a program. • Our Python program can be broken up into numerous, easy-to-follow functions if it is significant. • The ability to return as many outputs as we want using a variety of arguments is one of Python's most significant achievements. • However, Python programs have always incurred overhead when calling functions. • However, calling functions has always been overhead in a Python program.
  • 164. Syntax: # An example Python Function def function_name( parameters ): # code block The accompanying components make up to characterize a capability, as seen previously. • The start of a capability header is shown by a catchphrase called def. • function_name is the function's name, which we can use to distinguish it from other functions. We will utilize this name to call the capability later in the program. Name functions in Python must adhere to the same guidelines as naming variables. • Using parameters, we provide the defined function with arguments. Notwithstanding, they are discretionary. • A colon (:) marks the function header's end. • We can utilize a documentation string called docstring in the short structure to make sense of the reason for the capability. • Several valid Python statements make up the function's body. The entire code block's indentation depth-typically four spaces-must be the same. • A return expression can get a value from a defined function.
  • 165. • Illustration of a User-Defined Function • We will define a function that returns the argument number's square when called. # Example Python Code for User-Defined function 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_ ) Output: The square of the given number is: 36
  • 166. • 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 Python Code for calling a function # Defining a function def a_function( string ): "This prints the value of length of string" 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" ) ) Output: Length of the string Functions is: 9 Length of the string Python is: 6
  • 167. 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, Code # 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 ) Output: Squares of the list are: [289, 2704, 64]
  • 168. Function Arguments The following are the types of arguments that we can use to call a function: 1. Default arguments 2. Keyword arguments 3. Required arguments 4. Variable-length arguments 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.
  • 169. Code: # Python code to demonstrate the use of default argum ents # 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)
  • 170. Output: Passing only one argument number 1 is: 30 number 2 is: 20 Passing two arguments number 1 is: 50 number 2 is: 30
  • 171. • Keyword Arguments • Keyword arguments are linked to the arguments of a called function. While summoning a capability with watchword contentions, the client might tell whose boundary esteem it is by looking at the boundary name. • We can eliminate or orchestrate specific contentions in an alternate request since the Python translator will interface the furnished watchwords to connect the qualities with its boundaries. One more method for utilizing watchwords to summon the capability() strategy is as per the following:
  • 172. Code: # 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" ) function( 50, 30) # Calling function and passing arguments using keyword print( "With using keyword" ) function( n2 = 50, n1 = 30)
  • 173. Output: Without using keyword number 1 is: 50 number 2 is: 30 With using keyword number 1 is: 30 number 2 is: 50
  • 174. • 3) Required Arguments • Required arguments are those supplied to a function during its call in a predetermined positional sequence. The number of arguments required in the method call must be the same as those provided in the function's definition. • We should send two contentions to the capability() all put together; it will return a language structure blunder, as seen beneath.
  • 175. Code: # 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" )
  • 176. Output: Passing out of order arguments number 1 is: 30 number 2 is: 20 Passing only one argument Function needs two positional arguments
  • 177. 4) Variable-Length Arguments: • We can involve unique characters in Python capabilities to pass many contentions. However, we need a capability. This can be accomplished with one of two types of characters: • "args" and "kwargs" refer to arguments not based on keywords. • To help you understand arguments of variable length, here's an example.
  • 178. Code: # 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)
  • 179. Output: ['PYTHON', 'FUNCTIONS', 'TUTORIAL'] [['First', 'Python'], ['Second', 'Functions'], ['Third', 'Tutorial']]
  • 180. 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 > • 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. • A return statement in Python functions is depicted in the following example.
  • 181. Code: # 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 ) )
  • 182. • Output: With return statement 2704 Without return statement None
  • 183. Standard Type built in functions • Python provides a wide range of built-in functions to work with standard data types. Here are some of the commonly used built-in functions for various standard data types: 1. Numeric Types: • int(): Converts a value to an integer. • float(): Converts a value to a floating-point number. • abs(): Returns the absolute value of a number. • round(): Rounds a floating-point number to the nearest integer.
  • 184. • 2. Strings: • str(): Converts a value to a string. • len(): Returns the length of a string. • upper(): Converts a string to uppercase. • lower(): Converts a string to lowercase. • strip(): Removes leading and trailing whitespace from a string. • split(): Splits a string into a list of substrings based on a delimiter. • join(): Joins a list of strings into a single string using a delimiter. • find(): Searches for a substring within a string and returns its index. • replace(): Replaces occurrences of a substring in a string with another substring.
  • 185. • 3. Lists: • list(): Converts an iterable (e.g., tuple, string) to a list. • len(): Returns the number of elements in a list. • append(): Adds an element to the end of a list. • extend(): Appends the elements of an iterable to a list. • insert(): Inserts an element at a specific index in a list. • remove(): Removes the first occurrence of a specified value from a list. • pop(): Removes and returns an element at a specified index. • index(): Returns the index of the first occurrence of a specified value. • count(): Returns the number of occurrences of a specified value in a list. • sort(): Sorts the elements of a list in ascending order. • reverse(): Reverses the order of elements in a list.
  • 186. • 4. Tuples: • tuple(): Converts an iterable (e.g., list, string) to a tuple. • len(): Returns the number of elements in a tuple. • index(): Returns the index of the first occurrence of a specified value. • count(): Returns the number of occurrences of a specified value in a tuple. • 5. Dictionaries: • dict(): Creates a new dictionary or converts an iterable of key-value pairs to a dictionary. • len(): Returns the number of key-value pairs in a dictionary. • keys(): Returns a list of keys in the dictionary. • values(): Returns a list of values in the dictionary. • items(): Returns a list of key-value pairs as tuples. • get(): Returns the value associated with a key, or a default value if the key is not found. • pop(): Removes and returns the value associated with a key. • update(): Updates a dictionary with key-value pairs from another dictionary.
  • 187. Unsupported types in python Following are some of the types that are not supported by python Charcter type (char): In python there is no character data type, in python character is a string of length one, it is represented by class str. Pointers: No, we don't have any kind of Pointer in Python language. In C and C++, a pointer is a variable that holds a memory address, but we don't have any kind of Pointer in Python , if you want to find address of any object then you need to use id() function. Program: a=10 print(id(a)) #id() function is used to find address output: 9789280 long int and short int: In c programming for long size integer values and short size integer values we use long int data type and short int data type but python do not support long int and short int , in python for both long and short size integers we use type int. double data type: We use double data type for long size float values ,but python do not support double type. In python even for long size float values you can use float data type.python float is actually C’s double data type
  • 188. lambda function A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression. Syntax lambda arguments : expression The expression is executed and the result is returned: Example Add 10 to argument a, and return the result: x = lambda a: a + 10 print(x(5)) output: 15 •
  • 189. Python Function Recursion: Python also accepts function recursion, which means a defined function can call itself. Function which calls itself is know as recursion. This has the benefit of meaning that you can loop through data to reach a result. Example: def name(): print(“my name is nagendra”) name() name() name()
  • 190. output: my name is nagendra my name is nagendra my name is nagendra my name is nagendra : : : • in above example I written name() function inside name() function, which means function name() calls itself , so it keep on repeating same code again and again, so we can loop statements by using recursion
  • 191. Following is an example of a recursive function to find the factorial of an integer. • Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6= 720 Example of a recursive function def factorial(n): if n == 1: return 1 else: return n * factorial(n-1) n = 5 print("The factorial of", n, "is", factorial(n)) output: The factorial of 5 is 120
  • 192. Built-In Functions Python has a set of built-in functions. input() Input() Python built-in functions, reads an input. Example: a=int(input(“enter no:”)) print(a) output: enter no: 10 10 eval() Eval( ) function will accept any data type values that you enter. Example: a=eval(input(“enter no:”)) print(a) output: enter no: 10 10
  • 193. exec() exec() runs Python code dynamically. >>> exec('a=2;b=3;print(a+b)') Output 5 hex() Hex() Python built-in functions, converts an integer to hexadecimal. >>> hex(16) Output ‘0x10’ id() id() returns an object’s identity(address). >>> id(orange) Output 100218832
  • 194. len() We’ve seen len() so many times by now. It returns the length of an object. Example: a=(1,2,3,4,5,6,7) print(len(a)) output: 7 max() max() returns the item, in a sequence, with the highest value of all. Example: a=(1,2,3,4,5,6,7) print(max(a)) output: 7 min() min() returns the item, in a sequence, with the smallest value of all. Example: a=(1,2,3,4,5,6,7) print(min(a)) output: 1
  • 195. pow() pow() takes two arguments- say, x and y. It then returns the value of x to the power of y. >>> pow(3,4) Output 81 print() We don’t think we need to explain this anymore. We’ve been seeing this function since the beginning. >>> print("hi”) output: hi repr() repr() returns a representable string of an object. >>> repr("Hello") Output “‘Hello'”
  • 196. range() we use range ( ) function in order to print values in sequence example: >>> for i in range(1,6): print(i) Output 1 2 3 4 5 sorted() Like we’ve seen before, sorted() prints out a sorted version of an iterable. It does not, however, alter the iterable. >>> sorted('Python') Output [‘P’, ‘h’, ‘n’, ‘o’, ‘t’, ‘y’] sum() The function sum() takes an iterable as an argument, and returns the sum of all values. >>> sum([3,4,5],3) Output 15
  • 197. type() We have been seeing the type() function to check the type of object we’re dealing with. >>> type(10) Output <class ‘int’>
  • 198. other built in functions : int(), float(), str(), complex( ), list ( ) , tuple ( ) , set ( ) . • print(int(10.5)) #converting float value to int print(int("10")) #converting string to int • print(float(10)) #converting int to float print(float("10.5")) #converting string to float print(str(10)) #converting int to str • print(str(10.5)) #converting float to str • print(complex(1,2.3))#converting int and float numbers to complex print(list((1,2.4,"btech"))) #converting tuple to list print(tuple([1,2.4,"btech"])) #converting list to tuple print(set([1,2.4,"btech"])) #converting list to set
  • 199. output: 10 10 10.0 10.5 10 10.5 (1+2.3j) [1, 2.4, 'btech'] (1, 2.4, 'btech') {'btech', 1, 2.4}
  • 200. Python object • Python is an object-oriented programming language. Everything is in Python treated as an object, including variable, function, list, tuple, dictionary, set, etc. Every object belongs to its class. For example - An integer variable belongs to integer class. An object is a real-life entity. An object is the collection of various data and functions that operate on those data. An object contains the following properties.
  • 201. Value: data item that is represented by an object Example: a=10 #here 10 is value print(a) output: 10 Type: an object’s type indicates what kind of values an object can hold. what operations can be applied to such objects. type ( ) function is used to find type of object Example: a=10 print(type(a)) output: <class ‘int’>
  • 202. Identity : Each object contains unique identity that differentiates from all other objects. And you can check id of an object by using id ( ) function. Example: a=10 print(id(a)) output: 9789280
  • 203. literals and types of literal constants literal is a raw data given to variable or constant in python there are various types of literals they are numberic literals : 3 types – integer, float, complex Example: a=10 b=10.5 c=1+2j print(a) print(b) print(c) output: 10 10.5 1+2j
  • 204. string literals : Example: a=”hello” print(a) output: Hello special literals : None if you dont want to give any value to the variable then you can use None Example: a=None print(a) output: here you will not get any output because None means nothing
  • 205. python - Type conversion • type conversion is the process of converting data of one type to another. For example: converting integer data to string. There are two types of type conversion in Python. Implicit Conversion - automatic type conversion Explicit Conversion - manual type conversion
  • 206. Implicit Type Conversion: • In certain situations, Python automatically converts one data type to another. This is known as implicit type conversion. • Python always converts smaller data types to larger data types to avoid the loss of data. • Integer is smaller than float and float is smaller than string Example: a=10 b=10.5 c=a+b print(c) output: 20.5
  • 207. • In the above example, I took a value as 10 which is integer and b value as 10.5 which is float .though i given one value as integer and other value as float , i got output as float value because Python always converts smaller data types to larger data types to avoid the loss of data. In this example integer value is smaller than float value, so integer value 10 is automatically converted into float value,so i got output 20.5 which is float value.
  • 208. Explicit Type Conversion: • In Explicit Type Conversion, Python cannot automatically converts one data type to another so, users converts one data type to another manually . • We use the built-in functions like int(), float(), str(), complex( ), list ( ) , tuple ( ) , set ( ) to perform explicit type conversion. • This type of conversion is also called typecasting because the user casts (changes) the data type of the objects.
  • 209. Example: • print(int(10.5)) #converting float value to int print(int("10")) #converting string to int • print(float(10)) #converting int to float print(float("10.5")) #converting string to float print(str(10)) #converting int to str • print(str(10.5)) #converting float to str • print(complex(1,2.3))#converting int and float numbers to complex print(list((1,2.4,"btech"))) #converting tuple to list print(tuple([1,2.4,"btech"])) #converting list to tuple print(set([1,2.4,"btech"])) #converting list to set
  • 210. output: 10 10 10.0 10.5 10 10.5 (1+2.3j) [1, 2.4, 'btech'] (1, 2.4, 'btech') {'btech', 1, 2.4}