0% found this document useful (0 votes)
6 views

Python Ch-2_Notes

Python is a versatile, high-level programming language created by Guido van Rossum in 1991, known for its simplicity and support for multiple programming paradigms. It is widely used in web development, software development, scientific computing, and machine learning, among other applications. Key features include an easy-to-learn syntax, dynamic memory allocation, a large standard library, and cross-platform compatibility.

Uploaded by

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

Python Ch-2_Notes

Python is a versatile, high-level programming language created by Guido van Rossum in 1991, known for its simplicity and support for multiple programming paradigms. It is widely used in web development, software development, scientific computing, and machine learning, among other applications. Key features include an easy-to-learn syntax, dynamic memory allocation, a large standard library, and cross-platform compatibility.

Uploaded by

hetshihora247
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Python Programming (UNIT-2) | 4311601

Unit-II: Python Introduction (Marks-12)


List out features and application of python. WINTER – 2021, SUMMER-2022,
WINTER-2022

Introduction to python

 Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
 Python is a general-purpose, dynamic, high-level, and interpreted programming language.
It supports Object Oriented programming approach to develop applications. It is simple
and easy to learn and provides lots of high-level data structures.
 Python is an easy-to-learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.
 Python supports multiple programming patterns, including object-oriented and functional
or procedural programming styles.
 Python makes development and debugging fast because no compilation step is included
in Python development, and the edit-test-debug cycle is very fast.

It is used for:
 web development (server-side),
 software development,
 mathematics,
 system scripting.

Why Python?

 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a functional way.

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.

1) Easy to Learn and Use


INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 1
Python Programming (UNIT-2) | 4311601
Python is easy to learn as compared to other programming languages. Its syntax is straight
forward and much the same as the English language. There is no use of the semicolon or
curly-bracket, the indentation defines 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 programmers to
develop the software for several competing platforms by writing a program only once.

5) Free and Open Source

Python is freely available for everyone. It is freely available on its official website
www.python.org. 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) 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.

8) 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.

9) 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.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 2


Python Programming (UNIT-2) | 4311601
10). 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.

11). Dynamic Memory Allocation

In Python, we don't need to specify the data-type of the variable. When we assign some
value to the variable, it automatically allocates the memory to the variable at run time.
Suppose we are assigned integer value 15 to x, then we don't need to write int x = 15. Just
write x = 15.

Applications of python programming

1) Web Applications
We can use Python to develop web applications. It provides libraries to handle internet
protocols such as HTML and XML, JSON, Email processing, request, beautiful Soup,
Feedparser, etc. One of Python web-framework named Django is used on Instagram. Python
provides many useful frameworks, and these are given below:
 Django and Pyramid framework(Use for heavy applications)
 Flask and Bottle (Micro-framework)
 Plone and Django CMS (Advance Content management)

2) Desktop GUI Applications

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 3


Python Programming (UNIT-2) | 4311601
The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a Tk GUI library to develop a user interface. Some popular GUI
libraries are given below.
 Tkinter or Tk
 wxWidgetM
 Kivy (used for writing multitouch applications )
 PyQt or Pyside

3) Console-based Application
Console-based applications run from the command-line or shell. These applications are
computer program which are used commands to execute. This kind of application was more
popular in the old generation of computers.
Python provides many free library or module which helps to build the command-line apps.
The necessary IO libraries are used to read and write. It helps to parse argument and create
console help text out-of-the-box. There are also advance libraries that can develop
independent console apps.
4) Software Development
Python is useful for the software development process. It works as a support language and
can be used to build control and management, testing, etc.
 SCons is used to build control.
 Buildbot and Apache Gumps are used for automated continuous compilation and
testing.
 Round or Trac for bug tracking and project management.

5) Scientific and Numeric


Python is widely used in scientific and numeric computing:
 SciPy is a collection of packages for mathematics, science, and engineering.
 IPython is a powerful interactive shell that features easy editing and recording of a
work session, and supports visualizations and parallel computing.
 Pandas is a data analysis and modeling library.

6) Business Applications
Python is also used to build ERP and e-commerce systems:
 Odoo is an all-in-one management software that offers a range of business
applications that form a complete suite of enterprise management applications.
 Tryton is a three-tier high-level general purpose application platform.

7) Audio or Video-based Applications

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 4


