0% found this document useful (0 votes)
3 views37 pages

Python Unit1

Uploaded by

drashtijasani11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views37 pages

Python Unit1

Uploaded by

drashtijasani11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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 easy to learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.

Python supports multiple programmingpattern, including object-oriented, and functional


or procedural programming styles.

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.

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-bracketdefinesin the code block.

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

Python CH-1 (Dixita Bhimani) Page 1


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 [Link]. 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.

Python CH-1 (Dixita Bhimani) Page 2


Suppose we are assigned integer value 15 to x, then we don't need to write int x =
15. Just write x = 15.

Python Applications

How to Install Python (Environment Set-up)


Installation on Windows
Visit the link [Link] to download the latest release of
Python. In this process, we will install Python 3.7.3 on our Windows operating system.

Using this video you can install python in your computer

[Link]

Understanding Python Bytecode

The source code of a programming language can be executed using an interpreter or a

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

Python CH-1 (Dixita Bhimani) Page 3


machine can have a different operating system and hardware. After compilation, the

target machine will directly run the machine code.

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.

Python is usually called an interpreted language, however, it combines compiling and

interpreting. When we execute a source code (a file with a .py extension), Python first

compiles it into a bytecode. The bytecode is a low-level platform-independent

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

virtual machine which is called the Python Virtual Machine (PVM).

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

platform-independent, but PVM is specific to the target machine. The default

implementation of the Python programming language is CPython which is written in the C

programming language. CPython compiles the python source code into the bytecode,

and this bytecode is then executed by the CPython virtual machine.

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:

Python CH-1 (Dixita Bhimani) Page 4


It is a Python compiler that was implemented in C language. Even C++ code can be
execute using CPython.

2. JPython:

It is enables Python implementation to be run on Java platform. It runs on JVM.

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:

It is written in the form of Python(X,Y). It is designed by adding scientific and engineering


related packages.

[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

Python CH-1 (Dixita Bhimani) Page 5


Internal working of Python
Python is an object oriented programming language like Java. Python is called an
interpreted language. Python uses code modules that are interchangeable instead of a
single long list of instructions that was standard for functional programming languages.
The standard implementation of python is called “cpython”. It is the default and widely
used implementation of the Python.
Python doesn’t convert its code into machine code, something that hardware can
understand. It actually converts it into something called byte code. So within python,
compilation happens, but it’s just not into a machine language. It is into byte code and
this byte code can’t be understood by CPU. So we need actually an interpreter called the
python virtual machine. The python virtual machine executes the byte codes.

The Python interpreter performs following tasks to execute a Python program:


 Step 1: The interpreter reads a python code or instruction. Then it verifies that
the instruction is well formatted, i.e. it checks the syntax of each line. Ifany
erroroccur it immediately stop the translation and shows an error message.
 Step 2: If there is no error, i.e. if the python instruction or code is well formatted
then the interpreter translates it into its equivalent form in intermediate language
called “Byte code”.Thus, after successful execution of Python script or code, it is
completely translated into Byte code.

Python CH-1 (Dixita Bhimani) Page 6


 Step 3: Byte code is sent to the Python Virtual Machine (PVM).Here again the
byte code is executed on [Link] an error occurs during this execution then the
execution is stop with an error message.

Memory Management in Python


Understanding Memory allocation is important to any software developer as writing efficient
code means writing a memory-efficient code.

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

When x = 10 is executed an integer object 10 is created in memory and its reference


is assigned to variable x, this is because everything is object in Python.

Let’s verify if it’s true


Example
x =10
y =x

ifid(x) ==id(y):
print("x and y refer to the same object")
Output:
x and y refer to the same object

Python CH-1 (Dixita Bhimani) Page 7


In the above example, y = x will create another reference variable y which will refer
to the same object because Python optimizes memory utilization by allocation the
same object reference to a new variable if the object already exists with the same
value.

There are two parts of memory:


 stack memory
 heap memory
The methods/method calls and the references are stored in stack memory and all
the values objects are stored in a private heap.

Garbage Collection in Python


In any program, garbage is a collection of memory that is not being used by the program or
was being used at a given point but not anymore. As this memory space remains allocated to
the program but is not being used by it hence it is wasted memory which needs to be cleaned.

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.

Python: Automatic Garbage collection

Garbage collection in Python works automatically. When no reference is left to a


variable/data/value or object then the memory occupied by that object is freed up by garbage
collection mechanism of python. Thus, python provides with good memory management and
prevents the wastage of memory.

Python: Forced Garbage Collection

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

Python CH-1 (Dixita Bhimani) Page 8


Difference between C and Python
C python
1. Python is an object oriented programming
1. C is a procedure oriented programming
language with some features such as classes,
language
objects, polymorphism, inheritance etc.

2. Execution speed is fast 2. Execution speed is slow

3. Declaration of variables is required. 3. Declaration of variables is not required.

4. It cannot handle exceptions 4. It can handle exceptions.

5. It does not have garbage collector. [Link] has garbage collector

6. Indentation of C statement is not required 6. Indentation is compulsory

7. Comma is used as statement separator. 7. Semicolon is used as statement separator

8. semicolon is used to terminate the


8. New line indicates statements termination.
statement

9. Array index can be positive or negitive


9. Array index must be positive integer.
integer.

10. It supports one and multi-dimensional


10. It support only one dimensional array.
array.

11. It supports pointers. 11. It does not support pointers.

java python
Java is a Compiled Language Python is an Interpreted Language

Java is statically typed Python is dynamically typed

Complex learning curve Easy to learn and use

Python CH-1 (Dixita Bhimani) Page 9


Multiple inheritances is partially done through It offers both single and multiple inheritances.
interfaces.

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.

class A { Hello World in Python:


public static void main(String args[])
{ print "hello world";
[Link]("Hello World");
}
}
It is an object oriented programming language It is a scripting language

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.

o The first character of the variable must be an alphabet or underscore ( _ ).

Python CH-1 (Dixita Bhimani) Page 10


o 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).
o Identifier name must not contain any white-space, or special character (!, @, #,
%, ^, &, *).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive; for example, my name, and MyName is not
the same.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.

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. Assigning single value to multiple variables

1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)

Python CH-1 (Dixita Bhimani) Page 11


Output:
50
50
50

2. Assigning multiple values to multiple variables:


1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
5
10
15

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.

True False None and as

asset def class continue break


else finally elif del except
global for if from import
raise try or return pass
nonlocal in not is lambda

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

Python CH-1 (Dixita Bhimani) Page 12


Numbers
Python supports three types of numeric data.

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'>

Python CH-1 (Dixita Bhimani) Page 13


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

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.

String handling in Python is a straightforward task since Python provides built-in


functions and operators to perform operations in the string.

In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".

The operator * is known as a repetition operator as the operation "Python" *2 returns


'Python Python'.

The following example illustrates the string in Python.

Example - 1

1. str = "string using double quotes"


2. print(str)
3. s = '''''A multiline
4. string'''
5. print(s)
Output:
string using double quotes
A multiline
string

Consider the following example of string handling.

Example - 2

1. str1 = 'hello javatpoint' #string str1


2. str2 = ' how are you' #string str2
3. print (str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. print (str1 + str2) #printing the concatenation of str1 and str2

Output:

he
o

Python CH-1 (Dixita Bhimani) Page 14


hellojavatpointhellojavatpoint
hellojavatpoint how are you

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.

Consider the following example.

1. list1 = [1, "hi", "Python", 2]


2. #Checking type of given list
3. print(type(list1))
4.
5. #Printing the list1
6. print (list1)
7.
8. # List slicing
9. print (list1[3:])
10.
11. # List slicing
12. print (list1[0:2])
13.
14. # List Concatenation using + operator
15. print (list1 + list1)
16.
17. # List repetation using * operator
18. 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
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.

Python CH-1 (Dixita Bhimani) Page 15


Let's see a simple example of the tuple.

1. tup = ("hi", "Python", 2)


2. # Checking type of tup
3. print (type(tup))
4.
5. #Printing the tuple
6. print (tup)
7.
8. # Tuple slicing
9. print (tup[1:])
10. print (tup[0:1])
11.
12. # Tuple concatenation using + operator
13. print (tup + tup)
14.
15. # Tuple repatation using * operator
16. print (tup * 3)
17.
18. # Adding value to tup. It will throw an error.
19. 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 "[Link]", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

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 {}.

Consider the following example.

1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}


2.
3. # Printing dictionary
4. print (d)

Python CH-1 (Dixita Bhimani) Page 16


5.
6. # Accesing value using keys
7. print("1st name is "+d[1])
8. print("2nd name is "+ d[4])
9.
10. print ([Link]())
11. print ([Link]())

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.

1. # Python program to check the boolean type


2. print(type(True))
3. print(type(False))
4. print(false)

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.

1. # Creating Empty set


2. set1 = set()

Python CH-1 (Dixita Bhimani) Page 17


3.
4. set2 = {'James', 2, 3,'Python'}
5.
6. #Printing Set value
7. print(set2)
8.
9. # Adding element to the set
10.
11. [Link](10)
12. print(set2)
13.
14. #Removing element from the set
15. [Link](2)
16. print(set2)

Output:

{3, 'Python', 'James', 2}


{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

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.

# Create frozenset objects


fs1 = frozenset([1, 2, 3])
fs2 = frozenset(['a', 'b'])

# Create a dictionary using frozenset objects as keys


my_mapping = {
fs1: "First set of numbers",
fs2: "First set of letters"
}

Python CH-1 (Dixita Bhimani) Page 18


print(my_mapping[frozenset([1, 2, 3])])
print(my_mapping[frozenset(['a', 'b'])])

Type Conversion in Python




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'>

Explanation: x is an integer and y is a float. In z = x + y, Python


automatically converts x to float to avoid data loss, making z a float 0.6.
Explicit Type Conversion
Explicit conversion (or type casting) is when you manually convert the
data type of a value using Python’s built-in functions . This is helpful
when you want to control how the data is interpreted or manipulated in
your code. Some common type casting functions include:
 int() converts a value to an integer

Python CH-1 (Dixita Bhimani) Page 19


 float() converts a value to a floating point number
 str() converts a value to a string
 bool() converts a value to a Boolean (True/False)

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.

Consider the following table for a detailed explanation of arithmetic operators.


Operator Description
+ (Addition) It is used to add two operands. For example, if a = 20, b = 10
=>a+b = 30
- (Subtraction) It is used to subtract the second operand from the first

Python CH-1 (Dixita Bhimani) Page 20


operand. If the first operand is less than the second operand,
the value results negative. For example, if a = 20, b = 10 =>
a - b = 10
/ (divide) It returns the quotient after dividing the first operand by the
second operand. For example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example,
(Multiplication if a = 20, b = 10 => a * b = 200
)
% (reminder) It returns the reminder after dividing the first operand by the
second operand. For example, if a = 20, b = 10 =>a%b = 0
** (Exponent) It is an exponent operator represented as it calculates the first
operand power to the second operand.
// (Floor It gives the floor value of the quotient produced by dividing
division) the two operands.

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

Python CH-1 (Dixita Bhimani) Page 21


= It assigns the value of the right expression to the left operand.
+= It increases the value of the left operand by the value of the right
operand and assigns the modified value back to left operand. For
example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and
therefore, a = 30.
-= It decreases the value of the left operand by the value of the right
operand and assigns the modified value back to left operand. For
example, if a = 20, b = 10 => a- = b will be equal to a = a- b and
therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right
operand and assigns the modified value back to then the left operand.
For example, if a = 10, b = 20 => a* = b will be equal to a = a* b and
therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand
and assigns the reminder back to the left operand. For example, if a =
20, b = 10 => a % = b will be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will
assign 4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will
assign 4//3 = 1 to a.

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

hence, a & b = 0011


a | b = 0111
a ^ b = 0100
~ a = 1000

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

Python CH-1 (Dixita Bhimani) Page 22


or) resulting bit will be 1.
^ (binary The resulting bit will be 1 if both the bits are different; otherwise, the
xor) resulting bit will be 0.
~ It calculates the negation of each bit of the operand, i.e., if the bit is
(negation 0, the resulting bit will be 1 and vice versa.
)
<< (left The left operand value is moved left by the number of bits present in
shift) the right operand.
>> (right The left operand is moved right by the number of bits present in the
shift) right operand.

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 CH-1 (Dixita Bhimani) Page 23


is It is evaluated to be true if the reference present at both sides point to
the same object.
is not It is evaluated to be true if the reference present at both sides do not
point to the same object.

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.

In python there are three types of comment

1) Single line comment

2) Multiline comment

3) Dcostring comment

Let's understand the following example.

1. Single line comment

2. # This is the print statement


3. print("Hello Python")

