Python Unit1
Python Unit1
Python is easy to learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.
Python is not intended to work in a particular area, such as web programming. That is
why it is known as 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 the development and debugging fast because there is no compilation step
included in Python development, and edit-test-debug cycle is very fast.
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.
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
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.
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.
Python Applications
[Link]
compiler. In a compiled language, a compiler will translate the source code directly into
binary machine code. This machine code is specific to that target machine since each
In an interpreted language, the source code is not directly run by the target machine.
There is another program called the interpreter that reads and executes the source code
directly. The interpreter, which is specific to the target machine, translates each
statement of the source code into machine code and runs it.
interpreting. When we execute a source code (a file with a .py extension), Python first
representation of your source code, however, it is not the binary machine code and
cannot be run by the target machine directly. In fact, it is a set of instructions for a
After compilation, the bytecode is sent for execution to the PVM. The PVM is an
interpreter that runs the bytecode and is part of the Python system. The bytecode is
programming language. CPython compiles the python source code into the bytecode,
Flavors of Python
Types of Python compilers are referred as flavors of Python. They help to integrate
various types of programming languages in Python some of them are:
1. CPython:
2. JPython:
3. IronPython:
It is compiler designed for .NET framework, but it is written in C#. It can run on
CLR(Common Language Run time).
4. PyPy:
It is a Python implemented by using Python language itself. It runs fast since JIT is
incorporated to PVM.
5. Ruby Python:
It acts as a bridge from Ruby to Python interpreter. It embeds the Python interpreter
inside the Ruby application
6. Pythonxy:
[Link] Python:
The name Anaconda Python is obtained after redeveloping it to handle large scale data
processing, predictive analytics and scientific computing. It handles huge amount of
data.
8. Stackless Python:
Tasklets are the small tasks that are run independently. The communication is done with
each by using channels. They schedule, control and suspend the tasklets. Hundreds of
tasklets can run by a thread. The thread and tasklets can be created in stackless python.
It is a re-implementation of python.
PVM
What is PVM in Python?
PVM is which help to execute the python programme. Interpreter, translates source code
into some efficient intermediate representation (code) and immediately executes this.
Virtual Machine, explicitly executes stored pre-compiled code built by a compiler which is
part of the interpreter system
Memory allocation can be defined as allocating a block of space in the computer memory to
a program.
In Python memory allocation and deallocation method is automatic as the Python developers
created a garbage collector for Python so that the user does not have to do manual garbage
collection.
Example
x=10
ifid(x) ==id(y):
print("x and y refer to the same object")
Output:
x and y refer to the same object
Garbage collection is a process of freeing up memory that is not in use by a specific program
at a given instance of time.
This process is helpful in memory management and minimizes the wastage of memory. The
memory freed by garbage collection can be used for storing other important data or variables
for the same program or by other programs.
Sometimes, a user may need to do garbage collection for memory management explicitly so as
to free up some memory space. So, python also allows explicit garbage collection which can
be done using the gc module. Garbage collection can be done forcibly by using
the collect() function of the gc module
java python
Java is a Compiled Language Python is an Interpreted Language
It uses curly braces to define the beginning Python uses indentation to separate code into
and end of each function and class definition. code blocks.
Java program runs slowly compared to Python programs run faster than Java.
Python.
Java Virtual Machine provides the runtime For Python, the interpreter translates source
environment to execute the code and convert code into machine-independent bytecode.
bytecode into machine language
Java is best for Desktop GUI apps, Embed Python is excellent for scientific and numeric
Systems, Web application services, etc. computing, Machine learning apps, more.
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.
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.
1. name = "Devansh"
2. age = 20
3. marks = 80.50
4.
5. print(name)
6. print(age)
7. print(marks)
Output:
Devansh
20
80.5
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. x=y=z=50
2. print(x)
3. print(y)
4. print(z)
Python Keywords
Python Keywords are special reserved words that convey a special meaning to the
compiler/interpreter. Each keyword has a special meaning and a specific operation.
These keywords can't be used as a variable. Following is the List of Python Keywords.
Data Type
A variable can hold different types of values. For example, a person's name must be
stored as a string whereas its id must be stored as an integer.
Python provides various standard data types that define the storage method on each of
them. The data types defined in Python are given below.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc.
Python has no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y
denote the real and imaginary parts, respectively. The complex numbers like
2.14j, 2.0 + 2.3j, etc.
Python creates Number objects when a number is assigned to a variable. For example;
1. a = 5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:
The type of a <class 'int'>
Sequence Type
String
The string can be defined as the sequence of characters represented in the quotation
marks. In Python, we can use single, double, or triple quotes to define a string.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
Example - 1
Example - 2
Output:
he
o
List
Python Lists are similar to arrays in C. However, the list can contain data of different
types. The items stored in the list are separated with a comma (,) and enclosed within
square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator
(+) and repetition operator (*) works with the list in the same way as they were working
with the strings.
Output:
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of
the items of different data types. The items of the tuple are separated with a comma (,)
and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of
a tuple.
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array
or a hash table where each key stores a specific value. Key can hold any primitive data
type, whereas value is an arbitrary Python object.
The items in the dictionary are separated with the comma (,) and enclosed in the curly
braces {}.
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
Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false. It denotes by the class bool. True can be
represented by any non-zero value or 'T' whereas false can be represented by the 0 or
'F'. Consider the following example.
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify
after creation), and has unique elements. In set, the order of the elements is undefined;
it may return the changed sequence of the element. The set is created by using a built-in
function set(), or a sequence of elements is passed in the curly braces and separated by
the comma. It can contain various types of values. Consider the following example.
Output:
frozenset:
A frozenset is an immutable version of a set. Once created, its elements cannot be
changed, added, or removed. This immutability makes frozenset objects hashable,
which allows them to be used as:
Dictionary Keys: frozenset instances can serve as keys in Python dictionaries,
providing a way to map values to unique, immutable collections of elements.
Elements of other Sets: frozenset instances can be elements within
other set or frozenset objects, enabling the creation of nested set structures
where the inner collections are themselves immutable.
Type conversion means changing the data type of a value. For example, converting
an integer (5) to a float (5.0) or a string ("10") to an integer (10). In Python, there are
two types of type conversion:
1. Implicit Conversion: Python changes the data type by itself while running the
code, to avoid mistakes or data loss.
2. Explicit Conversion: You change the data type on purpose using functions like
int(), float() or str().
Implicit Type Conversion
In implicit conversion, Python automatically converts one data type into another
during expression evaluation. This usually happens when a smaller data type like int
is combined with a larger one like float in an operation.
Example:
x = 10 # Integer
y = 10.6 # Float
z=x+y
print("x:", type(x))
print("y:", type(y))
print("z =", z)
print("z :", type(z))
Output
x: <class 'int'>
y: <class 'float'>
z = 20.6
z : <class 'float'>
Example:
s = "100" # String
a = int(s)
print(a)
print(type(a))
Output
100
<class 'int'>
Explanation: a = int(s), we explicitly convert it to an integer. This
manual type change is called explicit type conversion and a becomes
100 of type <class 'int'>.
Python Operators
The operator can be defined as a symbol which is responsible for a particular operation
between two operands. Operators are the pillars of a program on which the logic is built
in a specific programming language. Python provides a variety of operators, which are
described as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between two operands. It
includes + (addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor
division), and exponent (**) operators.
Comparison operator
Comparison operators are used to comparing the value of the two operands and returns
Boolean true or false accordingly. The comparison operators are described in the
following table.
Operato Description
r
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes
true.
<= If the first operand is less than or equal to the second operand, then the
condition becomes true.
>= If the first operand is greater than or equal to the second operand, then
the condition becomes true.
> If the first operand is greater than the second operand, then the
condition becomes true.
< If the first operand is less than the second operand, then the condition
becomes true.
Assignment Operators
The assignment operators are used to assign the value of the right expression to the left
operand. The assignment operators are described in the following table.
Operato Description
r
Bitwise Operators
The bitwise operators perform bit by bit operation on the values of the two operands.
Consider the following example.
For example,
if a = 7
b=6
then, binary (a) = 0111
binary (b) = 0011
Operator Description
& (binary If both the bits at the same place in two operands are 1, then 1 is
and) copied to the result. Otherwise, 0 is copied.
| (binary The resulting bit will be 0 if both the bits are zero; otherwise, the
Logical Operators
The logical operators are used primarily in the expression evaluation to make a decision.
Python supports the following logical operators.
Operato Description
r
and If both the expression are true, then the condition will be true. If a and b
are the two expressions, a → true, b → true => a and b → true.
or If one of the expressions is true, then the condition will be true. If a and
b are the two expressions, a → true, b → false => a or b → true.
not If an expression a is true, then not (a) will be false and vice versa.
Membership Operators
Python membership operators are used to check the membership of value inside a
Python data structure. If the value is present in the data structure, then the resulting
value is true otherwise it returns false.
Operato Description
r
in It is evaluated to be true if the first operand is found in the second
operand (list, tuple, or dictionary).
not in It is evaluated to be true if the first operand is not found in the second
operand (list, tuple, or dictionary).
Identity Operators
The identity operators are used to decide whether an element certain class or type.
Operato Description
r
Python Comments
Python Comment is an essential tool for the programmers. Comments are generally used
to explain the code. We can easily understand the code if it has a proper explanation. A
good programmer must use the comments because in the future anyone wants to modify
the code as well as implement the new module; then, it can be done easily.
In the other programming language such as C++, It provides the // for single-lined
comment and /*.... */ for multiple-lined comment, but Python provides the single-lined
Python comment. To apply the comment in the code we use the hash(#) at the beginning
of the statement or code.
2) Multiline comment
3) Dcostring comment
Here we have written comment over the print statement using the hash(#). It will not
affect our print statement.
We must use the hash(#) at the beginning of every line of code to apply the multiline
Python comment. Consider the following example.
Example:
Output:
The above code is very readable even the absolute beginners can under that what is
happening in each line of the code. This is the advantage of using comments in code.
We can also use the triple quotes ('''''') for multiline comment. The triple quotes are also
used to string formatting. Consider the following example.
The docstring comment is mostly used in the module, function, class or method. It is a
documentation Python string. We will explain the class/method in further tutorials.
Example:
1. """
2. This function prints Hello Joseph
3. """
4. print("Hi Joseph")
Output:
Hi Joseph
Statement Description
If The if statement is used to test a specific condition. If the condition
Statemen is true, a block of code (if-block) will be executed.
t
If - else The if-else statement is similar to if statement except the fact that, it
Statemen also provides the block of the code for the false case of the condition
t to be checked. If the condition provided in the if statement is false,
then the else statement will be executed.
The if statement
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block. The condition of if statement can be any
valid logical expression which can be either evaluated to true or false.
1. if expression:
2. statement
Example 1
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even")
Output:
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest
1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)
Output:
Output:
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by
an if statement.
Example 1
1. number = int(input("Enter the number?"))
2. if number==10:
3. print("number is equals to 10")
4. elif number==50:
5. print("number is equal to 50");
6. elif number==100:
7. print("number is equal to 100");
8. else:
9. print("number is not equal to 10, 50 or 100");
Output:
Example 2
1. marks = int(input("Enter the marks? "))
2. f marks > 85 and marks <= 100:
3. print("Congrats ! you scored grade A ...")
4. lif marks > 60 and marks <= 85:
5. print("You scored grade B + ...")
6. lif marks > 40 and marks <= 60:
7. print("You scored grade B ...")
8. lif (marks > 30 and marks <= 40):
9. print("You scored grade C ...")
10. lse:
11. print("Sorry you are fail ?")
For this purpose, The programming languages provide various types of loops which are
capable of repeating some specific code several numbers of times. Consider the following
diagram to understand the working of a loop statement.
Advantages of loops
There are the following advantages of loops in Python.
Loop Description
Statement
for loop The for loop is used in the case where we need to execute some
part of the code until the given condition is satisfied. The for loop is
also called as a per-tested loop. It is better to use for loop if the
number of iteration is known in advance.
while The while loop is to be used in the scenario where we don't know
loop the number of iterations in advance. The block of statements is
executed in the while loop until the condition specified in the while
loop is satisfied. It is also called a pre-tested loop.
do-while The do-while loop continues until a given condition satisfies. It is
loop also called post tested loop. It is used when it is necessary to
execute the loop at least once (mostly menu driven programs).
1. str = "Python"
2. for i in str:
3. print(i)
Output:
P
y
t
h
o
n
The range() function is used to generate the sequence of the numbers. If we pass the
range(10), it will generate the numbers from 0 to 9. The syntax of the range() function is
given below.
Syntax:
1. range(start,stop,step size)
o The start represents the beginning of the iteration.
o The stop represents that the loop will iterate till stop-1. The range(1,5) will
generate numbers 1 to 4 iterations. It is optional.
o The step size is used to skip the specific numbers from the iteration. It is optional
to use. By default, the step size is 1. It is optional.
Output:
Syntax
Output:
Example 1
1. for i in range(0,5):
2. print(i)
3. else:
4. print("for loop completely exhausted, since there is no break.")
Output:
0
1
2
3
4
for loop completely exhausted, since there is no break.
1. while expression:
2. statements
Here, the statements can be a single statement or a group of statements. The expression
should be any valid Python expression resulting in true or false. The true is any non-zero
value and false is 0.
Output:
1
2
3
4
5
6
7
8
9
10
Any non-zero value in the while loop indicates an always-true condition, whereas zero
indicates the always-false condition. This type of approach is useful if we want our
program to run continuously in the loop without any disturbance.
Example 1
1. var = 1
2. while(var != 2):
3. i = int(input("Enter the number:"))
4. print("Entered value is %d"%(i))
Output:
Example 1
1. i=1
The do while loop is used to check condition after executing the statement. It is like while
loop but it is executed at least once.
1. do {
2. //statement
3. } while (condition);
Example 1
1. i=1
2. while(i<=5):
3. print(i)
4. i=i+1
5. if(i==3):
6. break
7. else:
8. print("The while loop exhausted")
Output:
1
2
In the above code, when the break statement encountered, then while loop stopped its
execution and skipped the else statement.
The break is commonly used in the cases where we need to break the loop for a given
condition.
Example 1
1. str = "python"
2. for i in str:
3. if i == 'o':
4. break
5. print(i);
Output:
p
y
t
h
Syntax
1. #loop statements
2. continue
3. #the code to be skipped
Example 1
1. i = 0
2. while(i < 10):
3. i = i+1
4. if(i == 5):
5. continue
6. print(i)
Output:
1
2
Python Pass
In Python, the pass keyword is used to execute nothing; it means, when we don't want to
execute code, the pass can be used to execute empty. It is the same as the name refers
to. It just makes the control to pass by without executing any code. If we want to bypass
any code pass statement can be used.
Suppose we have a loop, and we do not want to execute right this moment, but we will
execute in the future. Here we can use the pass.
Example - 1:
1. for i in [1,2,3,4,5]:
2. if(i==4):
3. pass
4. print("This is pass block",i)
5. print(i)
Output:
1. 1
2. 2
3. 3
4. This is pass block 4
5. 4
6. 5
Syntax:
def fun():
statements
.
.
return [expression]
Example:
return a + b
# calling function
Output:
The result is =5
Syntax :
assert condition, error_message(optional)
Parameters: