Python Notes -Unit -1
Python Notes -Unit -1
Python is a programming language that lets you work quickly and integrate systems more
efficiently.
• On 16 October 2000, Python 2.0 was released with many new features.
• On 3rd December 2008, Python 3.0 was released with more testing and includes new,
There are many interpreters available freely to run Python scripts like IDLE (Integrated
Development Environment) which is installed when you install the python software from
http://python.org/downloads/
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.
The following are the primary factors to use python in day-to-day life:
4. It’s Powerful
Dynamic typing
Library utilities
5. It’s Portable
As long as you have a compaitable python interpreter installed, python programs will run
in exactly the same manner, irrespective of platform.
No intermediate compile
Python Programs are compiled automatically to an intermediate form called byte code,
which the interpreter then reads.
This gives python the development speed of an interpreter without the performance loss
inherent in purely interpreted languages.
7. Interpreted Language
Users can interact with the python interpreter directly for writing the programs
3
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
The formation of python syntax is simple and straight forward which also makes it popular.
It is extremely easy to learn and code in Python and the indentation used instead of curly braces in
Python makes it very easy to read Python code.
2. Interpreted Language
Python is a dynamically typed language. In other words, in Python, we do not need to declare the
data types of the variables which we define. It is the job of the Python interpreter to determine the
data types of the variables at runtime based on the types of the parts of the expression. Though it
makes coding easier for programmers, this property might create runtime errors.
4
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
Python is an open-source programming language and one can download it for free from Python’s
official website. The community of Python users is constantly contributing to the code of Python in
order to improve it.
One of the very important features because of which Python is so famous in today’s times is the
huge standard library it offers to its users. The standard library of Python is extremely large with a
diverse set of packages and modules like itertools, functools, operator, and many more with
common and important functionalities in them
6. High-Level Language
Unlike C, Python is a high-level language. We can easily understand Python and it is closer to the
user than middle-level languages like C. In Python, we do not need to remember system
architecture or manage the memory.
5
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
However, the most important fact is that the Object-Oriented approach of Python allows its users to
implement the concepts of Encapsulation, Inheritance, Polymorphism, etc. which is extremely
important for the coding done in most Software Industries as objects map to entities in real-world
and lot of real-world problems can be solved using the Object-Oriented Approach.
With one of the biggest communities on StackOverflow and Meetup, Python has gained popularity
over the years. If we need any kind of help related to Python, the huge community is always there
to answer our queries. A lot of questions about Python have already been answered on these sites
and Python users can reference them as per requirement.
9. Platform Independent
Platform independence is yet another amazing feature of Python. In other words, it means that if we
write a program in Python, it can run on a variety of platforms, for instance, Windows, Mac, Linux,
etc. We do not have to write separate Python code for different platforms.
Yet another interesting feature of Python is the fact that we can use it to create GUI (Graphical User
Interfaces). We can use Tkinter, PyQt, wxPython, or Pyside for doing the same. Python also
features a large number of GUI frameworks available for it and various other cross-platform
solutions. Python binds to platform-specific technologies.
6
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
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.
7
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
The programming cycle for Python is a stage-by-stage method for developing systematic software.
Problem description is the first step in the development process, during which developers define the
project’s needs, limitations, and goals. Their algorithm, data structures, and technological requirements
are needed to address the challenge. They are created in depth at the planning stage by developers.
The Python programming cycle can assist developers in producing high-quality, dependable, and
different industries. The programming cycle has shown to be successful in producing reliable software
solutions. In short:
1. The programming cycle for Python is far shorter than the cycle for conventional programming.
3. During runtime, Python programs only load modules and use the objects. they do have. As a result,
4. It is even possible to change and reload portions of a current application. It is possible without
halting it altogether in situations where you can use dynamic module reloading.
8
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
Python is a lot easier to code and learn. Python programs can be written on any plain text editor like
notepad, notepad++, or anything of that sort.
We can also use an online IDE for writing Python codes or can even install one on their system to make
it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor,
debugger, compiler, etc.
To begin with, writing Python Codes and performing various intriguing and useful operations, one must
have Python installed on their System.
Python IDE:
9
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
An editor designed to handle code (with, for example, syntax highlighting and auto-
completion)
Build, execution, and debugging tools
Some form of source control
Most IDEs support many different programming languages and contain many more features. They
can, therefore, be large and take time to download and install. You may also need advanced
knowledge to use them properly
Sublime Text
Category: Code Editor
Website: http://www.sublimetext.com
Vi / Vim
Category: Code Editor
Website: https://www.vim.org/
PyCharm
Category: IDE
Website: https://www.jetbrains.com/pycharm/
Spyder
Category: IDE
Website: https://www.spyder-ide.org/
10
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
Thonny
Category: IDE
Website: http://thonny.org/
Installation on Windows
Visit the link https://www.python.org to download the latest release of Python. In this process, we
will install Python 3.11.3 on our Windows operating system. When we click on the above link, it
will bring us the following page.
To verify whether the python is installed or not in our system, we have to do the following.
o Go to "Start" button, and search " cmd ".
o Then type, " python - - version ".
o If python is successfully installed, then we can see the version of the python installed.
o If not installed, then it will print the error as " 'python' is not recognized as an internal or
external command, operable program or batch file. "
Python is an interpreted language, which means the source code of a Python program is
converted into bytecode that is then executed by the Python virtual machine. Python is
different from major compiled languages, such as C and C + +, as Python code is not
required to be built and linked like code for these languages.
12
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
Python Interpreter is a program that reads and executes Python code. It uses 2 modes of Execution.
1. Interactive mode
2. Script mode
1. Interactive mode:
Advantages:
Working in interactive mode is convenient for beginners and for testing small pieces of code.
2. Script Mode
Working with the interactive mode is better when Python programmers deal with small pieces of
code as you can type and execute them immediately, but when the code is more than 2-4 lines,
using the script for coding can help to modify and use the code in future.
In script mode, we type python program in a file and then use interpreter to execute the
content of the file.
Scripts can be saved to disk for future use. Python scripts have the extension .py, meaning
that the filename ends with .py
13
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
Advantages:
It's is very suitable for long program....type all the command once and show your output at
once.
Here we got the advantage to save our python script which is helpful for us because no
longer our python script get lost we can make changes whenever required.
Disadvantages:
1. Can be tedious when you need to run only a single or a few lines of cod.
2. You must create and save a file before executing your code.
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only, the indentation in
Python is very important.
if 5 > 2:
print("Five is greater than two!")
Python Comments
Creating a Comment
14
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
#This is a comment
print("Hello, World!")
A comment does not have to be text that explains the code, it can also be used to prevent Python from
executing code:
#print("Hello, World!")
print("Cheers, Mate!")
Multiline Comments
Python does not really have a syntax for multiline comments.
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string
(triple quotes) in your code, and place your comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Python Keywords:
Keywords are predefined, reserved words used in Python programming that have special meanings
to the compiler.
15
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
We cannot use a keyword as a variable name, function name, or any other identifier. They are
used to define the syntax and structure of the Python language.
All the keywords except True, False and None are in lowercase and they must be written as they
are. The list of all the keywords is given below.
16
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
Python Variables:
Python variables are the reserved memory locations used to store values with in a Python P rogram.
This means that when we create a variable we reserve some space in the memory. Based on the data
type of a variable, Python interpreter allocates memory.
Identifier Naming:
Identifiers are the name given to variables, classes, methods, etc. Variables are the example of
identifiers. An Identifier is used to identify the literals used in the program.
17
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
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.
Since everything is an object in Python programming, data types are actually classes and variables
are instances (object) of these classes.
Python has the following data types built-in by default, in these categories:
18
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
To define the values of various data types and check their data types we use the type()
function. Consider the following examples.
19
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an integer
value can be.
Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed
by a positive or negative integer may be appended to specify scientific notation.
Example:
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Python String
Python List
Python Tuple
20
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
Strings in Python are arrays of bytes representing Unicode characters. A string is a collection of one
or more characters put in a single quote, double-quote, or triple-quote.
In python there is no character data type, a character is a string of length one. It is represented by str
class.
Python strings are immutable which means when we perform an operation on strings, we always
produce a new string object of the same type, rather than mutating an existing string.
<class 'str'>
Python List:
Lists are just like arrays, declared in other languages which are an ordered collection of data. It is
very flexible as the items in a list do not need to be of the same type.
Lists in Python can be created by just placing the sequence inside the square brackets[].
A list in Python is an object of list class. We can check it with type() function.
<class 'list'>
As mentioned, an item in the list may be of any data type. It means that a list object can also be an
item in another list. In that case, it becomes a nested list.
21
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
In Python, a tuple is an object of tuple class. We can check it with the type() function.
<class 'tuple'>
As in case of a list, an item in the tuple may also be a list, a tuple itself or an object of any other
Python class.
To form a tuple, use of parentheses is optional. Data items separated by comma without any
enclosing symbols are treated as a tuple by default.
A dictionary in Python is an unordered collection of data values, used to store data values like a
map, unlike other Data Types that hold only a single value as an element, a Dictionary holds a key:
value pair. Key-value is provided in the dictionary to make it more optimized.
Each key-value pair in a Dictionary is separated by a colon : , whereas each key is separated by a
‘comma’.
Create a Dictionary
22
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces,
separated by ‘comma’. Values in a dictionary can be of any data type and can be duplicated,
whereas keys can’t be repeated and must be immutable.
The dictionary can also be created by the built-in function dict(). An empty dictionary can be
created by just placing it in curly braces{}.
In Python, dictionary is an object of the built-in dict class. We can check it with the type() function.
<class 'dict'>
In Python, a Set is an unordered collection of data types that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of various
elements.
Sets can be created by using the built-in set() function with an iterable object or a sequence by
placing the sequence inside curly braces, separated by a ‘comma’. The type of elements in a set
need not be the same, various mixed-up data type values can also be passed to the set.
Python Set is an object of built-in set class, as can be checked with the type() function.
A set can store only immutable objects such as number (int, float, complex or bool), string or
tuple. If you try to put a list or a dictionary in the set collection, Python raises a TypeError
23
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
Python boolean type is one of built-in data types which represents one of the two values
either True or False. Python bool() function allows us to evaluate the value of any expression and
returns either True or False based on the expression.
a = True
print(a)
print(type(a))
Output:
true
<class 'bool'>
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operator
5. Assignment Operators
6. Membership Operators
7. Identity Operators
Arithmetic Operators:
24
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
These operators are used to perform operations such as addition, subtraction, multiplication,
division and modulo division. For example, x=7, and y=3.
These operators are used to compare value. The operators can either return True or False
according to the condition. The table with following values for x=7 and y=3
25
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
26
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
Bitwise Operators
Bitwise operators act on operands as if they were string of binary digits. The operators operate
bit by bit. For example, x=2 (binary value is 10) and y=7 (Binary value is 111). The binary
equivalent of the decimal values of x and y will be 10 and 111 respectively.
Logical Operator:
27
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
There are three logical operators: and, or, and not. The semantics (meaning) of these
operators is similar to their meaning in English. For example, x > 0 and x < 10 is true only if x is
greater than 0 and less than 10. n % 2 == 0 or n % 3 == 0 is true if either (or both) of the
conditions is true, that is, if the number is divisible by 2 or 3. Finally, the not operator negates a
boolean expression, so not(x > y) is true if (x > y) is false, that is, if x is less than or equal to y.
28
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
Assignment Operator
Assignment operator is used to assign values to the variable. For example, x=5 is simple
assignment operator, that assigns value 5 to the to the variable x.
There are various compound operators in python like a+=5, which adds value 5 to the variable
and later assigns it to variable
a. This expressions is equivalent to a=a+5.
b. The same assignment operator can be applied to all expressions that contain arithmetic
operators such as, *=, /=, -=, **=,%= etc.
x=4
x+=5
>>> x
print “The value of x is:”, x
>>> The value of x 9
Membership Operators
These operators are used to test whether a value or operand is there in the sequence such as list,
string, set, or dictionary. There are two membership operators in python: in and not in. In the
29
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering
dictionary we can use to find the presence of the key, not the value.
Example Program:
30
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Identity Operators
These are used to check if two values (variable) are located on the same part of the memory. If the x is a
variable contain some value, it is assigned to variable y. Now both variables are pointing (referring) to
the same location on the memory as shown in the example program.
Example Program:
31
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Python provides numerous built-in functions that are readily available to us at the Python prompt.
Some of the functions like input() and print() are widely used for standard input and output operations
respectively
We use the print() function to output data to the standard output device (screen).
The simplest way to produce output is using the print() function where we can pass zero or more
expressions separated by commas.
This function converts the expressions we pass into a string before writing to the screen.
Ex:
a=5
Output
The value of a is 5
Parameters:
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : Optional) Specify how to separate the objects, if there is more than one.Default :’
‘end=’end’ : (Optional) Specify what to print at the end. Default : ‘\n’
file : (Optional) An object with a write method. Default : sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered
(False).Default: False
32
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Example:
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
Output
1234
1*2*3*4
1#2#3#4&
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by using
the str.format() method. This method is visible to any string object.
>>> x = 5; y = 10
Here, the curly braces {} are used as placeholders. We can specify the order in which they are printed
by using numbers (tuple index).
Output
'John'))
We can also format strings like the old sprintf() style used in C programming language . We use
the % operator to accomplish this.
>>> x = 12.3456789
Python Input:
To allow flexibility, we might want to take the input from the user. In Python, we have
the input() function to allow this. The syntax for input() is:
input([prompt])
Enter a number: 10
>>> num
'10'
Here, we can see that the entered value 10 is a string, not a number. To convert this into a number we can
use int() or float() functions.
34
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
>>> int('10')
10
>>> float('10')
10.0
When input() function executes program flow will be stopped until the user has given an input.
The text or message display on the output screen to ask a user to enter input value is optional i.e. the
prompt, will be printed on the screen is optional.
Whatever you enter as input, input function convert it into a string. if you enter an integer value
still input() function convert it into a string. You need to explicitly convert it into an integer in your code
using typecasting.
Typecasting Example:
num1 = int(input())
num2 = int(input())
print(num1 + num2)
In C++/C we can take multiple inputs in one line using scanf but in Python we can take multiple values or
inputs in one line by two methods.
35
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
This function helps in getting a multiple inputs from user . It breaks the given input by the specified
separator. If separator is not provided then any white space is a separator. Generally, user use
a split() method to split a Python string but one can used it in taking multiple input.
Syntax :
input().split(separator, maxsplit)
Example :
5. Taking multiple inputs at a time and type casting using list() function
Output:
36
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
List comprehension is an elegant way to define and create list in Python. We can create lists just like
mathematical statements in one line only. It is also used in getting multiple inputs from a user.
print()
print()
37
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
print()
Output:
Note : The above examples take input separated by spaces. In case we wish to take input separated by
comma (, ), we can use following:
38