0% found this document useful (0 votes)
0 views68 pages

lecture 3 datatypes of python

The document provides an overview of comments, variables, and data types in Python, explaining single-line and multi-line comments, the concept of variables as tags for values, and built-in data types such as NoneType, numeric types, sequences, and more. It also discusses how to convert between data types and the use of docstrings for documentation. Additionally, it covers specific data types like strings, bytes, lists, and tuples, highlighting their characteristics and usage in Python programming.

Uploaded by

kumud yadav
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)
0 views68 pages

lecture 3 datatypes of python

The document provides an overview of comments, variables, and data types in Python, explaining single-line and multi-line comments, the concept of variables as tags for values, and built-in data types such as NoneType, numeric types, sequences, and more. It also discusses how to convert between data types and the use of docstrings for documentation. Additionally, it covers specific data types like strings, bytes, lists, and tuples, highlighting their characteristics and usage in Python programming.

Uploaded by

kumud yadav
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/ 68

Lecture3

Datatypes in Python
By
Dr. Sunita Varma
Comments in Python
• Single line comment
• Comments start with hash symbol #
• Entire line till end should be treated as comment
• # to find sum of two numbers
• a = 10 # store 10 into variable a
• Comments are non-executable statements
• Neither Python compiler nor PVM will execute them
• Comments are for purpose of understanding human beings
Comments in Python
• Multi line comment
• To mark several lines as comment then writing # symbol in beginning of every line
will be tedious job
• For example
• # This is a program to find net salary of an employee
• # Based on the basic salary, provident fund, house rent allowance,
• # dearness allowance and income tax
• Multiline comment can be written by using triple double quotes ””” or
triple single quotes ‘’’ in the beginning and ending of block
• “”” This is a program to find net salary of an employee
Based on the basic salary, provident fund, house rent allowance,
dearness allowance and income tax “””
Or
• ‘’’ This is a program to find net salary of an employee
Based on the basic salary, provident fund, house rent allowance,
dearness allowance and income tax ‘’’
Docstrings
• Python supports only single line comments
• Multi line comments are not available in python
• Triple doble quotes or triple single quotes are actually not multi line
comments but they are regular strings with exception that they span
multiple line
• Memory will be allocated to these strings internally
• If these strings are not assigned to any variable than they are
removed from memory by garbage collector and the can be used as
comments
Docstrings
• Using “”” are ‘’’ or not recommended for comments since they
internally occupy memory and would waste time of interpreter since
interpreter has to check them
• If strings inside “”” or ‘’’ are written as first statements in module
functions class or method then these strings are called
documentation strings or docstrings
• docstrings are useful to create API documentation file from python
program
• API documentation file is text file or html file that contains
description of all features of software language or product
Docstrings
• When new software is created it is duty of developers to describe all
classes modules functions etc which are written in that software so
that user will be able to understand software and use it in proper way
• Descriptions are provided in separate file either as text file or html file
so user can understand that API documentation files is like help file
for end user
Docstrings
• Example:
• # program with two functions
• def add(x,y):
• “””
This functions takes two numbers and finds their sum
It displays the sum as result.
• “””
Print(“Sum =“, (x+y))
• def message():
• “””
This function display message.
This welcome message to the user
“””
print(“welcome to core python”)
• # now call the functions
add(10,25)
message()
Docstrings
• C:\>python ex.py
• sum = 35
• Wel come to python
Docstrings
• For creating API documentation file program is executed by using
following command:
• C:\python –m pydoc –w ex
sum = 35
welcome to python
wrote to ex.html

• -m indicate module with name pydoc is used to create a API


documentation file
• -w indicates HTML documentation file is to be created
• ex represents source file name
• Open ex.html in any web browser
Variables
• a = 10
• b = 15
• Value 10 is stored into left side variable a
• Storage is done by symbol = called assignment operator
• Value 15 is stored in variable b
• Variable can be imagined like memory location where data can be stored
• Name given to variable is called identifier
• Identifiers represents names of variables functions objects or any such
things
Variables
• Depending upon type od data stored into variable python interpreter
understands how much memory is to be allocated foe that variable
• In C and Java datatype of variables are explicitly declared
• int a;
• a =10;
• In python variable is used as
• a= 10
• This creates variable by name a and stores value 10
• Since 10 is stored which is integer python will understand that ‘a’ is of
integer type variable and allocates memory required to store integer
value
• If string is stored in variable a then python will understand string type
variable and allocates memory required to store string
How python sees Variables
• In programming languages like C Java and many other languages
concept of variable is connected to memory location
• In all languages variable is imagined as storage box which can store
some value
• a = 1;
• Some memory is allocated with name a and value 1 is stored in it
1