Python Programming (UNIT-2) | 4311601
Python is flexible to perform multiple tasks and can be used to create multimedia
applications. Some multimedia applications which are made by using Python are TimPlayer,
cplay, etc. Gstreamer, Pyglet, and QT Phonon are some of the few multimedia libraries.
8) 3D CAD Applications
CAD (Computer-Aided Design) is the process of designing products and structures using
computers. CAD applications have become an integral part of the design process, allowing
designers to change a 3D model in real time and explore different design options. Python is a
powerful programming language that can be used to create CAD applications.
9) Enterprise Applications
Python can be used to create applications that can be used within an Enterprise or an
Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.
10) Image Processing Application
Python contains many libraries that are used to work with the image. The image can be
manipulated according to our requirements.
11) Machine Learning and Artificial Intelligence
Python has found its way into the world of machine learning and artificial intelligence
software.
Machine learning and artificial intelligence are the two most important technologies that
have changed the world by making it smarter.
Disadvantages of Python
1. Speed Limitations
2. Weak in Mobile Computing and Browsers
3. Design Restrictions
4. Underdeveloped Database Access Layers
5. Simple
Explain Basic Structure of Python Program. WINTER - 2021
Basic structure of python program
Every programming language has a basic structure to write program. Python has 6 different
sections
1. Documentation Section:
The documentation section is an important section but optional for a python program. It
includes basic information about a python program.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 5


Python Programming (UNIT-2) | 4311601
The information includes the author's name, date of creation, version, program name,
company name, and description of the program. It improves the readability of the program.
2. Import Statements
The import section provides instructions to the interpreter to link functions from the module
such as using the import statement.
3. Global variable section
Some variables are used more than one function. Such variables are called global variable
and declared in the global section that is outside of all functions.
4. Class Definition
Here, we can declare different classes. Classes are a collocation of data members and data
functions.
5. User define functions
This section also declares all the user defined function.
6. Executable part
There is at least one statement in the executable part.
Example:
“”” Basic program Strucuture”””
import math # adding math module
x=22 #Global variable
def add(); #user define function
a=20
b=2
print(“add=”,a+b)
print(“Start python programming”) #Executable part
add()
Keywords
Every scripting language has designated words or keywords, with particular definitions and
usage guidelines. Python is no exception. The fundamental constituent elements of any
Python program are Python keywords.
Python keywords are unique words reserved with defined meanings and functions that we
can only apply for those functions. You'll never need to import any keyword into your
program because they're permanently present.
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 6
Python Programming (UNIT-2) | 4311601
False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield

Identifiers
Python Identifier is the name we give to identify a variable, function, class, module or other
object. That means whenever we want to give an entity a name, that’s called identifier.
Rules for Writing Identifiers
There are some rules for writing Identifiers. But first you must know Python is case
sensitive. That means Name and name are two different identifiers in Python.
Here are some rules for writing Identifiers in python.
1. Identifiers can be combination of uppercase and lowercase letters, digits or an
underscore(_). So myVariable, variable_1, variable_for_print all are valid python
identifiers.
2. An Identifier cannot start with digit. So while variable1 is valid, 1variable is not valid.
3. We can’t use special symbols like !,#,@,%,$ etc in our Identifier.
4. Identifier can be of any length.

Check following variable names and indicate whether it is valid or invalid. SUMMER-
2022
i) _my_var = "IT"
ii) 16myvar="AHMedabad"
iii) iii) MYVAR = "computer2"
Define variable and mention rules for choosing name of variable.WINTER-2022
Variables
Variables are containers for storing data values.
A variable, as the name indicates is something whose value is changeable over time. In fact a
variable is a memory location where a value can be stored.
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 7
Python Programming (UNIT-2) | 4311601
Later we can retrieve the value to use. But for doing it we need to give a variable name to
that memory location so that we can refer to it. That’s identifier, the variable name.
Declaring Variable and Assigning Values
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
We don't need to declare explicitly variable in Python. When we assign any value to the
variable, that variable is declared automatically.
The equal (=) operator is used to assign value to a variable.
Example:
x=5
y = "John"
List out various data types in python. Explain any three data types with example.
WINTER-2022
Data types
Every value has a datatype, and variables can hold values.
Python is a powerfully composed language; consequently, we don't have to characterize the
sort of variable while announcing it. The interpreter binds the value implicitly to its type.
The storage method for each of the standard data types that Python provides is specified by
Python. The following is a list of the Python-defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 8


Python Programming (UNIT-2) | 4311601

1. Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities
have a place with a Python Numbers datatype. Python offers the type() function to
determine a variable's data type.
Python supports three kinds of numerical data.
 Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and
so on. An integer can be any length you want in Python. Its worth has a place with int.
 Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate
to within 15 decimal places.
 Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y
