PP Unit I Notes Dbatu-1
PP Unit I Notes Dbatu-1
PP Unit I Notes Dbatu-1
1.1 Introduction
Python is a general purpose high level programming language.
Python is a general purpose, dynamic, high level, and interpreted programming language.
Python is a simple, general purpose, high level, and object-oriented programming language.
Python is recommended as first programming language for beginners.
Python is open source software.
On October 2020, Python 3.9 was released with new features like Dictionary Merge &
Update Operators, New remove prefix() and remove suffix() string methods, Built-in
Generic types etc.
Python 3.10 - October 2021, Python 3.11 - October 2022, Python 3.12 - October 2023.
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:
o ABC language.
o Modula-3
1
1.3 Need of Python Programming (Features of Python Programming)
Following are the major features and applications of Python that has influenced more and more
people to learn Python and gain certification.
1. Data Science: Python is the preferred programming language of most data scientists.
2. Easy to Learn: Python is an easy language to master.
3. Cross-Platform and Open Source: It’s been more than 20 years since this language has
been running cross-platform and open source. Be it Linux, Windows or MacOS, Python code
works on every platform.
4. Versatile Language and Platform: Python remains very relevant today as it can be used in
any operations scenario or software development, be it in managing local and cloud
infrastructure.
5. Vast Libraries: Python is supported by PyPI which has 85,000+ python scripts and
modules accessible to the user.
6. Flexibility: Python has several powerful applications integrated with other programming
languages.
7. High Salary: The salary of Python engineers is comparatively higher as compared to others
in the industry.
8. Scripting and Automation: What most people don’t know about Python is that it can be
used as a scripting language.
9. Artificial Intelligence: Without any dispute, Artificial intelligence is going to lead the
future IT. Python’s libraries such as Keras and TensorFlow enable machine learning
functionality.
10. Computer Graphics: Python can be employed in small, large, online or offline projects. It
is used to develop GUI and desktop applications.
11. Testing Framework: This language is an excellent tool for validating the products or ideas
for established enterprises. Python has numerous built-in testing frameworks that deal with
debugging and rapid workflows.
12. Web Development: Python’s different frameworks support website development. Python
has an array of frameworks for developing websites. Popular frameworks such as Django,
Flask, and Pylons are characterized by faster and stable code; this is because they are written in
Python.
2
1.4 Installation of Python
Installing Python on Windows takes a series of few easy steps.
On clicking download, various available executable installers shall be visible with different
operating system specifications. Choose the installer which suits your system operating system
and download the installer. Let suppose, we select the Windows installer (64 bits).
The download size is less than 30MB.
3
Step 3 − Run Executable Installer
We downloaded the Python 3.9.1 Windows 64 bit installer.
Run the installer. Make sure to select both the checkboxes at the bottom and then click Install
Now.
The installation process will take few minutes to complete and once the installation is successful,
the following screen is displayed.
4
Step 4 − Verify Python is installed on Windows
To ensure if Python is successfully installed on your system. Follow the given steps −
Open the command prompt.
Type ‘python’ and press enter.
The version of the python which you have installed will be displayed if the python is
successfully installed on your windows.
Python’s REPL (Read-Eval-Print Loop) or shell is a command-line interface that allows users to
interact with the Python interpreter in real-time. The REPL is a powerful tool that allows
programmers to write, test, and debug Python code on the fly, without the need for a full-fledged
integrated development environment (IDE). Here are some common applications of Python’s
REPL:
1. Testing Code Snippets: The Python REPL is a great tool for testing small code snippets
or for quickly prototyping an idea. Programmers can write a few lines of code in the shell
and see the output immediately, without having to save and run the code in a separate
file. This makes it easy to experiment with new ideas and test out different approaches to
a problem.
2. Debugging Code: The Python REPL can be used for interactive debugging of Python
code. Programmers can step through their code line by line and examine variables and
objects at each step. This allows them to identify bugs and other issues in their code and
fix them on the fly.
3. Data Analysis: The Python REPL can be used for interactive data analysis and
exploration. Python has several libraries for data analysis, such as Pandas and NumPy,
which allow programmers to manipulate and analyze data in real-time. The REPL can be
used to explore data sets and test out different data analysis techniques.
4. Learning Python: The Python REPL is a great tool for learning Python, especially for
beginners. It allows users to experiment with Python code and see the results
immediately, which can help them understand the language’s syntax and semantics
better. Additionally, the REPL provides feedback on syntax errors and other issues,
which can help beginners, learn faster and avoid common mistakes.
5. Scripting: The Python REPL can be used for scripting, allowing users to write short
scripts and run them in the shell. This is useful for automating repetitive tasks or for
performing quick calculations.
Python’s REPL (Read-Eval-Print Loop) or shell is a powerful tool that allows programmers to
interact with the Python interpreter in real-time. Its versatility makes it useful for a wide range of
applications, from testing code snippets to interactive data analysis and exploration.
Additionally, it is a great tool for learning Python and for scripting simple tasks.
6
1.6 Running Python Scripts
Python programmers must know every possible way to run the Python scripts or code. This is the
only way to verify whether code is working as we want.
Python interpreter is responsible for executing the Python scripts. Python interpreter is a piece of
software which works between the Python program and computer hardware.
The series of ways to run Python scripts
The operating system command-line or terminal.
The Python interactive mode.
The IDE or Text editor
The file manager of system.
Write the Python print statement and save it as sample.py in working directory. Now, run this
file using the command-line.
7
The Python interactive mode
To run the Python code, use the Python interactive session. Need to start Python interactive
session, just open a command-line or terminal in start menu, then type in python, and press enter
key.
Here is the example of how to run Python code using interactive shell.
It allows us to check every piece of code, and this facility makes it an awesome development
tool. But once close the session it will lose all code that has written.
Below are the few options to exit the interactive mode.
o Type built-in functions quit() or exit(). Or
o Type the enter ctrl+ Z key combination to end the current session of Python interactive
shell.
8
The IDE or Text Editor
The IDE stands for Integrated Development Environment. There are various IDEs
but Pycharm is Python's most popular and useful text editor among them. It is recommended for
developing large and more complex applications. Here are using the Pycharm to run python
script.
Create a new project and then create a new Python file using the .py extension.
Now, click on the green button and it will show the output as follows.
9
1.7 Variables in Python
Python variables are the reserved memory locations used to store values with in a Python
Program.
Variables are containers for storing data values.
Variable acts as an address for where the data is stored in memory.
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example
x=5
y = "John"
print(x)
print(y)
5
John
Variables do not need to be declared with any particular type, and can even change type
after they have been set.
Example
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Sally
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
print(x)
print(y)
print(z)
3
3
3.0
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
Rules for Python variables
A Python variable name must start with a letter or the underscore character.
A Python variable name cannot start with a number.
A Python variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ ).
10
Variable in Python names are case-sensitive (name, Name, and NAME are three different
variables).
The reserved words (keywords) in Python cannot be used to name the variable in Python.
Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
One Value to Multiple Variables: Assign the same value to multiple variables in one line
Example
x = y = "Orange"
print(x)
print(y)
Orange
Orange
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the
values into variables. This is called unpacking.
Example: Unpack a list
fruits = ["apple", "banana"]
x, y = fruits
print(x)
print(y)
apple
banana
11
Output Variables
The Python print() function is often used to output variables.
Example
x = "Python is awesome"
print(x)
Python is awesome
In the print() function, you output multiple variables, separated by a comma:
Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Python is awesome
You can also use the + operator to output multiple variables:
Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Python is awesome
Global Variables
Variables that are created outside of a function are known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
Example
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Python is awesome
Example
Create a variable inside a function, with the same name as the global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
Python is fantastic
Python is awesome
12
1.8 Assignment Operators
Following are the different types of assignment operators in Python:
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
13
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
14
1.9 List of Keywords in Python (35 Keywords)
Represents an
It is a Logical expression that It is a non-local
and False nonlocal
Operator will result in not variable
being true.
It is used to
It is used with It is a Logical
as create an alias finally not
exceptions Operator
name
pass is used
To import when the user
break Break out a Loop from specific parts of a pass doesn’t
module want any code
to execute
Represents an
It is used to
It is used to expression that
def define the import True
import a module will result in
Function
true.
It is used to test
It is used to Try is used to
del is if two variables try
delete an object handle errors
are equal
15
Keyword Description Keyword Description Keyword Description
with statement
It is used in a Used to create an
is used in
else conditional lambda anonymous with
exception
statement function
handling
yield keyword
try-except is
It represents a is used to create
except used to handle None yield
null value a generator
these errors
function
pause execution
Manage multiple
await until the awaited async
tasks at once
task completes
Syntax
input(prompt)
print() – print() function is used to display result on the screen (output function Syntax)
Example
x = input('Enter your name:')
print('Hello, ' + x)
Output
Enter your name: King
Hello, King
16
1.11 Indentation in Python
Python indentation refers to adding white space before a statement to a particular block of
code.
In another word, all the statements with the same space to the right belong to the same code
block.
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
The number of spaces is up to you as a programmer, but it has to be at least one.
Example
# Python program showing
# indentation
site = 'gfg'
if site == 'gfg':
print('Logging on to geeksforgeeks...')
else:
print('retype the URL.')
print('All set !')
Output
Logging on to geeksforgeeks...
All set !
17
1.12 Differences between C, C++, Java and Python
Multiple Allow for both Java provides partial Provides both single as well
inheritance is not single as well as multiple inheritance as multiple inheritance
supported in C. multiple inheritance
options.
A small number Has a small number Many concepts, such It comes with a large
of libraries of library patrons as UI, are supported library set that allows it to
available. by the library. be used for AI, data
science, and other
applications.
Outside of the Outside of the class, Every line of code is Functions and variables can
class, variables variables and contained within a be declared global.
and functions are functions are class.
utilized. utilized.
Have a similar C++ is a computer The Java Program Execution is delayed due to
speed as C++ language that Compiler is a little the employment of an
compiles quickly. slower than the C++ interpreter.
Compiler.
Syntax rules are Syntax rules are Syntax rules are It isn't necessary to use
strictly followed. strictly followed. strictly followed. semicolon ' ;'.
18
Difference between Python, Java and C Program with Example
print("Hello World")
Output
Hello World
import java.io.*;
class GFG {
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
Output
Hello World
#include <stdio.h>
int main()
{
printf("Hello World");
return 0;
}
Output
Hello World
19
Unit I Questions
20