Here we have written comment over the print statement using the hash(#). It will not
affect our print statement.

2. Multiline Python Comment

We must use the hash(#) at the beginning of every line of code to apply the multiline
Python comment. Consider the following example.

1. # First line of the comment


2. # Second line of the comment
3. # Third line of the comment

Example:

1. # Variable a holds value 5


2. # Variable b holds value 10
3. # Variable c holds sum of a and b
4. # Print the result

Python CH-1 (Dixita Bhimani) Page 24


5. a = 5
6. b = 10
7. c = a+b
8. print("The sum is:", c)

Output:

The sum is: 15

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.

3. Docstrings Python Comment

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

Python If-else statements


Decision making is the most important aspect of almost all the programming languages.
As the name implies, decision making allows us to run a particular block of code for a
particular decision. Here, the decisions are made on the validity of the particular
conditions. Condition checking is the backbone of decision making.

In python, decision making is performed by the following statements.

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.

Python CH-1 (Dixita Bhimani) Page 25


Nested if Nested if statements enable us to use if ?else statement inside an
Statemen outer if statement.
t

The if statement
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block. The condition of if statement can be any
valid logical expression which can be either evaluated to true or false.

The syntax of the if-statement is given below.

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:

enter the number?10


Number is even

Example 2 : Program to print the largest of the three numbers.


1. a = int(input("Enter a? "));
2. b = int(input("Enter b? "));
3. c = int(input("Enter c? "));
4. if a>b and a>c:
5. print("a is largest");
6. if b>a and b>c:
7. print("b is largest");
8. if c>a and c>b:
9. print("c is largest");

Output:

Enter a? 100
Enter b? 120
Enter c? 130
c is largest

The if-else statement


The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition.

Python CH-1 (Dixita Bhimani) Page 26


If the condition is true, then the if-block is executed. Otherwise, the else-block is
executed.

The syntax of the if-else statement is given below.

1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)

Example 1 : Program to check whether a person is eligible to


vote or not.
1. age = int (input("Enter your age? "))
2. if age>=18:
3. print("You are eligible to vote !!");
4. else:
5. print("Sorry! you have to wait !!");

Output:

Enter your age? 90


You are eligible to vote !!

Example 2: Program to check whether a number is even or not.


1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even...")
4. else:
5. print("Number is odd...")

Output:

enter the number?10


Number is even

The elif statement


The elif statement enables us to check multiple conditions and execute the specific block
of statements depending upon the true condition among them. We can have any number
of elif statements in our program depending upon our need. However, using elif is
optional.

The elif statement works like an if-else-if ladder statement in C. It must be succeeded by
an if statement.

The syntax of the elif statement is given below.

Python CH-1 (Dixita Bhimani) Page 27


1. if expression 1:
2. # block of statements
3. elif expression 2:
4. # block of statements
5. elif expression 3:
6. # block of statements
7. else:
8. # block of statements

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:

Enter the number?15


number is not equal to 10, 50 or 100

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 ?")

Python CH-1 (Dixita Bhimani) Page 28


Python Loops
The flow of the programs written in any programming language is sequential by default.
Sometimes we may need to alter the flow of the program. The execution of a specific
code may need to be repeated several numbers of times.

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.

Why we use loops in python?


The looping simplifies the complex problems into the easy ones. It enables us to alter the
flow of the program so that instead of writing the same code again and again, we can
repeat the same code for a finite number of times. For example, if we need to print the
first 10 natural numbers then, instead of using the print statement 10 times, we can print
inside a loop which runs up to 10 iterations.

Advantages of loops
There are the following advantages of loops in Python.

1. It provides code re-usability.


2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or linked
lists).

There are the following loop statements 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).

Python CH-1 (Dixita Bhimani) Page 29


Python for loop
The for loop in Python is used to iterate the statements or a part of the program
several times. It is frequently used to traverse the data structures like list, tuple, or
dictionary.

The syntax of for loop in python is given below.

1. for iterating_var in sequence:


2. statement(s)

For loop Using Sequence


Example-1: Iterating string using for loop

1. str = "Python"
2. for i in str:
3. print(i)

Output:

P
y
t
h
o
n

For loop Using range() function


The range() function

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.

Consider the following examples:

Example - 2: Program to print table of given number.

1. n = int(input("Enter the number "))

Python CH-1 (Dixita Bhimani) Page 30


2. for i in range(1,11):
3. c = n*i
4. print(n,"*",i,"=",c)

Output:

Enter the number 10


10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100

Nested for loop in python


Python allows us to nest any number of for loops inside a for loop. The inner loop is
executed n number of times for every iteration of the outer loop. The syntax is given
below.

Syntax

1. for iterating_var1 in sequence: #outer loop


2. for iterating_var2 in sequence: #inner loop
3. #block of statements
4. #Other statements

Example- 1: Nested for loop


1. # User input for number of rows
2. rows = int(input("Enter the rows:"))
3. # Outer loop will print number of rows
4. for i in range(0,rows+1):
5. # Inner loop will print number of Astrisk
6. for j in range(i):
7. print("*",end = '')
8. print()

Output:

Enter the rows:5


*
**
***
****
*****