signify the genuine and non-existent parts separately. The complex numbers like 2.14j,
2.0 + 2.3j, etc.

Example:
a=5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
Output:
The type of a <class 'int'>
The type of b <class 'float'>

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 9


Python Programming (UNIT-2) | 4311601
Sequence Type
1. String

The sequence of characters in the quotation marks can be used to describe the string. A string
can be defined in Python using single, double, or triple quotes.
When dealing with strings, the operation "hello"+" python" returns "hello python," and the
operator + is used to combine two strings.
Because the operation "Python" *2 returns "Python, Python" the operator * is referred to as
a repetition operator.
Example:
str = "string using double quotes"
print(str)
Output:
string using double quotes
2. List
Lists are used to store multiple items in a single variable.
Lists in Python are like arrays in C, but lists can contain data of different types. The things
put away in the rundown are isolated with a comma (,) and encased inside square sections [].
To gain access to the list's data, we can use slice [:] operators. Like how they worked with
strings, the list is handled by the concatenation operator (+) and the repetition operator (*).
Example:
list1 = [1, "hi", "Python", 2]
print(type(list1)) #Checking type of given list
print (list1) #Printing the list1
O/P:
<class 'list'>
[1, 'hi', 'Python', 2]
3. Tuple
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from
various data types. A parenthetical space () separates the tuple's components from one
another.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 10


Python Programming (UNIT-2) | 4311601
Because we cannot alter the size or value of the items in a tuple, it is a read-only data
structure.
Example:
tup = (1, "hi", "Python", 2)
print(type(tup)) #Checking type of given tuple
print (tup) #Printing the tuple
O/P:
<class 'tuple'>
('hi', 'Python', 2)
Dictionary
A dictionary is a key-value pair set arranged in any order. It stores a specific value for each
key, like an associative array or a hash table. Value is any Python object, while the key can
hold any primitive data type.
The comma (,) and the curly braces are used to separate the items in the dictionary.
Example:
d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
print(d)
O/P:
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
Boolean

True and False are the two default values for the Boolean type. These qualities are utilized to
decide the given assertion valid or misleading. The class book indicates this.

False can be represented by the 0 or the letter "F," while true can be represented by any value
that is not zero.

Example:

print(type(True))

print(type(False))

print(false)

O/P:

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 11


Python Programming (UNIT-2) | 4311601
<class 'bool'>

<class 'bool'>

NameError: name 'false' is not defined

Set

The data type's unordered collection is Python Set.

It is iterable, mutable(can change after creation), and has remarkable components. The
elements of a set have no set order; It might return the element's altered sequence.

Either a sequence of elements is passed through the curly braces and separated by a comma
to create the set or the built-in function set() is used to create the set. It can contain different
kinds of values.

Example:

# Creating Empty set

set1 = set()

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

print(set2) #Printing Set value

O/P:

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

List out arithmetic operations. Build python code which performs three arithmetic
operations. SUMMER-2022

Summarize the assignment operators of python. SUMMER-2022

Summarize the comparison operators of python. SUMMER-2022

Operators

The operator is a symbol that performs a specific operation between two operands, according
to one definition.

Operators are used to perform operations on variables and values.

Python also has some operators, and these are given below –

1. Arithmetic operators
2. Comparison operators
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 12
Python Programming (UNIT-2) | 4311601
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

1. Arithmetic Operators

Arithmetic operators used between two operands for a particular operation. There are many
arithmetic operators. These operations are Addition, Subtraction, Multiplication, Division,
Modulus, Expoents and Floor Division.

Operator Name Example

+ Addition 10 + 20 = 30

- Subtraction 20 – 10 = 10

* Multiplication 10 * 20 = 200

/ Division 20 / 10 = 2

% Modulus 22 % 10 = 2

** Exponent(same as power function) 4**2 = 16

// Floor Division(smallest possible nearest 9//2 = 4


integer value)

Example:

a = 21

b = 10

# Addition

print ("a + b : ", a + b)

# Subtraction

print ("a - b : ", a - b)

# Multiplication

print ("a * b : ", a * b)

# Division

print ("a / b : ", a / b)

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 13


Python Programming (UNIT-2) | 4311601
# Modulus

print ("a % b : ", a % b)

# Exponent

print ("a ** b : ", a ** b)

# Floor Division

