0% found this document useful (0 votes)
32 views33 pages

Data Type in Python

This document summarizes the main data types in Python including text, numeric, sequence, mapping, and boolean types. It provides examples of how to use integers, floats, complex numbers, strings, lists, tuples, dictionaries, and sets in Python. It demonstrates how to create, access, modify, loop through and add/remove items from these fundamental Python data types.

Uploaded by

hothyfa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
32 views33 pages

Data Type in Python

This document summarizes the main data types in Python including text, numeric, sequence, mapping, and boolean types. It provides examples of how to use integers, floats, complex numbers, strings, lists, tuples, dictionaries, and sets in Python. It demonstrates how to create, access, modify, loop through and add/remove items from these fundamental Python data types.

Uploaded by

hothyfa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 33

DATA TYPES IN PYTHON

STUDENT PREPARATION/ HOTHYFA AHMED ALFKEEH


D. E/Auad Almuhalfi
DATA TYPES IN PYTHON
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
Python Numbers
There are three numeric types in Python:
int,float,complex
Variables of numeric types are created when you assign a value to them:
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example. RESULT.
print(type(x)) <class 'int'>
print(type(y)) <class 'float'>
print(type(z)) <class 'complex'>
Int
Int, or integer, is a whole number, positive or negative, without
decimals, of unlimited length.
Float
Float, or "floating point number" is a number, positive or negative,
containing one or more decimals.
Complex
Complex numbers are written with a "j" as the imaginary par
Type Conversion
You can convert from one type to another with the int(), float(), and complex()
and str() methods:
Example
Convert from one type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x) #convert from float to int:
b = int(y) #convert from int to complex:
c = complex(x) print(a) print(b) print(c)
print(type(a)) print(type(b)) print(type(c))
Python Strings

String Literals
String literals in python are surrounded by either single quotation
marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
a = """Python is a programming language.
Python can be used on a server to create web applications..
"""
print(a)
Strings are Arrays
Like many other popular programming languages, strings in Python are
arrays of bytes representing unicode characters.
However, Python does not have a character data type, a single character
is simply a string with a length of 1.
Square brackets can be used to access elements of the string.
Get the character at position 1 (remember that the first character has the
position 0):
Example
a = "Hello, World!"
print(a[1])
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return
a part of the string.
Get the characters from position 2 to position 5 (not included):
Example. Result.
b = "Hello, World!" llo

print(b[2:5])
String Length
To get the length of a string, use the len() function.
a = "Hello, World!"
print(len(a))
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Python Lists
Python Collections (Arrays)
There are four collection data types in the Python programming
language:
List is a collection which is ordered and changeable. Allows duplicate
members.
Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
Set is a collection which is unordered and unindexed. No duplicate
members.
Dictionary is a collection which is unordered, changeable and indexed.
No duplicate members.
List
A list is a collection which is ordered and changeable. In Python lists are
written with square brackets.
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
Access Items
You access the list items by referring to the index number:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Range of Indexes
You can specify a range of indexes by specifying where to start and
where to end the range.
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
print(thislist[2:5])
This example returns the items from the beginning to "orange":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
print(thislist[:4])
This example returns the items from "cherry" and to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
print(thislist[2:])
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
The remove() method removes the specified item:
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
The pop() method removes the specified index, (or the last item if index
is not specified):

thislist = ["apple", "banana", "cherry"]


thislist.pop()
print(thislist)
The del keyword removes the specified index:

thislist = ["apple", "banana", "cherry"]


del thislist[0]
print(thislist)
Tuple
A tuple is a collection which is ordered and unchangeable. In Python
tuples are written with round brackets.
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Access Tuple Items
You can access tuple items by referring to the index number, inside
square brackets:
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Range of Indexes
You can specify a range of indexes by specifying where to start and
where to end the range.
When specifying a range, the return value will be a new tuple with the
specified items.
Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango")
print(thistuple[2:5])
Change Tuple Values
Once a tuple is created, you cannot change its values. Tuples are
unchangeable, or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change
the list, and convert the list back into a tuple.
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Result:
("apple", "kiwi", "cherry")
Set
A set is a collection which is unordered and unindexed. In Python sets
are written with curly brackets.
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Access Items

You cannot access items in a set by referring to an index, since sets are
unordered the items has no index.
But you can loop through the set items using a for loop, or ask if a
specified value is present in a set, by using the in keyword.
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Result: banana
cherry
apple
Change Items
Once a set is created, you cannot change its items, but you can add new
items.
Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method.
Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
Result:
{'orange', 'banana', 'apple', 'cherry'}

Add multiple items to a set, using the update() method:


thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)
Result:
{'mango', 'banana', 'apple', 'cherry', 'grapes', 'orange'}
Remove Item
To remove an item in a set, use the remove(), or the discard() method.

Remove "banana" by using the remove() method:


thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)

Remove "banana" by using the discard() method:


thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
Result:
set()
The del keyword will delete the set completely:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
Dictionary
A dictionary is a collection which is unordered, changeable and indexed.
In Python dictionaries are written with curly brackets, and they have
keys and values.
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Result:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Accessing Items
You can access the items of a dictionary by referring to its key name,
inside square brackets:
Get the value of the "model" key:
x = thisdict["model"]
Result:
Mustang
There is also a method called get() that will give you the same result:
Get the value of the "model" key:
x = thisdict.get("model")
Result:
Mustang
Change Values
You can change the value of a specific item by referring to its key name:
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Result:

{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}


Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well.
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Result:
brand
model
year
Adding Items
Adding an item to the dictionary is done by using a new index key and
assigning a value to it:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Result:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Removing Items
There are several methods to remove items from a dictionary:
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Result:
{'brand': 'Ford', 'year': 1964}
The popitem() method removes the last inserted item (in versions before
3.7, a random item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
Result:
{'brand': 'Ford', 'model': 'Mustang'}
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Result:
{'brand': 'Ford', 'year': 1964}
The clear() keyword empties the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
Result:
{}
Nested Dictionaries
A dictionary can also contain many dictionaries, this is called nested
dictionaries.
Create a dictionary that contain three dictionaries:
myfamily = {"child1" : {
"name" : "Emil",
"year" : 2004
},"child2" : {
"name" : "Tobias",
"year" : 2007
},"child3" : {
"name" : "Linus",
"year" : 2011}}
THANK YOU

You might also like