SlideShare a Scribd company logo
1 of 164
Python programming
CRT
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 Program to calculate the
square of a given number
#take input from the user
num = int(input("Enter a number to calculate
square : "))
print("square =",num*num)
Output:
Enter a number to calculate square : 5
square = 25
Python program to calculate the cube
of a number
#take input from the user
num = int(input("Enter a number to calculate
cube : "))
print("cube =",num*num*num)
output:
Enter a number to calculate cube : 2
cube = 8
Python program to check given
number is even or odd
#taking input from the user
num = int(input("Enter a number to check even/odd "))
#if number is divisible by 2
if num%2 == 0:
print(num,"is even number")
else:
print(num,"is odd number")
Output:
Enter a number to check even/odd 5
5 is odd number
Enter a number to check even/odd 2
2 is even number
Python Program to Find the max of 3
numbers
Program:
n1 = int(input("please give first number n1: "))
n2 = int(input("please give second number n2: "))
n3 = int(input("please give third number n3: "))
if n1>=n2 and n1>=n3:
print(" n1 is greatest");
if n2>=n1 and n2>=n3:
print(" n2 is greatest");
if n3>=n1 and n3>=n2:
print("n3 is greatest");
Output:
please give first number n1: 5
please give second number n2: 33
please give third number n3: 1
n2 is greatest
Python program to find smallest
number among three
a = int(input("Enter the value for a :"))
b = int(input("Enter the value for b :"))
c = int(input("Enter the value for c :"))
#comparing integer ‘a’ with other two integer
if a<=b and a<=c:
print("a is smallest")
#comparing integer ‘b’ with other two integer
elif b<=a and b<=c:
print("b is smallest")
#comparing integer ‘c’ with other two integer
elif c<=a and c<=b:
print("c is smallest")
Output:
Enter the value for a :6
Enter the value for b :8
Enter the value for c :0
c is smallest
Python program to reverse a number
Method 1: Reverse Using While Loop in Python:
Program:
n = int(input("Please give a number: "))
print("Before reverse your number is : %d" %n)
reverse = 0
while n!=0:
reverse = reverse*10 + n%10
n = (n//10)
print("After reverse : %d" %reverse)
Output:
please give a number : 12345
before reverse your number is : 12345
After reverse : 54321
Method 2: Reverse Using String Slicing in Python
Program:
num = int(input("Please give a number: "))
print("Before reverse your number is : %d" %num)
rev = int(str(num)[::-1])
print("After reverse the number:", rev)
Output:
Please give a number: 12345
Before reverse your number is : 12345
After reverse the number: 54321
Python program to check number
representation is in binary
num = int(input("please give a number : "))
while(num>0):
j=num%10
if j!=0 and j!=1:
print("num is not binary")
break
num=num//10
if num==0:
print("num is binary")
Output:
please give a number : 5
num is not binary
Armstrong number program in python
Method 1: Check Armstrong Using a While Loop
# Armstrong number program using while loop
num = int(input("Please give a number: "))
sum = 0
temp = num
# count the number of digits in input
count = len(str(num))
# loop on each digit and calculate the sum
while temp > 0:
digit = temp % 10
sum += digit ** count
temp //= 10
# check if the number is an Armstrong or not
if num == sum:
print("Given ",num, "is an Armstrong number")
else:
print("Given ",num, "is not an Armstrong number")
Output:
Please give a number: 153
Given 153 is an Armstrong number
Method 2: Armstrong Using List Comprehension:
# Armstrong number using list comprehension
num = int(input("Please Enter a Number: "))
digits = [int(digit) for digit in str(num)]
count = len(digits)
sum = sum([digit ** count for digit in digits])
if num == sum:
print("Given ", num, "is an Armstrong number")
else:
print("Given ", num, "is not an Armstrong number")
Output:
Please Enter a Number: 371
Given 371 is an Armstrong number
Prime Number Program in Python
Program:
n = int(input("please give a number : "))
i,temp=0,0
for i in range(2,n//2):
if n%i == 0:
temp=1
break
if temp == 1:
print("given number is not prime")
else:
print("given number is prime")
Output:
please give a number : 23
given number is prime
Fibonacci series program in python
using iterative method
Program:
n = int(input("please give a number for fibonacci series :
"))
first,second=0,1
print("fibonacci series are : ")
for i in range(0,n):
if i<=1:
result=i
else:
result = first + second;
first = second;
second = result;
print(result)
Output:
please give a number for fibonacci series : 5
fibonacci series are :
0
1
1
2
3
Python program for palindrome using
an iterative method
n = int(input("please give a number : "))
reverse,temp = 0,n
while temp!=0:
reverse = reverse*10 + temp%10;
temp=temp//10;
if reverse==n:
print("number is palindrom")
else:
print("number is not palindrom")
Output:
please give a number : 9889
number is palindrom
Python program for palindrome number
using recursive method
n = int(input("please give a number : "))
def reverse(num):
if num<10:
return num
else:
return int(str(num%10) + str(reverse(num//10)))
def isPalindrome(num):
if num == reverse(num):
return 1
return 0
if isPalindrome(n) == 1:
print("Given number is a palindrome")
else:
print("Given number is a not palindrome")
• Output:
please give a number : 7887
Given number is a palindrome
Swap two variables without using the
third variable in Python
a = int(input("please give first number a: "))
b = int(input("please give second number b: "))
a=a-b
b=a+b
a=b-a
print("After swapping")
print("value of a is : ", a);
print("value of b is : ", b);
• Output:
please give first number a: 6
please give second number b: 3
After swapping
value of a is : 3
value of b is : 6
Python Program to swap two number
using third variable
a = int(input("please give first number a: "))
b = int(input("please give second number b: "))
tempvar=a
a=b
b=tempvar
print("After swapping")
print("value of a is : ", a);
print("value of b is : ", b);
Output:
please give first number a: 5
please give second number b: 7
After swapping
value of a is : 7
value of b is : 5
Python Program to find Prime factors
of given integer
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
num = int(input("Please enter a number: "))
print("Prime factors of", num, "are:", prime_factors(num))
Output:
Enter a number: 24
Prime factors of 24 are: [2, 2, 2, 3]
Add two number without + Operator
in Python
def add_numbers(x, y):
while y != 0:
temp = x & y
x = x ^ y
y = temp << 1
return x
num1 = 10
num2 = 15
sum_result = add_numbers(num1, num2)
print(f"Sum of {num1} and {num2} is: {sum_result}")
Output:
Sum of 10 and 15 is: 25
Perfect number program in Python
num = int(input("please give a number: "))
sum=0
for i in range(1,(num//2)+1):
remainder = num % i
if remainder == 0:
sum = sum + i
if sum == num:
print("given input is perfect number")
else:
print("given input is not a perfect number")
Output1:
please give a number: 65
given input is not a perfect number
Output2:
please give a number: 6
given input is perfect number
Python code to find the average of
numbers
size=int(input("Enter the number of elements you want
in array: "))
arr=[]
#taking input of the list
for i in range(0,size):
elem=int(input("Please give value for index "+str(i)+":
"))
arr.append(elem)
#taking average of the elements of the list
avg=sum(arr)/size
print("Average of the array elements is ",avg)
Output:
Enter the number of elements you want in array: 4
Please give value for index 0: 3
Please give value for index 1: 4
Please give value for index 2: 5
Please give value for index 3: 6
Average of the array elements is 4.5
Python program to calculate the
factorial using iterative approach
#taking an integer input from user
num=int(input("Enter the whole number to find the factorial: "))
factorial = 1
if num < 0:
print("Factorial can't be calculated for negative number")
elif num == 0:
print("Factorial of 0 is 1")
else:
#calculating the factorial of the input number
for i in range(1,num + 1):
factorial = factorial*i
print("Factorial of",num,"is",factorial)
Output:
Enter the whole number to find the factorial: 5
Factorial of 5 is 120
Factorial Program in python using recursion with explanation
def fact(n):
if n == 1:
return n
else:
#recursion
return n*fact(n-1)
num = int(input("Enter a whole number to find Factorial: "))
if num < 0:
print("Factorial can't be calculated for negative number")
elif num == 0:
print("Factorial of 0 is 1")
else:
print("Factorial of",num,"is",fact(num))
Output:
Enter a whole number to find Factorial: 5
Factorial of 5 is 120
Python Program to Print Prime
Number in given range
lower_value = int(input ("Please, Enter the Lowest Range Value:
"))
upper_value = int(input ("Please, Enter the Upper Range Value:
"))
print ("The Prime Numbers in the range are: ")
for number in range (lower_value, upper_value + 1):
if number > 1:
for i in range (2, number):
if (number % i) == 0:
break
else:
print (number)
Please, Enter the Lowest Range Value: 14
Please, Enter the Upper Range Value: 97
The Prime Numbers in the range are:
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
Python program to calculate the
power using ‘pow()’ method
base = int(input("Enter the value for base :"))
exponent = int(input("Enter the value for exponent:"))
print(base,"to power ",exponent,"=",end = ' ')
print(pow(base,exponent))
output:
Enter the value for base :5
Enter the value for exponent :4
5 to power 4 = 625
Python program to calculate the
power using ‘for-loop’
#taking 3 integer as input from the user
base = int(input("Enter the value for base :"))
exponent = int(input("Enter the value for exponent :"))
result=1;
print(base,"to power ",exponent,"=",end = ' ')
#using ‘for’ loop with ‘range’ function
for exponent in range(exponent, 0, -1):
result *= base
print(result)
Output:
Enter the value for base :5
Enter the value for exponent :4
5 to power 4 = 625
Python program to calculate the
power using ‘while-loop’
base = int(input("Enter the value for base :"))
exponent = int(input("Enter the value for exponent :"))
result=1;
print(base,"to power ",exponent,"=",end = ' ')
#using while loop with a condition that come out of while
loop if exponent is 0
while exponent != 0:
result = base * result
exponent-=1
print(result)
Output:
Enter the value for base :5
Enter the value for exponent :4
5 to power 4 = 625
Python program to calculate the
square root of a number
#check if the input number is negative
if num<0:
print("Negative numbers can't have square
roots")
else:
print("square roots = ",math.sqrt(num))
output:
Enter a number to find square root : 9
square roots = 3.0
Python Program to find l.c.m. of two
numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 > num2:
greater = num1
else:
greater = num2
while(True):
if((greater % num1 == 0) and (greater % num2 == 0)):
lcm = greater
break
greater += 1
print("LCM of",num1,"and",num2,"=",greater)
output:
Enter first number: 6
Enter second number: 4
LCM of 6 and 4 = 12
Python code to find h.c.f. of two
numbers
#taking two inputs from the user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
#checking for smaller number
if num1 > num2:
minimum = num2
else:
minimum = num1
#finding highest factor of the numbers
for i in range(1, minimum+1):
if((num1 % i == 0) and (num2 % i == 0)):
hcf = i
print("hcf/gcd of",num1,"and",num2,"=",hcf)
output:
Enter first number: 8
Enter second number: 2
hcf/gcd of 8 and 2 = 2
Python code to find h.c.f. of two
numbers using recursion
def gcd(num1,num2):
if num2 == 0:
return num1;
return gcd(num2, num1 % num2)
#taking inputs from the user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("hcf/gcd
of",num1,"and",num2,"=",gcd(num1,num2))
output:
Enter first number: 8
Enter second number: 2
hcf/gcd of 8 and 2 = 2
Convert Decimal to Binary Using Loop
decimal = temp = int(input("Please Enter a decimal
number: "))
binary = ""
while temp > 0:
remainder = temp % 2
binary = str(remainder) + binary
temp = temp // 2
print("Binary number is ", binary, " for ", decimal)
Output:
Please Enter a decimal number: 13
Binary number is 1101 for 13
Decimal to Binary Using bin() function
in Python
decimal = int(input("Please Enter a decimal
number: "))
binary = bin(decimal)
print("Binary number is ", binary[2:], " for ",
decimal)
Output:
Please Enter a decimal number: 34
Binary number is 100010 for 34
Python Program to convert Decimal
to Octal number
def decimal_to_octal(decimal):
if decimal == 0:
return ""
quotient = decimal // 8
remainder = decimal % 8
return decimal_to_octal(quotient) + str(remainder)
decimal = int(input("Please Enter a decimal number: "))
octal = decimal_to_octal(decimal)
print("Octal number is ", octal, " for ", decimal)
Output:
Please Enter a decimal number: 157
Octal number is 235 for 157
Leap Year Program in Python
year = int(input("Please Enter a year: "))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
else:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
Output:
Enter a year: 2000
2000 is a leap year
Convert Celsius to Fahrenheit in Python
# program to convert Celsius to Fahrenheit
celsius = float(input("Enter temperature in
Celsius: "))
fahrenheit = (celsius * 1.8) + 32
print("Temperature in Fahrenheit: ", fahrenheit)
Output:
Enter temperature in Celsius: 30
Temperature in Fahrenheit: 86.0
Python program to convert Fahrenheit
into Celsius
#taking input from the user
fahrenheit = float(input("Please give the
Hahrenheit Temperature : "))
#converting Celsius into Fahrenheit
celsius = ((fahrenheit-32)*5)/9
print("Celcius= ",celsius)
output:
Please give the Hahrenheit Temperature : 19.6
Celcius= -6.888888888888888
Python program to calculate simple
interest
#taking the values of principal, rate of interest and time
from the user
principal = int(input("Enter the principal amount: "))
rate = int(input("Enter the rate of interest: "))
time = int(input("Enter the time of interest in year: "))
#using the input values calculate simple interest
simpleInterest = (principal*rate*time)/100
print("Simple Interest = ",simpleInterest)
output:
Enter the principal amount: 100
Enter the rate of interest: 5
Enter the time of interest in year: 5
Simple Interest = 25.0

More Related Content

Similar to Python programming ppt.pptx

Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonSoba Arjun
 
PYTHON IN DETAIL INFORMATION EDUCATIONAL
PYTHON IN DETAIL INFORMATION EDUCATIONALPYTHON IN DETAIL INFORMATION EDUCATIONAL
PYTHON IN DETAIL INFORMATION EDUCATIONALauramarketings
 
How to start Python? - lesson 1
How to start Python? - lesson 1How to start Python? - lesson 1
How to start Python? - lesson 1Shohel Rana
 
Machine learning session 1
Machine learning session 1Machine learning session 1
Machine learning session 1NirsandhG
 
Python programming
Python programmingPython programming
Python programmingMegha V
 
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
 
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
 
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
 
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
 
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
 
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
 
Presentation (1).pdf
Presentation (1).pdfPresentation (1).pdf
Presentation (1).pdfnaganeparth06
 
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
 
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
 
Machine learning libraries with python
Machine learning libraries with pythonMachine learning libraries with python
Machine learning libraries with pythonVishalBisht9217
 
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
 

Similar to Python programming ppt.pptx (20)

Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
PYTHON IN DETAIL INFORMATION EDUCATIONAL
PYTHON IN DETAIL INFORMATION EDUCATIONALPYTHON IN DETAIL INFORMATION EDUCATIONAL
PYTHON IN DETAIL INFORMATION EDUCATIONAL
 
How to start Python? - lesson 1
How to start Python? - lesson 1How to start Python? - lesson 1
How to start Python? - lesson 1
 
Machine learning session 1
Machine learning session 1Machine learning session 1
Machine learning session 1
 
Python programming
Python programmingPython programming
Python programming
 
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
 
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 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
 
Python
PythonPython
Python
 
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
 
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
 
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
 
Presentation (1).pdf
Presentation (1).pdfPresentation (1).pdf
Presentation (1).pdf
 
Python training Course in Mohali
Python training Course in MohaliPython training Course in Mohali
Python training Course in Mohali
 
Python presentation by Monu Sharma
Python presentation by Monu SharmaPython presentation by Monu Sharma
Python presentation by Monu Sharma
 
PYTHON COURSE IN KHANNA
PYTHON COURSE IN KHANNAPYTHON COURSE IN KHANNA
PYTHON COURSE IN KHANNA
 
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
 
Machine learning libraries with python
Machine learning libraries with pythonMachine learning libraries with python
Machine learning libraries with python
 
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
 

Recently uploaded

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 

Recently uploaded (20)

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 

Python programming ppt.pptx

  • 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 Program to calculate the square of a given number #take input from the user num = int(input("Enter a number to calculate square : ")) print("square =",num*num) Output: Enter a number to calculate square : 5 square = 25
  • 121. Python program to calculate the cube of a number #take input from the user num = int(input("Enter a number to calculate cube : ")) print("cube =",num*num*num) output: Enter a number to calculate cube : 2 cube = 8
  • 122. Python program to check given number is even or odd #taking input from the user num = int(input("Enter a number to check even/odd ")) #if number is divisible by 2 if num%2 == 0: print(num,"is even number") else: print(num,"is odd number") Output: Enter a number to check even/odd 5 5 is odd number Enter a number to check even/odd 2 2 is even number
  • 123. Python Program to Find the max of 3 numbers Program: n1 = int(input("please give first number n1: ")) n2 = int(input("please give second number n2: ")) n3 = int(input("please give third number n3: ")) if n1>=n2 and n1>=n3: print(" n1 is greatest"); if n2>=n1 and n2>=n3: print(" n2 is greatest"); if n3>=n1 and n3>=n2: print("n3 is greatest"); Output: please give first number n1: 5 please give second number n2: 33 please give third number n3: 1 n2 is greatest
  • 124. Python program to find smallest number among three a = int(input("Enter the value for a :")) b = int(input("Enter the value for b :")) c = int(input("Enter the value for c :")) #comparing integer ‘a’ with other two integer if a<=b and a<=c: print("a is smallest") #comparing integer ‘b’ with other two integer elif b<=a and b<=c: print("b is smallest") #comparing integer ‘c’ with other two integer elif c<=a and c<=b: print("c is smallest") Output: Enter the value for a :6 Enter the value for b :8 Enter the value for c :0 c is smallest
  • 125. Python program to reverse a number Method 1: Reverse Using While Loop in Python: Program: n = int(input("Please give a number: ")) print("Before reverse your number is : %d" %n) reverse = 0 while n!=0: reverse = reverse*10 + n%10 n = (n//10) print("After reverse : %d" %reverse) Output: please give a number : 12345 before reverse your number is : 12345 After reverse : 54321
  • 126. Method 2: Reverse Using String Slicing in Python Program: num = int(input("Please give a number: ")) print("Before reverse your number is : %d" %num) rev = int(str(num)[::-1]) print("After reverse the number:", rev) Output: Please give a number: 12345 Before reverse your number is : 12345 After reverse the number: 54321
  • 127. Python program to check number representation is in binary num = int(input("please give a number : ")) while(num>0): j=num%10 if j!=0 and j!=1: print("num is not binary") break num=num//10 if num==0: print("num is binary") Output: please give a number : 5 num is not binary
  • 128. Armstrong number program in python Method 1: Check Armstrong Using a While Loop # Armstrong number program using while loop num = int(input("Please give a number: ")) sum = 0 temp = num # count the number of digits in input count = len(str(num)) # loop on each digit and calculate the sum while temp > 0: digit = temp % 10 sum += digit ** count temp //= 10 # check if the number is an Armstrong or not if num == sum: print("Given ",num, "is an Armstrong number") else: print("Given ",num, "is not an Armstrong number") Output: Please give a number: 153 Given 153 is an Armstrong number
  • 129. Method 2: Armstrong Using List Comprehension: # Armstrong number using list comprehension num = int(input("Please Enter a Number: ")) digits = [int(digit) for digit in str(num)] count = len(digits) sum = sum([digit ** count for digit in digits]) if num == sum: print("Given ", num, "is an Armstrong number") else: print("Given ", num, "is not an Armstrong number") Output: Please Enter a Number: 371 Given 371 is an Armstrong number
  • 130. Prime Number Program in Python Program: n = int(input("please give a number : ")) i,temp=0,0 for i in range(2,n//2): if n%i == 0: temp=1 break if temp == 1: print("given number is not prime") else: print("given number is prime") Output: please give a number : 23 given number is prime
  • 131. Fibonacci series program in python using iterative method Program: n = int(input("please give a number for fibonacci series : ")) first,second=0,1 print("fibonacci series are : ") for i in range(0,n): if i<=1: result=i else: result = first + second; first = second; second = result; print(result)
  • 132. Output: please give a number for fibonacci series : 5 fibonacci series are : 0 1 1 2 3
  • 133. Python program for palindrome using an iterative method n = int(input("please give a number : ")) reverse,temp = 0,n while temp!=0: reverse = reverse*10 + temp%10; temp=temp//10; if reverse==n: print("number is palindrom") else: print("number is not palindrom") Output: please give a number : 9889 number is palindrom
  • 134. Python program for palindrome number using recursive method n = int(input("please give a number : ")) def reverse(num): if num<10: return num else: return int(str(num%10) + str(reverse(num//10))) def isPalindrome(num): if num == reverse(num): return 1 return 0 if isPalindrome(n) == 1: print("Given number is a palindrome") else: print("Given number is a not palindrome")
  • 135. • Output: please give a number : 7887 Given number is a palindrome
  • 136. Swap two variables without using the third variable in Python a = int(input("please give first number a: ")) b = int(input("please give second number b: ")) a=a-b b=a+b a=b-a print("After swapping") print("value of a is : ", a); print("value of b is : ", b);
  • 137. • Output: please give first number a: 6 please give second number b: 3 After swapping value of a is : 3 value of b is : 6
  • 138. Python Program to swap two number using third variable a = int(input("please give first number a: ")) b = int(input("please give second number b: ")) tempvar=a a=b b=tempvar print("After swapping") print("value of a is : ", a); print("value of b is : ", b);
  • 139. Output: please give first number a: 5 please give second number b: 7 After swapping value of a is : 7 value of b is : 5
  • 140. Python Program to find Prime factors of given integer def prime_factors(n): i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors num = int(input("Please enter a number: ")) print("Prime factors of", num, "are:", prime_factors(num))
  • 141. Output: Enter a number: 24 Prime factors of 24 are: [2, 2, 2, 3]
  • 142. Add two number without + Operator in Python def add_numbers(x, y): while y != 0: temp = x & y x = x ^ y y = temp << 1 return x num1 = 10 num2 = 15 sum_result = add_numbers(num1, num2) print(f"Sum of {num1} and {num2} is: {sum_result}") Output: Sum of 10 and 15 is: 25
  • 143. Perfect number program in Python num = int(input("please give a number: ")) sum=0 for i in range(1,(num//2)+1): remainder = num % i if remainder == 0: sum = sum + i if sum == num: print("given input is perfect number") else: print("given input is not a perfect number")
  • 144. Output1: please give a number: 65 given input is not a perfect number Output2: please give a number: 6 given input is perfect number
  • 145. Python code to find the average of numbers size=int(input("Enter the number of elements you want in array: ")) arr=[] #taking input of the list for i in range(0,size): elem=int(input("Please give value for index "+str(i)+": ")) arr.append(elem) #taking average of the elements of the list avg=sum(arr)/size print("Average of the array elements is ",avg)
  • 146. Output: Enter the number of elements you want in array: 4 Please give value for index 0: 3 Please give value for index 1: 4 Please give value for index 2: 5 Please give value for index 3: 6 Average of the array elements is 4.5
  • 147. Python program to calculate the factorial using iterative approach #taking an integer input from user num=int(input("Enter the whole number to find the factorial: ")) factorial = 1 if num < 0: print("Factorial can't be calculated for negative number") elif num == 0: print("Factorial of 0 is 1") else: #calculating the factorial of the input number for i in range(1,num + 1): factorial = factorial*i print("Factorial of",num,"is",factorial) Output: Enter the whole number to find the factorial: 5 Factorial of 5 is 120
  • 148. Factorial Program in python using recursion with explanation def fact(n): if n == 1: return n else: #recursion return n*fact(n-1) num = int(input("Enter a whole number to find Factorial: ")) if num < 0: print("Factorial can't be calculated for negative number") elif num == 0: print("Factorial of 0 is 1") else: print("Factorial of",num,"is",fact(num)) Output: Enter a whole number to find Factorial: 5 Factorial of 5 is 120
  • 149. Python Program to Print Prime Number in given range lower_value = int(input ("Please, Enter the Lowest Range Value: ")) upper_value = int(input ("Please, Enter the Upper Range Value: ")) print ("The Prime Numbers in the range are: ") for number in range (lower_value, upper_value + 1): if number > 1: for i in range (2, number): if (number % i) == 0: break else: print (number)
  • 150. Please, Enter the Lowest Range Value: 14 Please, Enter the Upper Range Value: 97 The Prime Numbers in the range are: 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
  • 151. Python program to calculate the power using ‘pow()’ method base = int(input("Enter the value for base :")) exponent = int(input("Enter the value for exponent:")) print(base,"to power ",exponent,"=",end = ' ') print(pow(base,exponent)) output: Enter the value for base :5 Enter the value for exponent :4 5 to power 4 = 625
  • 152. Python program to calculate the power using ‘for-loop’ #taking 3 integer as input from the user base = int(input("Enter the value for base :")) exponent = int(input("Enter the value for exponent :")) result=1; print(base,"to power ",exponent,"=",end = ' ') #using ‘for’ loop with ‘range’ function for exponent in range(exponent, 0, -1): result *= base print(result) Output: Enter the value for base :5 Enter the value for exponent :4 5 to power 4 = 625
  • 153. Python program to calculate the power using ‘while-loop’ base = int(input("Enter the value for base :")) exponent = int(input("Enter the value for exponent :")) result=1; print(base,"to power ",exponent,"=",end = ' ') #using while loop with a condition that come out of while loop if exponent is 0 while exponent != 0: result = base * result exponent-=1 print(result) Output: Enter the value for base :5 Enter the value for exponent :4 5 to power 4 = 625
  • 154. Python program to calculate the square root of a number #check if the input number is negative if num<0: print("Negative numbers can't have square roots") else: print("square roots = ",math.sqrt(num)) output: Enter a number to find square root : 9 square roots = 3.0
  • 155. Python Program to find l.c.m. of two numbers num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if num1 > num2: greater = num1 else: greater = num2 while(True): if((greater % num1 == 0) and (greater % num2 == 0)): lcm = greater break greater += 1 print("LCM of",num1,"and",num2,"=",greater) output: Enter first number: 6 Enter second number: 4 LCM of 6 and 4 = 12
  • 156. Python code to find h.c.f. of two numbers #taking two inputs from the user num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) #checking for smaller number if num1 > num2: minimum = num2 else: minimum = num1 #finding highest factor of the numbers for i in range(1, minimum+1): if((num1 % i == 0) and (num2 % i == 0)): hcf = i print("hcf/gcd of",num1,"and",num2,"=",hcf) output: Enter first number: 8 Enter second number: 2 hcf/gcd of 8 and 2 = 2
  • 157. Python code to find h.c.f. of two numbers using recursion def gcd(num1,num2): if num2 == 0: return num1; return gcd(num2, num1 % num2) #taking inputs from the user num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) print("hcf/gcd of",num1,"and",num2,"=",gcd(num1,num2)) output: Enter first number: 8 Enter second number: 2 hcf/gcd of 8 and 2 = 2
  • 158. Convert Decimal to Binary Using Loop decimal = temp = int(input("Please Enter a decimal number: ")) binary = "" while temp > 0: remainder = temp % 2 binary = str(remainder) + binary temp = temp // 2 print("Binary number is ", binary, " for ", decimal) Output: Please Enter a decimal number: 13 Binary number is 1101 for 13
  • 159. Decimal to Binary Using bin() function in Python decimal = int(input("Please Enter a decimal number: ")) binary = bin(decimal) print("Binary number is ", binary[2:], " for ", decimal) Output: Please Enter a decimal number: 34 Binary number is 100010 for 34
  • 160. Python Program to convert Decimal to Octal number def decimal_to_octal(decimal): if decimal == 0: return "" quotient = decimal // 8 remainder = decimal % 8 return decimal_to_octal(quotient) + str(remainder) decimal = int(input("Please Enter a decimal number: ")) octal = decimal_to_octal(decimal) print("Octal number is ", octal, " for ", decimal) Output: Please Enter a decimal number: 157 Octal number is 235 for 157
  • 161. Leap Year Program in Python year = int(input("Please Enter a year: ")) if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print(year, "is a leap year") else: print(year, "is not a leap year") else: print(year, "is a leap year") else: print(year, "is not a leap year") Output: Enter a year: 2000 2000 is a leap year
  • 162. Convert Celsius to Fahrenheit in Python # program to convert Celsius to Fahrenheit celsius = float(input("Enter temperature in Celsius: ")) fahrenheit = (celsius * 1.8) + 32 print("Temperature in Fahrenheit: ", fahrenheit) Output: Enter temperature in Celsius: 30 Temperature in Fahrenheit: 86.0
  • 163. Python program to convert Fahrenheit into Celsius #taking input from the user fahrenheit = float(input("Please give the Hahrenheit Temperature : ")) #converting Celsius into Fahrenheit celsius = ((fahrenheit-32)*5)/9 print("Celcius= ",celsius) output: Please give the Hahrenheit Temperature : 19.6 Celcius= -6.888888888888888
  • 164. Python program to calculate simple interest #taking the values of principal, rate of interest and time from the user principal = int(input("Enter the principal amount: ")) rate = int(input("Enter the rate of interest: ")) time = int(input("Enter the time of interest in year: ")) #using the input values calculate simple interest simpleInterest = (principal*rate*time)/100 print("Simple Interest = ",simpleInterest) output: Enter the principal amount: 100 Enter the rate of interest: 5 Enter the time of interest in year: 5 Simple Interest = 25.0