a
How python sees Variables
• For every variable created there will be new box created with variable
name to store value
• If value is changed in variable then box will updated with new value
• a = 2;

• When one variable is assigned to another variable as:


• int b = a;
How python see Variables

2 2

b a

• In python variable is seen as tag that is tied to some value


a =1
• Value 1 is created first in memory and then tag by name a is created
to show value
• a 1

• Python consider value 1 as object


How python sees Variables
• If value of a is changed to new value
• a =2
• Tag is changed to new value or object
• a 2 1

• Value 1 becomes unreferenced object it is removed by garbage


collector
• Assigning one variable to another variable makes new tag bound to
same value
• b =a
How python sees Variables
• a
2
• b

• Other languages have variables python has tags or names to


represent values
• For two variables two memory locations are created in other
languages
• In python only one memory referenced by two names
• Python is using memory efficiently
Datatypes in Python
• Datatype represents type of data stored into variable or memory
• Datatypes which are already available in Python language are called
Built-in datatypes
• Datatypes which can be created by programmers are called User-
defined datatypes
Datatypes in Python
• Built-in datatypes
❑NoneType
❑Numeric types
❑Sequences
❑Sets
❑Mappings
NoneType
• Nonetype datatype represents object that does not contain any value
• To represent such object null is used in Java
• Python store None to represent empty object and its datatype is
considered ad NoneType
• In python program maximum one none object is provided
• One of uses of None is that it is used inside function as default value
of arguments
• When calling function if no value is passed value will be taken as None
• In Boolean expression None value represents False
Numeric Types
❑Int
❑Float
❑Complex
int Datatype
• Int datatype represents integer number
• Integer number is number without decimal point or fraction part
• For example: 200 -50 0 988889987000 etc
• a = -57

• In python there is no limit for size of an int datatype


• It can store very large integer very conveniently
float datatype
• Float datatype represents floating point numbers
• Floating number is number that contains decimal point
• For example: 0.5 -3.4567 290.08 0.001
• num = 55.67998

• Floating point number can also be written in scientific notation where


e or E is used to represent power of 10
• e or E represents exponentiation
• For example: 2.5 x 104 is written as 2.5E4 or
• X =22.55e3
Complex datatype
• Complex number is number that is written in form of a+bj or a+bJ
• a represents real part and b represents imaginary part of the number
• Suffix j or J after b indicates square root value of -1
• Parts and b may contain integer or floating point value
• Foe example: 3+5j -1-5.5j 0.2+10.5J
• C1 = -1-5.5J
Complex datatype
• # python program to add two complex numbers
• c1 = 2.5+2.5J
• C2=3.0-0.5J
• C3=c1+c2
• Print(“Sum = “, c3)
Representing Binary Octal and Hexadecimal
Numbers
• Binary number should be written by prefixing 0b or 0B before value
• For example: 0b110110 0B101010011
• Hexadecimal numbers are written by prefixing 0x or 0X before value
as 0xA180 or 0X11fb91
• Octal numbers are indicated by prefixing 0o or 0O before actual value
• For example: 0o145 or 0O773
Converting Datatypes Explicitly
• Depending on type of data python internally assumes datatype for
variable
• Sometimes programmer wants to covert one data type into another
datatype
• This is called type conversion or coercion
• This is possible by mentioning datatype with parentheses
• For example for converting number into integer
• int(num)
• X = 15.56
• int(x)
• Float(x) is used to convert x into float type
• num = 15
• Float(num)
Converting Datatypes Explicitly
• Complex is used to convert x into complex number with real part x and
imaginary part zero
• For example:
• n = 10
• Complex(n)
• Comlex(x,y) is used to convert x and y into complex number such as x will
be real number and y will be imaginary number
• a = 10
• b = -5
• Complex(a,b)
• int(x) is converting datatype of x into int type and producing decimal
integer number
• int(x) can be used to convert value from other number systems into
decimal number system
Converting Datatypes Explicitly
• Program 1:
• Write a python program to conver into decimal number system
• n1 = 0o17
• n2 = 0b1110010
• n3 = 0x1c2
Converting Datatypes Explicitly
• int(string,base) is function used to convert string into integer
represents string format of number
• It should contain integer number in string format
• Base represents base of number system to be used for string
• For example base 2 represent binary number and base 1 represents
hexadecimal number
• str = “1c2”
• n = int(str,16)
• Print(n)
Converting Datatypes Explicitly
• Program 3:
• Write python program using int() function to convert numbers from
different number system into decimal number system
• s1 = “17”
• s2 = “1110010”
• s3 = “1c2”
Converting Datatypes Explicitly
• bin() function convert decimal number into binary number
• oct() function convert decimal number into octal number
• hex() function convert decimal number into hexadecimal number
• a = 10
• b = bin(a)
• print(b)

