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

CTP - Introduction To Python Basics - Lect003

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

CTP - Introduction To Python Basics - Lect003

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

Computational thinking and Programming

(Introduction to basic Python)

Saurabh Singh
Department of AI & Big Data
Woosong University
2024/09/25
Python Data Types
• Python data types are actually classes, and the defined variables are
their instances or objects. Since Python is dynamically typed, the data
type of a variable is determined at runtime based on the assigned
value.
• In general, the data types are used to define the type of a variable. It
represents the type of data we are going to store in a variable and
determines what operations can be done on it.
• Each programming language has its own classification of data
items. With these datatypes, we can store different types of data
values.
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


None Type: NoneType
Python Numeric Data Types
• Python numeric data types store numeric values. Number objects are
created when you assign a value to them. For example −
var1 = 1 # int data
type var2 = True # bool data type
type(5+6j)
var3 = 10.023 # float data type <class 'complex'>
var4 = 10+3j # complex data type
# integer variable.
a=100
print("The type of variable having value", a, " is ", type(a))

# float variable.
c=20.345
print("The type of variable having value", c, " is ", type(c))

# complex variable. d=10+3j print("The type of variable having


value", d, " is ", type(d))
Python String Data Type
• Python string is a sequence of one or more Unicode characters, enclosed in single,
double or triple quotation marks (also called inverted commas). Python strings are
immutable which means when you perform an operation on strings, you always
produce a new string object of the same type, rather than mutating an existing
string.
type("Welcome To the Woosong University")
<class 'str'>

• A string is a non-numeric data type. Obviously, we cannot perform arithmetic


operations on it. However, operations such as slicing and concatenation can be
done. Python's str class defines a number of useful methods for string processing.
Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes
starting at 0 in the beginning of the string and working their way from -1 at the end.
• The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator in Python.
Ex.

str = 'Hello World!’

print (str) # Prints complete string


print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
String operations
• >>> first = 10
• >>> second = 15
• >>> print(first+second)
• 25
• >>> first = '100‘
• >>> second = '150'
• >>> print(first + second)
• 100150
• The + operator works with strings, but it is not addition in the mathematical sense.
• Instead it performs concatenation, which means joining the strings by linking them end
to end. For example
String operations
• The * operator also works with strings by multiplying the content of a
string by an integer. For example:
• >>> first = 'Test '
• >>> second = 3
• >>> print(first * second)
• Test Test Test
Python Sequence Data Types
• Sequence is a collection data type. It is an ordered collection of items.
Items in the sequence have a positional index starting with 0. It is
conceptually similar to an array in C or C++. There are following three
sequence data types defined in Python.
• List Data Type
• Tuple Data Type
• Range Data Type
(a) Python List Data Type
• Python Lists are the most versatile compound data types. A Python list
contains items separated by commas and enclosed within square
brackets ([]).
type([2023, "Python", 3.11, 5+6j, 1.23E-4])

• an item in the list may be of any data type. It means that a list object
can also be an item in another list. In that case, it becomes a nested list.
• >>> [['One', 'Two', 'Three'], [1,2,3], [1.0, 2.0, 3.0]]
• The values stored in a Python list can be accessed using the slice
operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list
and working their way to end -1. The plus (+) sign is the list
concatenation operator, and the asterisk (*) is the repetition operator.
Example of List Data Type
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
b)Python Tuple Data Type
• Python tuple is another sequence data type that is similar to a list. A Python tuple
consists of a number of values separated by commas. Unlike lists, however, tuples
are enclosed within parentheses (...).
• A tuple is also a sequence, hence each item in the tuple has an index referring to
its position in the collection. The index starts from 0.
>>> (2023, "Python", 3.11, 5+6j, 1.23E-4)
• In Python, a tuple is an object of tuple class. We can check it with the type()
function.

• To form a tuple, use of parentheses is optional. Data items separated by comma


without any enclosing symbols are treated as a tuple by default.
>>> 2023, "Python", 3.11, 5+6j, 1.23E-4
(2023, 'Python', 3.11, (5+6j), 0.000123)
Example of Tuple data Type
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints the complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd
print (tuple[2:]) # Prints elements of the tuple starting from 3rd element
print (tinytuple * 2) # Prints the contents of the tuple twice
print (tuple + tinytuple) # Prints concatenated tuples
Difference b/w tuple and list
• The main differences between lists and tuples are: Lists are enclosed
in brackets ( [ ] ) and their elements and size can be changed i.e. lists
are mutable, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated (immutable). Tuples can be thought of as read-
only lists.
• The following code is invalid with tuple, because we attempted to
update a tuple, which is not allowed. Similar case is possible with lists

