[go: up one dir, main page]

0% found this document useful (0 votes)
108 views21 pages

Python Datatypes

Python supports several datatypes including numbers, lists, tuples, dictionaries, and strings. Numbers can be integers, floating point, or complex. Lists are mutable ordered sequences, tuples are immutable ordered sequences, and dictionaries store key-value pairs. Strings represent text data. Built-in functions like type() and isinstance() can check datatypes. Values of different datatypes can be converted between each other using functions like int(), float(), and str(). Operators perform computations on operands and follow an order of operations. Strings support operations like concatenation, repetition, slicing, and case changes.

Uploaded by

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

Python Datatypes

Python supports several datatypes including numbers, lists, tuples, dictionaries, and strings. Numbers can be integers, floating point, or complex. Lists are mutable ordered sequences, tuples are immutable ordered sequences, and dictionaries store key-value pairs. Strings represent text data. Built-in functions like type() and isinstance() can check datatypes. Values of different datatypes can be converted between each other using functions like int(), float(), and str(). Operators perform computations on operands and follow an order of operations. Strings support operations like concatenation, repetition, slicing, and case changes.

Uploaded by

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

PYTHON DATATYPES

Prepared By
Anand G
Assistant Professor,
ECE Department,
Dr. Mahalingam College of Engineering and Technology,
Pollachi-642003
Email: anandg@drmcet.ac.in
Python numbers
• Integers, floating point numbers and complex numbers fall under Python
numbers category. They are defined as int, float and complex class in
Python.
• We can use the type() function to know which class a variable or a value
belongs to and the isinstance() function to check if an object belongs to a
particular class.
a=5
>>>print(a, "is of type", type(a))
5 is of type <class 'int'>
>>>a = 2.0
>>>print(a, "is of type", type(a))
2.0 is of type <class 'float'>
>>>a= 1+2j
>>>print(a, "is complex number?")
 (1+2j) is complex number?
>>>print(isinstance(1+2j, complex))
 True
Number Length
• Integers can be of any length, it is only limited by the memory available. A
floating point number is accurate up to few decimal places. Integer and
floating points are separated by decimal points. 1 is integer, 1.0 is floating
point number.
• Complex numbers are written in the form, x + yj, where x is the real part
and y is the imaginary part.
Examples
>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
>>> c = 1+2j
• >>> c
(1+2j)
Python List
• List is an ordered sequence of items. It is one of the most used datatype in
Python and is very flexible. All the items in a list do not need to be of the
same type.
• Declaring a list is pretty straight forward. Items separated by commas are
enclosed within brackets [ ].
• We can use the slicing operator [ ] to extract an item or a range of items
from a list. Index starts form 0 in Python.

Examples: Lists are mutable, meaning, value of


>>>a = [5,10,15,20,25,30,35,40] elements of a list can be altered.
>>>print("a[2] = ", a[2])
 a[2] = 15 >>> a = [1,2,3]
>>>print("a[0:3] = ", a[0:3]) >>> a[2]=4
 a[0:3] = [5, 10, 15] >>> print(a)
>>>print("a[5:] = ", a[5:]) [1, 2, 4]
a[5:] = [30, 35, 40]
Python Tuple
• Tuple is an ordered sequence of items same as list. The only difference is
that tuples are immutable. Tuples once created cannot be modified.
• Tuples are used to write-protect data and are usually faster than list as it
cannot change dynamically.
• It is defined within parentheses () where items are separated by commas.
t = (5,'program', 1+3j)
• The slicing operator [] can be used to extract items but their values cannot
be changed
>>>t = (5,'program', 1+3j)
>>>print("t[1] = ", t[1])
t[1] = program
>>>print("t[0:3] = ", t[0:3])
t[0:3] = (5, 'program', (1+3j))
# Generates error since Tuples are immutable
>>>t[0] = 10
 Error: 'tuple' object does not support item assignment
Python Strings
• String is sequence of Unicode characters. We can use
single quotes or double quotes to represent strings.
>>>s = 'Hello world!’
>>>print("s[4] = ", s[4])
 s[4] = o
>>>print("s[6:11] = ", s[6:11])
 s[6:11] = world
# Generates error
# Strings are immutable in Python
>>>s[5] ='d‘
 TypeError: 'str' object does not support item
assignment
Python Set
• Set is an unordered collection of unique items. Set is defined by values
separated by comma inside braces { }. Items in a set are not ordered.
>>>a = {5,2,3,1,4}
>>>print("a = ", a)
 a = {1, 2, 3, 4, 5}
>>>print(type(a))
 <class 'set'>
• Set have unique values. They eliminate duplicates.
>>> a = {1,2,2,3,3,3}
>>>print( )a
{1, 2, 3}
• Since, set are unordered collection, indexing has no meaning. Hence the
slicing operator [] does not work.
Python Dictionary
• Dictionary is an unordered collection of key-value pairs.
• It is generally used when we have a huge amount of data. Dictionaries are
optimized for retrieving data. We must know the key to retrieve the value.
• In Python, dictionaries are defined within braces {} with each item being a
pair in the form key:value. Key and value can be of any type.
• We use key to retrieve the respective value. But not the other way around.
>>>d = {1:'value','key':2}
>>>print(type(d))
<class 'dict'>
>>>print("d[1] = ", d[1]);
d[1] = value
>>>print("d['key'] = ", d['key']);
d['key'] = 2
# Generates error
>>>print("d[2] = ", d[2]);
 KeyError: 2