• b = oct(a)
• print(b)

• b = hex(a)
• print(b)
Bool datatype
• Bool datatype in python represents Boolean values
• There are only two Boolean values True or False that can be represented by
bool datatype
• Python internally represents True as 1 and False as 0
• Condition will be evaluated internally to either True or False
• For example:
• a = 10
• b = 20
• if (a>b):
• Print(a)
• else:
• Print(b)
Sequence in Python
• Sequence represents group of elements or items
• For example a group of integer number form sequence
• There are six types of sequences in python
❑str
❑bytes
❑bytearry
❑list
❑tuple
❑range
Str datatype
• In python str represents string type datatype
• String is represented by group of characters
• String are enclosed in single quotes or double quotes
• str = “welcome”
• str = ‘welcome’
• String can also be written in inside “”” triple double quotes or ‘’’ triple single quotes to span of group of lines
including spaces
• str1 = “””this is book on python which
discusses all the topics of core python
in a vey lucid manner”””
• str2 = ‘’’this is book on python which
discusses all the topics of core python
in a vey lucid manner’’’
Str datatype
• Triple double quotes or triple single quotes are useful to embed string into
another string
• str = “”” This is a ‘core python’ book”””
• print(str)
• str = ‘’’This is a “core python” book’’’
• Slice operator represents square brackets [] to retrieve pieces of string
• Characters in string counted from 0 onwards
• s = ‘Welcome to core python’
• print(s)
• print(s[0])
• print(s[3:7])
• print(s[11:])
• print(s[-1])
Str datatype
• Repetition operator is denoted by * symbol and useful to repeat
string for several times
• s*n repeats string for n times
• print(s*2)
Bytes datatype
• Bytes datatype represents group of byte numbers just like array does
• Byte number is any positive integer from 0 to 255
• It cannot store negative number
• For example
• elements = [10, 20, 0, 40, 15]
• x = bytes(elements)
• Print(x[0])
• Element cannot modify or edit in any element in bytes type array
• For example:
• X[0] = 55 gives error
Bytes datatype
• Program 4:
• Write a python program to create a byte array, read and display the
elements of the array
Bytearray Datatype
• Bytearray datatype is similar to bytes datatype
• Difference is that bytes type array cannot be modified but bytearray
type array can be modified
• Bytearray function is used to create byte type array
• For example:
• elements = [10, 20, 0, 40, 15]
• x = bytearray(elements)
• Print(x[0])