Python CH-1 (Dixita Bhimani) Page 31


Using else statement with for loop
Unlike other languages like C, C++, or Java, Python allows us to use the else statement
with the for loop which can be executed only when all the iterations are exhausted. Here,
we must notice that if the loop contains any of the break statement then the else
statement will not be executed.

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.

The for loop completely exhausted, since there is no break.

Python While loop


The Python while loop allows a part of the code to be executed until the given condition
returns false. It is also known as a pre-tested loop.

It can be viewed as a repeating if statement. When we don't know the number of


iterations then the while loop is most effective to use.

The syntax is given below.

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.

While loop Flowchart

Example-1: Program to print 1 to 10 using while loop


1. i=1
2. #The while loop will iterate until condition becomes false.
3. While(i<=10):

Python CH-1 (Dixita Bhimani) Page 32


4. print(i)
5. i=i+1

Output:

1
2
3
4
5
6
7
8
9
10

Infinite while loop


If the condition is given in the while loop never becomes false, then the while loop will
never terminate, and it turns into the infinite while loop.

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:

Enter the number:10


Entered value is 10
Enter the number:10
Entered value is 10
Enter the number:10
Entered value is 10
Infinite time

Using else with while loop


Python allows us to use the else statement with the while loop also. The else block is
executed when the condition given in the while statement becomes false. Like for loop, if
the while loop is broken using break statement, then the else block will not be executed,
and the statement present after else block will be executed. The else statement is
optional to use with the while loop. Consider the following example.

Example 1
1. i=1

Python CH-1 (Dixita Bhimani) Page 33


2. while(i<=5):
3. print(i)
4. i=i+1
5. else:
6. print("The while loop exhausted")

Python Do While Loop


Python doesn't have do-while loop. But we can create a program like this.

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.

General Do While Loop Syntax

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.

Python break statement


The break is a keyword in python which is used to bring the program control out of the
loop. The break statement breaks the loops one by one, i.e., in the case of nested loops,
it breaks the inner loop first and then proceeds to outer loops. In other words, we can say
that break is used to abort the current execution of the program and the control goes to
the next line after the loop.

The break is commonly used in the cases where we need to break the loop for a given
condition.

The syntax of the break is given below.

Python CH-1 (Dixita Bhimani) Page 34


1. #loop statements
2. break;

Example 1
1. str = "python"
2. for i in str:
3. if i == 'o':
4. break
5. print(i);

Output:

p
y
t
h

Python continue Statement


The continue statement in Python is used to bring the program control to the beginning
of the loop. The continue statement skips the remaining lines of code inside the loop and
start with the next iteration. It is mainly used for a particular condition inside the loop so
that we can skip some specific code for a particular [Link] continue statement in
Python is used to bring the program control to the beginning of the loop. The continue
statement skips the remaining lines of code inside the loop and start with the next
iteration. It is mainly used for a particular condition inside the loop so that we can skip
some specific code for a particular condition.

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 CH-1 (Dixita Bhimani) Page 35


3
4
6
7
8
9
10

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.

It is beneficial when a statement is required syntactically, but we want we don't want to


execute or execute it later. The difference between the comments and pass is that,
comments are entirely ignored by the Python interpreter, where the pass statement is
not ignored.

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.

Consider the following example.

Example - Pass statement

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

Python return statement


A return statement is used to end the execution of the function call and “returns” the
result (value of the expression following the return keyword) to the caller. The

Python CH-1 (Dixita Bhimani) Page 36


statements after the return statements are not executed. If the return statement is
without any expression, then the special value None is returned.

Note: Return statement can not be used outside the function.

Syntax:
def fun():
statements
.
.
return [expression]

Example:

def add(a, b):

# returning sum of a and b

return a + b

# calling function

print("the result is=",add(2,3))

Output:
The result is =5

Python assert keyword


Assertions in any programming language are the debugging tools which help in smooth
flow of code. Assertions are mainly assumptions that a programmer knows always wants
to be true and hence puts them in code so that failure of them doesn’t allow the code to
execute further.
In python assert keyword helps in achieving this task. This statement simply takes input
a boolean condition, which when returns true doesn’t return anything, but if it is
computed to be false, then it raises an AssertionError along with the optional message
provided.

Syntax :
assert condition, error_message(optional)

Parameters:

condition : The boolean condition returning true or false.


error_message : The optional argument to be printed in console in case
of AssertionError
Returns :
Returns AssertionError, in case the condition evaluates to false along with the
error message which when provided.

Python CH-1 (Dixita Bhimani) Page 37

You might also like