Conversion between datatypes
• We can convert between different data types by using different type
conversion functions like int(), float(), str() etc.
>>> float(5)
5.0
• Conversion from float to int will truncate the value (make it closer to zero).
>>> int(10.6)
10
>>> int(-10.6)
-10
• Conversion to and from string must contain compatible values.
>>> float('2.5')  String to float conversion
2.5
>>> str(25)  Integer to string conversion
'25'
>>> int('1p')
ValueError: invalid literal for int() with base 10: '1p'
Conversion between datatypes
• We can even convert one sequence to another.
>>> set([1,2,1,3,3])  List to Set
{1, 2, 3}
>>> tuple({5,6,7})  Set to tuple
(5, 6, 7)
>>> list('hello')  String to List
['h', 'e', 'l', 'l', 'o']

• To convert to dictionary, each element must be a pair


>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
Variables
• A variable is a name that refers to a value.
• The assignment statement creates new variables and gives them values.

>>> message = "What's up, Doc?" 


>>> n = 17 
>>> pi = 3.14159 
• The type of a variable is the type of the value it refers to.

>>> type(message) 
<type 'str'> 
• The underscore character (_) can appear in a name. It is often used in
names with multiple words, such as my_name or price_of_tea_in_china.
Contd…
• Variable names can be arbitrarily long. They can contain both letters and
numbers, but they have to begin with a letter.
• If uppercase letters are used, remember case matters. A and a are
different variables.
• If you give a variable an illegal name, you get a syntax error:

>>> 76trombones = 'big parade' 


SyntaxError: invalid syntax
• Keywords define the language's rules and structure, and they cannot be
used as variable names
Expressions
• An expression is a combination of values, variables, and operators.

>>> x=2+3
>>> message = 'Hello, World!'
• When the Python interpreter displays the value of an expression, it uses the same
format you would use to enter a value. In the case of strings, that means that it
includes the quotation marks.
• But if you use a print statement, Python displays the contents of the string without
the quotation marks.
>>> message 
'Hello, World!' 
>>> print message 
Hello, World!
Operators and Operands
• Operators are special symbols that represent computations like addition
and multiplication.

• The values the operator uses are called as operands.

• Some of the operands are

+  addition

-  subtraction

*  multiplication
/  division

**  exponentiation
Order of operations
• When more than one operator appears in an expression, the order of
evaluation depends on the rules of precedence.
• Python follows the same precedence rules for its mathematical operators
that mathematics does.
• The acronym PEMDAS is a useful way to remember the order of
operations.
• Parentheses have the highest precedence and can be used to force an
expression to evaluate in the order you want. Since expressions in
parentheses are evaluated first, 2 * (3-1) is 4.
• Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4
• Multiplication and Division have the same precedence, which is higher
than Addition and Subtraction, which also have the same precedence.
So 2*3-1 yields 5 rather than 4, and 2/3-1 is -1, not 1
• Operators with the same precedence are evaluated from left to right. So in
the expression minute*100/60, the multiplication happens first,
yielding 5900/60, which in turn yields 98.
String Operations
• In general, mathematical operations can not be performed on
strings, even if the strings look like numbers. The following are
illegal (assuming that message has type string):
message-1   'Hello'/123   message*'Hello'   '15'+2 
• Interestingly, the + operator does work with strings. For strings,
the + operator represents concatenation, which means joining
the two operands by linking them end-to-end. Execute the
following:
>>>fruit = 'banana' 
>>>baked= ' nut bread' 
>>>print (fruit + baked) 
• The * operator also works on strings; it performs repetition. For
example, 'Fun'*3 is 'FunFunFun'. One of the operands has to be a
string; the other has to be an integer.
String Operations
• ‘len’ command is used to find the length of a string
>>>astring = “Hello world!”
>>>print(len(astring))
• To find the index of a particular alphabet
>>>print(astring.index("o"))
• To count the number of times an alphabet occurs in a string
>>>print(astring.count("l"))
• To print a slice of string
>>>print(astring[3:7])
• To print a slice of string by skipping one character
>>>print(astring[3:9:2])
• To print uppercase or lowercase
>>>print(astring.upper())
>>>print(astring.lower())
Complex Number Operations
>>>x=4+5j
• To print the real and imaginary parts:
>>>print(x.real)
>>>print(x.imag)
• To find the magnitude of the complex number
>>>m=abs(x)
• To find the phase of the complex number, we can use phase() function in
the cmath library
>>>import cmath
>>>p=cmath.phase(x)
• For rectangular to polar form conversion and vice-versa, we cae use
functions from cmath library
>>>import cmath
>>>w=cmath.polar(x)
List Operations
append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of number of items passed as an argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
Set Operations
>>>my_set = {1,3}
>>>my_set.add(2)
>>>print(my_set)
>>>my_set.update([3,4,5],{5,6,7,8})
>>>print(my_set)
>>>my_set.remove(6)
>>>print(my_set)

| for union. Input : A = {0, 2, 4, 6, 8}


B = {1, 2, 3, 4, 5}
& for intersection. Output :
– for difference Union : [0, 1, 2, 3, 4, 5, 6, 8]
^ for symmetric difference Intersection : [2, 4]
Difference : [8, 0, 6]
Symmetric difference : [0, 1,
3, 5, 6, 8]
THANK YOU

You might also like