• x[0] = 88
• x[1] = 99
Bytearray Datatype
• Program 5: Write a program to create a bytearry and modify the first
two elements. Also retrieve the elements of array
list Datatype
• List represents group of elements
• Python are similar to arrays in C and Java
• Main difference between list and array is that list can store different
types of elements but array store only one type of elements
• List can grow dynamically in memory
• Size of array is fixed and they cannot grow at runtime
• Lists are represented using square brackets [] and elements are
written in [] separated by commas
• List = [10, -20, 15.5, ‘vijay’, “Marry”]
list Datatype
• Program 6: write a python program to print the
1. First element of list
2. First three element of list
3. Second last element of list
4. Print the list 4 times
Tuple Datatype
• Tuple is similar to list
• Tuple contains group of elements which can be of different types
• Elements in tuple are separated by commas and enclosed in
parentheses ()
• List of elements can be modified it is not possible to modify tuple
elements
• Tuple is a read only list
• For example:
• Tp1 = (10, -20, 15.5, ‘Vijay’, “Marry)
• Individual elements of tuple can be referenced using square braces as
tp1[0] tp1[1]……
• Tp1[0] = 99 gives error
Tuple Datatype
• Program 7: write a python program to print the
1. Third element of tuple
2. 2nd to 4th element of tuple
3. last element of tuple
4. Print the tuple 4 times
range Datatype
• Range data type represents sequence of numbers
• Numbers in range are not modifiable
• Generally range is used for generating for loop for specific number of
times
• For example:
• r = range(10)
• Range object is created with numbers starting from 0 to 9
• This number can be displayed by using for loop
• r = range(10,40,2)
• for i in r: print(i)
• lst = list(range(10))
• print(lst)
Sets
• Set is an unordered collection of elements
• Order of elements is not maintained in sets
• Elements may not appear in same order as they are entered into set
• Set does not accept duplicate elements
• Two sub types in sets:
❑Set datatypes
❑Frozen set datatype
set Datatype
• To create set elements are entered separated by commas inside curly
braces{}
• s = {10, 20, 30, 20, 50}
• Print(s)
• Sets are not maintaining order of elements
• Elements are not repeated in set
• ch = set(“Hello”)
• print(ch)

• lst [1,2,5,4,3]
• s = set(lst)
• print(s)
set Datatype
• Sets are unordered elements can not retrieve using indexing or slicing
operation
• For example:
• print(s[0])
• print(s[0:2])
• Gives error
• update() method is used to add elements to set as:
• s.update([50,60])
• print(s)
• remove() method is used to remove any particular element from set
• s.remove(50)
• print(s)
frozenset Datatype
• frozenset datatype is same as set datatype
• Main difference is that elements in set datatype can be modified
whereas elements of frozenset cannot be modified
• frozenset is created by passing set to frozenset() function as
• s = {50,60,70,80,90}
• print(s)

• fs = frozenset(s)
• Print(fs)
• Another way of creating frozenset is by passing string to frozenset()
function as:
• fs = frozenset(“abcdefg”)
• print(fs)
Mapping Types
• Map represents group of elements in form of key value pairs so that when key is given
associated value can be retrieved
• Dict datatype is example for map
• Dict represents dictionary that contains pairs of element such that first element
represents key and next one becomes its value
• Key and its value should be separated by colon : and every pair should be separated by
comma
• All elements should be enclosed inside curly brackets{}
• Dictionary is created for student roll number and names
• Roll number are keys and names of students are values
• d = { 10: ‘kamal’, 11: ‘paranav’, 12: ‘hasini’, 13: ‘Anup’, 14: ‘Reethu’}
• D = {} empty dictionary
• Key and values are stored in dictionary as
• d[10] = ‘kamal’
• d[11] = ‘paranav’
• Print(d)
Mapping Types
• Program 8: write a program to display
• keys of dictionary
• Values of dictionary
• Change the value of key
• Delete a key
Literals in Python
• Literal is constant value that is stored into variable in program
• a = 15
• Types of literal
❑Numerical literals
❑Boolean literals
❑String literals
Numeric literals
Literal name
450, -15 Integer literal
3.14286, -10.6, 1.25E4 Float literal
0x5A1C Hexadecimal literal
0o557 Octal literal
0B110101 Binary literal
18+3J Complex literal
Boolean Literals
• Boolean literals are TRUE and False values stored into bool type
variable
String Literals
• Group of characters is called string literals
• String literals are enclosed in single quotes ‘ or double quotes “ or triple quotes
“”” in python there is no difference between single quoted strings and double
quoted strings
• Single and double quoted strings should end in same line
• s1 = ‘This is a first Indian Book’
• s2 = “core python”
• When string literal extends beyond single line triple quotes are used
• s1 =‘’’This is first Indian book on
core python exploring all important
And useful features’’’
• s2 = “”” ’This is first Indian book on
core python exploring all important
And useful features”””
String Literals
• When string spans in more than one line adding backslash \ will join
next string to it
• For example:
• Str = “This is first line and \
This will be continued with first line”
print(str)
Escape characters like \n can be used inside string literal
str = “This is \npython”
print(str)
Escape characters escape normal meaning and are useful to perform
different task
When \n is written it will throw cursor to new line
String Literals
• Import escape characters in strings