print ("a // b : ", a // b)

O/P:

a + b : 31

a - b : 11

a * b : 210

a / b : 2.1

a%b: 1

a ** b : 16679880978201

a // b : 2

2.Comparison Operators

Python comparison operators compare the values on either sides of them and decide the
relation among them. They are also called relational operators. These operators are equal, not
equal, greater than, less than, greater than or equal to and less than or equal to.

Operator Name Example

== Equal 4 == 5 is not true.

!= Not Equal 4 != 5 is true.

> Greater Than 4 > 5 is not true.

< Less Than 4 < 5 is true.

>= Greater than or Equal to 4 >= 5 is not true.

<= Less than or Equal to 4 <= 5 is true.

Example

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 14


Python Programming (UNIT-2) | 4311601
Following is an example which shows all the above comparison operations:

a=4

b=5

# Equal

print ("a == b : ", a == b)

# Not Equal

print ("a != b : ", a != b)

# Greater Than

print ("a > b : ", a > b)

# Less Than

print ("a < b : ", a < b)

# Greater Than or Equal to

print ("a >= b : ", a >= b)

# Less Than or Equal to

print ("a <= b : ", a <= b)

O/P:

a == b : False

a != b : True

a > b : False

a < b : True

a >= b : False

a <= b : True

3.Assignment Operators

Python assignment operators are used to assign values to variables. These operators include
simple assignment operator, addition assign, subtraction assign, multiplication assign,
division and assign operators etc.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 15


Python Programming (UNIT-2) | 4311601
Operator Name Example

= Assignment Operator a = 10

+= Addition Assignment a += 5 (Same as a = a + 5)

-= Subtraction Assignment a -= 5 (Same as a = a - 5)

*= Multiplication Assignment a *= 5 (Same as a = a * 5)

/= Division Assignment a /= 5 (Same as a = a / 5)

%= Remainder Assignment a %= 5 (Same as a = a % 5)

**= Exponent Assignment a **= 2 (Same as a = a ** 2)

//= Floor Division Assignment a //= 3 (Same as a = a // 3)

Example:

# Assignment Operator

a = 10

# Addition Assignment

a += 5

print ("a += 5 : ", a)

# Subtraction Assignment

a -= 5

print ("a -= 5 : ", a)

# Multiplication Assignment

a *= 5

print ("a *= 5 : ", a)

# Division Assignment

a /= 5

print ("a /= 5 : ",a)

O/P:
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 16
Python Programming (UNIT-2) | 4311601
a += 5 : 105

a -= 5 : 100

a *= 5 : 500

a /= 5 : 100.0

4. Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b =
13; Now in the binary format their values will be 0011 1100 and 0000 1101 respectively.
Following table lists out the bitwise operators supported by Python language with an
example each in those, we use the above two variables (a and b) as operands −

a = 0011 1100

b = 0000 1101

--------------------------

a&b = 12 (0000 1100)

a|b = 61 (0011 1101)

a^b = 49 (0011 0001)

~a = -61 (1100 0011)

a << 2 = 240 (1111 0000)

a>>2 = 15 (0000 1111)

Operator Name Example

& Binary AND Sets each bit to 1 if both bits are 1

| Binary OR Sets each bit to 1 if one of two bits is 1

^ Binary XOR Sets each bit to 1 if only one of two bits is 1

~ Binary Ones Complement Inverts all the bits

<< Binary Left Shift Shift left by pushing zeros in from the right and let
the leftmost bits fall off

>> Binary Right Shift Shift right by pushing copies of the leftmost bit in
from the left, and let the rightmost bits fall off

Example

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 17


Python Programming (UNIT-2) | 4311601
Following is an example which shows all the above bitwise operations:

a = 60 # 60 = 0011 1100

b = 13 # 13 = 0000 1101

# Binary AND

c=a&b # 12 = 0000 1100

print ("a & b : ", c)

# Binary OR

c=a|b # 61 = 0011 1101

print ("a | b : ", c)

# Binary XOR

c=a^b # 49 = 0011 0001

print ("a ^ b : ", c)

# Binary Ones Complement

c = ~a; # -61 = 1100 0011

print ("~a : ", c)

# Binary Left Shift

c = a << 2; # 240 = 1111 0000

print ("a << 2 : ", c)

# Binary Right Shift

c = a >> 2; # 15 = 0000 1111

print ("a >> 2 : ", c)

O/P:

a & b : 12

a | b : 61

a ^ b : 49

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 18


Python Programming (UNIT-2) | 4311601
~a : -61

a >> 2 : 240

a >> 2 : 15

5. Logical Operators

There are following logical operators supported by Python language. Assume variable a
holds 10 and variable b holds 20 then

Operator Description Example

and Logical If both the operands are true then condition becomes true. (a and b)
AND is true.

or Logical OR If any of the two operands are non-zero then condition becomes true. (a or b) is
true.

not Logical Used to reverse the logical state of its operand. Not(a and
NOT b) is false.

Example:

x=5

print(x > 3 and x < 10)

# returns True because 5 is greater than 3 AND 5 is less than 10

O/P:

True

6. Membership Operators

Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below –

Operat Description Example


or

in Evaluates to true if it finds a variable in the specified x in y, here in results in a 1 if


sequence and false otherwise. x is a member of sequence y.

not in Evaluates to true if it does not finds a variable in the x not in y, here not in results
specified sequence and false otherwise. in a 1 if x is not a member of
sequence y.

Example:
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 19
Python Programming (UNIT-2) | 4311601
a = 10

b = 20

list = [1, 2, 3, 4, 5 ];

if ( a in list ):

print "Line 1 - a is available in the given list"

else:

print "Line 1 - a is not available in the given list"

if ( b not in list ):

print "Line 2 - b is not available in the given list"

else:

print "Line 2 - b is available in the given list"

O/P:

Line 1 - a is not available in the given list

Line 2 - b is not available in the given list

7. Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity
operators explained below –

Operator Description Example

is Evaluates to true if the variables on either side of the x is y, here is results in 1 if


operator point to the same object and false otherwise. id(x) equals id(y).

is not Evaluates to false if the variables on either side of the x is not y, here is
operator point to the same object and true otherwise. not results in 1 if id(x) is
not equal to id(y).

Example:

a = 20

b = 20

if ( a is b ):

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 20


Python Programming (UNIT-2) | 4311601
print "Line 1 - a and b have same identity"

else:

print "Line 1 - a and b do not have same identity"

if ( id(a) == id(b) ):

print "Line 2 - a and b have same identity"

else:

print "Line 2 - a and b do not have same identity"

O/P:

Line 1 - a and b have same identity

Line 2 - a and b have same identity

Develop python code which calculate the value of c using equation c=a/b. Apply explicit
type conversion, Take a=50 and b=2.7 SUMMER-2022

Explain Type Conversion in Python. WINTER – 2021, WINTER-2022

Type Conversion

Python defines type conversion functions to directly convert one data type to another which
is useful in day-to-day and competitive programming.

There are two types of Type Conversion in Python:

1. Implicit Type Conversion


2. Explicit Type Conversion

1. Implicit Type Conversion

In Implicit type conversion of data types in Python, the Python interpreter automatically
converts one data type to another without any user involvement. To get a more clear view of
the topic see the below examples.

Example:

x = 10

print("x is of type:",type(x))

y = 10.6

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 21


Python Programming (UNIT-2) | 4311601
print("y is of type:",type(y))

z=x+y

print(z)

print("z is of type:",type(z))

O/P:

x is of type: <class 'int'>

y is of type: <class 'float'>

20.6

z is of type: <class 'float'>

2. Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to required data type.

We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion.

This type of conversion is also called typecasting because the user casts (changes) the data
type of the objects.

Example:

num_string = '12'

num_integer = 23

print("Data type of num_string before Type Casting:",type(num_string))

# explicit type conversion

num_string = int(num_string)

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string

print("Sum:",num_sum)

print("Data type of num_sum:",type(num_sum))

O/P:

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 22


Python Programming (UNIT-2) | 4311601
Data type of num_string before Type Casting: <class 'str'>

Data type of num_string after Type Casting: <class 'int'>

Sum: 35

Data type of num_sum: <class 'int'>

Comment in Python

Python comments are programmer-readable explanation in the Python source code.

They are added with the purpose of making the source code easier for humans to understand,
and are ignored by Python interpreter.

Comments enhance the readability of the code and help the programmers to understand the
code very carefully.

Just like most modern languages, Python supports single-line (or end-of-line) and multi-line
(block) comments.

There are three types of comments available in Python

1. Single line Comments


2. Multiline Comments

1. Single Line Comments

A hash sign (#) that is not inside a string literal begins a comment. All characters after the #
and up to the end of the physical line are part of the comment and the Python interpreter
ignores them.

2. Multi-Line Comments

Python does not provide a direct way to comment multiple line. You can comment multiple
lines as follows −

# This is a comment.

# This is a comment, too.

# This is a comment, too.

# I said that already.

triple-quoted string is also ignored by Python interpreter and can be used as a multiline
comments:

'''
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 23
Python Programming (UNIT-2) | 4311601
This is a multiline

comment.

'''

**********
“Do not give up, the beginning is always hardest!”

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 24

You might also like