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

S2 Python Datatypes (2) 2sect

The document provides an overview of various data types in Python, including Numbers, Lists, Tuples, Strings, Sets, Dictionaries, and Booleans. It explains the characteristics, methods, and functions associated with each data type, as well as type conversion and practical assignments for demonstration. Additionally, it includes example code snippets to illustrate the usage of these data types and their methods.

Uploaded by

paulemma2020
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

S2 Python Datatypes (2) 2sect

The document provides an overview of various data types in Python, including Numbers, Lists, Tuples, Strings, Sets, Dictionaries, and Booleans. It explains the characteristics, methods, and functions associated with each data type, as well as type conversion and practical assignments for demonstration. Additionally, it includes example code snippets to illustrate the usage of these data types and their methods.

Uploaded by

paulemma2020
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Python

Python Datatypes

Every value in Python has a datatype. Since everything is an object in


Python programming, data types are actually classes and variables
are instance (object) of these classes.
Python Datatypes
Python Numbers

• Integers, floating point numbers and complex numbers fall


under Python numbers category.
• They are defined as int, float and complex classes in Python.
• We can use the type() function to know which class a variable or a
value belongs to.
• isinstance() function is used to check if an object belongs to a
particular class.
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 [ ].
Functions of List
SN Function Description Example

1 cmp(list1, It compares the elements of both the This method is not used in the Python 3 and the above
list2) lists. versions.

2 len(list) It is used to calculate the length of the L1 = [1,2,3,4,5,6,7,8]


list. print(len(L1))
8

3 max(list) It returns the maximum element of the L1 = [12,34,26,48,72]


list. print(max(L1))
72

4 min(list) It returns the minimum element of the L1 = [12,34,26,48,72]


list. print(min(L1))
12

5 list(seq) It converts any sequence to the list. str = "Johnson"


s = list(str)
print(type(s))
<class list>
List Methods

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position


pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list


sort() Sorts the list
Python Tuple

Tuple is an ordered sequence of items same as a 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 lists
as they cannot change dynamically.
It is defined within parentheses () where items are separated by
commas.
Tuple Methods

Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of
where it was found
Python String

String is sequence of Unicode characters. We can use single quotes


or double quotes to represent strings. Multi-line strings can be
denoted using triple quotes, ''' or """.
String Methods
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
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.
• We can perform set operations like union, intersection on two
sets. Sets have unique values. They eliminate duplicates.
• Sets can be created by using the built-in set() function with an
iterable object or a sequence by placing the sequence inside curly
braces, separated by ‘comma’.
• Type of elements in a set need not be the same, various mixed-up
data type values can also be passed to the set.
Set Methods
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two or more sets
intersection_update() Removes the items in this set that are not present in other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
update() Update the set with another set, or any other iterable
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.
Creating Dictionary

Creating Dictionary
In Python, a Dictionary can be created by placing a sequence of
elements within curly {} braces, separated by ‘comma’. Values in a
dictionary can be of any datatype and can be duplicated, whereas
keys can’t be repeated and must be immutable. Dictionary can also
be created by the built-in function dict(). An empty dictionary can be
created by just placing it to curly braces{}.
Accessing elements of
Dictionary

In order to access the items of a dictionary refer to its key name. Key
can be used inside square brackets. There is also a method
called get() that will also help in accessing the element from a
dictionary.
Dictionary Methods

Method Description
clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary


fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key


items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair


setdefault() Returns the value of the specified key. If the key does not exist: insert the key,
with the specified value
update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary


Python Boolean

• Data type with one of the two built-in values, True or False.
• Boolean objects that are equal to True are truthy (true), and those
equal to False are falsy (false).
• It is denoted by the class bool.

Note – True and False with capital ‘T’ and ‘F’ are valid booleans
otherwise python will throw an error.
Python Datatypes
Data type conversion

We can convert between different data types by using different


type conversion functions like int(), float(), str(), etc.
Assignments:

1. Write a python code to demonstrate type function to know


which class a variable or a value belongs to.
2. Write a Python program to get the 4th element from the last
element of a tuple.
3. Write a Python program to demonstrate use of count() and
return the number of times an element appears in the tuple.
4. Write a Python program to calculate your age.
Content Covered

• Datatypes
Python Numbers
Python List
Tuple
String
Set
Dictionary
• Type Conversion
Solution 1

num1 = 5
print(num1, 'is of type', type(num1))

num2 = 2.0
print(num2, 'is of type', type(num2))

num3 = 1+2j
print(num3, 'is of type', type(num3))
Solution 2

#Get an item of the tuple


tuplex = (“r", 5, “y", "em", "o", “t", "u", “p", "c", "e")
print(tuplex)
#Get item (4th element)of the tuple by index
item = tuplex[3]
print(item)
#Get item (4th element from last)by index negative item1 = tuplex[-
4] print(item1)
Solution 3

#create a tuple
tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7
print(tuplex)
#return the number of times it appears in the tuple.
count = tuplex.count(4)
print(count)
Solution 4

birth_year='1988'
a=int(birth_year)
current_year=2023
print(current_year-a)

age=current_year-a
print(age)
print('I am', age ,'years old')
Thank You

You might also like