Escape character Meaning


\ New line continuation
\\ Display a single \
\’ Display a single quote
\” Display a double quote
\b backspace
\r Enter
\t Horizontal tab space
\v Vertical tab
\n New line
Determining Datatype of Variable
• type() function is used to know datatype of variable or object
• For example:
• a = 15
• Print(type(a))
• <class ‘int’>
• Result shows class int
• It means variable a is object of class int
• Int is treated as class
• Every datatype is treated as object internally in python
• Every datatype function method class module lists sets etc. are all
objects in python
What about Characters
• Languages like C and Java contain char datatype that represents single
character
• Python does not have char datatype to represent individual characters
• It has datatype which represents string
• String consist of several characters and character is element of character
• ch = ‘A’
• Print(type(ch))
• <class ’str’>
• Individual character of string is accessed by using index of string
• str = ‘Bharat’
• print(str[0])
• B
• for i in str: print(i)
What about Characters
• Some useful methods in case of strings can also be used for
characters
• For example isupper() is method that tests whether string is
uppercase or lowercase
• str[0].isupper() # checking if ‘B’ is capital letter or not
• str[1].isupper() #checking if ‘h’ is capital letter or not
User-defined Datatypes
• Datatypes which are created by programmers are called user-defined
datatypes
• For example array class module is user-defined datatype
Constants in Python
• Constant is similar to variable but its value cannot be modified or changed
in course of program execution
• Variable value can be changes whenever required
• That is not possible for constant
• Once defined constant cannot allow changing its value
• For example in Mathematics pi value is 22/7 which never changes and
hence it is constant
• In languages like C and Java defining constants is possible
• In python that is not possible
• Programmer can indicate variable as constant by writing its name in all
capital letters
• For example MAX_Value is constant
• But its value can be changed
Identifiers and Reserved Words
• Identifier is name that is given to variable function or class etc
• Identifiers can include letters numbers and underscore character _
• They should always start with nonnumeric caharecter
• Special symbols such as ? # $ % and @ are not allowed in identifiers
• Examples are:
• Salary name11 gross-income
• Python is case sensitive programming language
Identifiers and Reserved Words
• Reserved words are words that are already reserved for some
particular purpose in python language
• Name of reserved words should not be used as identifiers
• and del from nonlocal try as elif global etc
Naming Conventions in Python
• Python developers made some suggestions to programmer regarding how
to write names in programs
• Rules related writing names of packages modules classes variable etc. are
called naming convention
• Following naming convention should be followed
❑Packages: package names should be written in all lower case letters
When multiple words are used for name they should be separated by suing underscore
❑Modules: Modules names should be written in all lower case letters
When multiple words are used for name they are separated by using underscore _
❑Classes: Each word of class name should start with capital letter
This rule is applicable for classes created by user
Python’s built-in class names use all lowercase words
When class represents exception then its name should end with word Error
Naming Conventions in Python
❑Global variables or Module-level variables: Global variables names
should be all lower case letters
When multiple words are used for name should separate them using
underscore _
❑Instance variables: Instance varaibles names should be all lower case
letters
When multiple words are used for name they are separated by using
underscore _
Non-public instance variable name should begin with underscore
❑Functions: Function names should be all lower case letters
When multiple words are used foe name they are separated by
underscore _
Naming Conventions in Python
• Methods: Method names should be all lower letters
When multiple words are used foe name they are separated by underscore _
Method arguments: in case of instance methods their first argument name should
be self
In case of class methods their first argument name should be cls
• Constants: Constants names should be written in all capital letters
If constant has several words then each word should be separated by underscore _
• Non accessible entities: Some variables functions and methods are not accessible
outside and they should be used as they are in program
Such entities names are written with two double quotes before and two double
quotes after
For example __init__(self) is function used in class to initialize variable
Thank you

You might also like