tuple = ( 'abcd', 786 , 2.23, 'john',
70.2 ) list = [ 'abcd', 786 , 2.23, 'john',
tuple = ( 'abcd', 786 , 2.23, 'john',
70.2 ] tuple[2] = 1000 # Invalid syntax
70.2 ) list = [ 'abcd', 786 , 2.23, 'john',
with tuple list[2] = 1000 # Valid syntax
70.2 ] list[2] = 1000 # Valid syntax with
with list
list print(list)
(c) Python Range Data Type
• A Python range is an immutable sequence of numbers which is
typically used to iterate through a specific number of items.
• It is represented by the Range class. The constructor of this class
accepts a sequence of numbers starting from 0 and increments to 1
until it reaches a specified number. Following is the syntax of the
function −
>>>range(start, stop, step)
• start: Integer number to specify starting position, (Its optional,
Default: 0)
• stop: Integer number to specify ending position (It's mandatory)
• step: Integer number to specify increment, (Its optional, Default: 1)
Example of Range Data
Type
• Following is a program which uses for loop to print number from 0 to 4 −
for i in range(5):
print(i)

• Now let's modify above program to print the number starting from 2
instead of 0 −
for i in range(2, 5):
print(i)

Again, let's modify the program to print the number starting from 1 but with
an increment of 2 instead of 1:
for i in range(1, 5, 2):
print(i)
4. Python Binary Data Types
• A binary data type in Python is a way to represent data as a series of
binary digits, which are 0's and 1’s.
• This type of data is commonly used when dealing with things like files,
images, or anything that can be represented using just two possible
values. Either 0 or 1 or its combination
• Python provides three different ways to represent binary data. They
are as follows −
• bytes
• bytearray
• memoryview
(a) Python Bytes Data Type
• The byte data type in Python represents a sequence of bytes. Each
byte is an integer value between 0 and 255. It is commonly used to
store binary data, such as images, files, or network packets.
• We can create bytes in Python using the built-in bytes() function or by
prefixing a sequence of numbers with b
• we are using the built-in bytes() function to explicitly specify a
sequence of numbers representing ASCII values −
# Using bytes() function to create bytes
b1 = bytes([65, 66, 67, 68, 69])
print(b1)

ASCII table - Table of ASCII codes, characters and symbols (ascii-


code.com)
(b) Python Bytearray Data Type
• The bytearray data type in Python is quite similar to the bytes data type, but with one key
difference: it is mutable, meaning you can modify the values stored in it after it is created.
# Creating a bytearray from an iterable of integers
value = bytearray([72, 101, 108, 108, 111])
print(value)
You can create a bytearray using various methods, including by passing an iterable of integers
representing byte values, by encoding a string, or by converting an existing bytes or bytearray
object.
Now, we are creating a bytearray by encoding a string using a "UTF-8" encoding −

# Creating a bytearray by encoding a string


val = bytearray("Hello", 'utf-8’)
print(val)

o/p= bytearray(b'Hello')
(c) Python Memoryview Data Type
• In Python, a memoryview is a built-in object that provides a view into the memory of the original object,
generally objects that support the buffer protocol, such as byte arrays (bytearray) and bytes (bytes).
• It helps providing efficient memory access for large datasets.
• These methods include using the memoryview() constructor,
Ex.
data = bytearray(b'Hello, world!’)
view = memoryview(data)
print(view)

Ex.

x = bytearray(5)
print(x)
x = memoryview(bytes(5))
print(x)
5. Python Dictionary Data Type
• A dictionary key can be almost any Python type, but are usually
numbers or strings.
• Python dictionary is like associative arrays or hashes found in Perl and
consist of key:value pairs.
• The pairs are separated by comma and put inside curly brackets {}.
• To establish mapping between key and value, the semicolon':' symbol
is put between the two.
>>> {1:'one', 2:'two', 3:'three’}
>>> type({1:'one', 2:'two', 3:'three’})
<class 'dict'>
Example of Dictionary Data Type
• Dictionaries are enclosed by curly braces ({ }) and values
can be assigned and accessed using square braces ([]).
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two“
tinydict = {'name': 'john','code':6734, 'dept': 'sales’}

print (dict['one’]) # Prints value for 'one' key


print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
o/p
print (tinydict.keys()) # Prints all the keys This is one
This is two
print (tinydict.values()) # Prints all the values {'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
• Python's dictionary is not a sequence. It is a collection of items but
each item (key:value pair) is not identified by positional index as in
string, list or tuple. Hence, slicing operation cannot be done on a
dictionary.
• Dictionary is a mutable object, so it is possible to perform add, modify
or delete actions with corresponding functionality defined in dict
class.
Quiz

• If x = 5, what is a correct syntax for printing the data type of the


variable x?
a. print(dtype(x))
b. print(type(x))
c. print(x.dtype())
• Thank you

You might also like