Day 2
Day 2
É==
§ Data type is an attribute associated with a piece of data that tells a computer system how to interpret
its value
§ Understanding data types ensures that data is collected in the preferred format and the value of each
property is as expected
§ It helps to know what kind of operations are often performed on a variable
Data Types
=
① ② ③ ④ ⑤
Numeric Dictionary Boolean Sequence Set
= ← = ←
se
II
Integer ① Integer
Cleo list
Float Tuple
Float ② Geo
Complex
Geeeeo string et
Complex
§ Numeric Literals
§ Numeric Literals are immutable (unchangeable)
§ Numeric literals can belong to 3 different numerical types:
§ Integer (value = 100)
§ Float (salary = 15.50)
§ Complex (x = 10 + 5j)
§ String literals
¥
§ A string literal is a sequence of characters surrounded by quotes [: ]
"
" " "
§ Boolean literals
←
§ A Boolean literal can have any of the two values: True or False
§ E.g., can_vote = True or can_vote = False
to ☐ an
§ Special literal
§ Python contains one special literal i.e. None
§ We use it to specify that the field has not been created
§ E.g., value = None
§ Literal Collections
§ Used to declare variables of collection types
§ There are four different literal collections List literals, Tuple literals, Dict literals, and Set literals
IF I
§ Due to the dynamic nature of Python, inferring or checking the type of an object being used is
especially hard
§ This fact makes it hard for developers to understand what exactly is going on in code they haven't
written. As a result they resort to trying to infer the type with around 50% success rate.
§ Why type hints?
§ Helps type checkers: By hinting at what type you want the object to be the type checker can easily detect if,
for instance, you're passing an object with a type that isn't expected
§ Helps with documentation: A third person viewing your code will know what is expected where, ergo, how
to use it without getting them TypeErrors
§ Helps IDEs develop more accurate and robust tools: Development Environments will be better suited at
suggesting appropriate methods when know what type your object is
§ The process of converting the value of one data type (integer, string, float, etc.) to another data type is
called type conversion -
n-F-g.mg?-#g.,,ai..
§ This process doesn't need any user involvement
§ E.g.
§ result = 10 + 35.50
§ Explicit Type Conversion
§ Users convert the data type of an object to required data type
§ We use the predefined functions like int(), float(), str(), etc to perform explicit type conversion
§ E.g. . . .
§ num_str = str(1024)
§ Type Conversion is the conversion of object from one data type to another data type
§ Implicit Type Conversion is automatically performed by the Python interpreter
§ Python avoids the loss of data in Implicit Type Conversion
§ Explicit Type Conversion is also called Type Casting, the data types of objects are converted using
predefined functions by the user
§ In Type Casting, loss of data may occur as we enforce the object to a specific data type
§ Operators are special symbols in Python that carry out arithmetic or logical computation
§ The value that the operator operates on is called the operand
§ Types
§ Arithmetic operators
§ Comparison operators
§ Logical operators
§ Bitwise operators
§ Special operators
§ Membership operators
%
/ Divide left operand by the right one (always results into float) x/y
÷
// x // y
the left in the number line
>
O Greater than - True if left operand is greater than the right x>y
<
O Less than - True if left operand is less than the right x<y
==
O Equal to - True if both operands are equal x == y
!=
O Not equal to - True if operands are not equal x != y
0
and True if both the operands are true x and y
0
or True if either of the operands is true x or y
0
not True if operand is false (complements the operand) not x
Traedfatse
And
=
Tnue = false
not
e) e)
True
/ |
True True
True True True True
not false =
false false
false false false
False
+= x += 5 x=x+5 0
&= x &= 5 x=x&5
-= x -= 5 x=x-5 o
|= x |= 5 x=x|5
0
*= x *= 5 x=x*5 0
^= x ^= 5 x=x^5
8☒¥
/= x /= 5 x=x/5 >>= x >>= 5 x = x >> 5
//= x //= 5 x = x // 5
F
Operator Meaning Example
is True if the operands are identical (refer to the same object) x is True
-
is not
True if the operands are not identical (do not refer to the same
object) =
x is not
True
§ As our program grows larger and larger, functions make it more organized and manageable
§ Furthermore, it avoids repetition and makes the code reusable
§ Syntax # function declaration / definition
def function C) '
m=Numentes nl :
"
)
def function_name(parameters): n2== Number C
"
enter n2 : )
"
)
"
body
define
§ The first string after the function header is called the docstring and is short for documentation string
§ It is briefly used to explain what a function does
§ Although optional, documentation is a good programming practice
§ We generally use triple quotes so that docstring can extend up to multiple lines
§ This string is available to us as the __doc__ attribute of the function
Jn\
non-oetu-ni.mg returning
Returning a value
§ The return statement is used to exit a function and go back to the place from where it was called
=
§ This statement can contain an expression that gets evaluated and the value is returned
§ If there is no expression in the statement or the return statement itself is not present inside a function,
-
T
then the function will return the None object
IÉÉÉn returns None
# int
|
def Square (n ) :
bum = 100
oetuonkx-xtzpnntCPI.PH
def ft ( P ! P2 ) :
# None Type
value =
square [
" " "
O"
=
print ( value
)→°oM÷e-
default value
§ In Python, a variable declared outside of the function or in global scope is known as a global variable
§ This means that a global variable can be accessed inside or outside of the function
g_var = "global"
def foo():
print(“inside foo”)
print(g_var)
foo()
F-t-cfs.pe
§ A variable declared inside the function's body or in the local scope is known as a local variable
def foo():
local_var = "local"
foo()
→
# error ✗
print(local_var)
§ In Python, global keyword allows you to modify the variable outside of the current scope
§ It is used to create a global variable and make changes to the variable in a local context
§ Rules of global Keyword
§ When we create a variable inside a function, it is local by default
§ When we define a variable outside of a function, it is global by default. You don't have to use global keyword
§ We use global keyword to read and write a global variable inside a function
§ Use of global keyword outside a function has no effect
the variable
c-
declare
nun
global
20° variable
num =
local scoped
f- I C)
# 200
( nun)
print
def outer():
print(“inside outer”)
def inner():
print(”inside inner”)
inner()
outer()
# error
inner()
=€im÷m
§ Characteristics
§ It can only contain expressions and can’t include statements in its body
§ It is written as a single line of execution
§ It does not support type annotations hinting )
§ It can be immediately invoked
ition①
① ② ③ ④
List
÷
§ Python lists are one of the most versatile data types that allow us to work with multiple elements at
once
-
§ For example
§ # a list of programming languages
§ ['Python', 'C++', 'JavaScript’]
§ List is created by placing elements inside square brackets [], separated by commas
- -
-
§ List is mutable
§ append() § index()
¥
§ adds an element to the end of the list § returns the index of the first matched item
§ extend() § count()
§ adds all elements of a list to another list § returns the count of the number of items passed
as an argument
§ insert()
§ inserts an item at the defined index ✓ § sort()
-
→ 0 I 5 3 4
☒ ☒ 17¥67
•
G -
3 - 2 -
I
=
index = length -
( negative index
=
my_list = ['p','r','o','g','r','a','m','i','z']
-
I
§ A tuple is a collection of objects which ordered and immutable
updated
§ Tuples are sequences, just like lists can
NOT be
-
§ The differences between tuples and lists are
§ Tuples cannot be changed unlike lists
§ Tuples use parentheses, whereas lists use square brackets
ls =
[ ]
II.
append czo
:
)y€€
Mutable → can be updated
-
new values can be added
-
old values can be removed
§ Creating Tuples
§ Concatenation of Tuples multi
dimesiona
}
single
§ Nesting of Tuples (Tuple of Tuples) ×
dimensional
§ Repetition of Tuples
Émeat
( extracting] collection &
§ Packing and Unpacking ✓
collection
§ Indexing in Tuple ivpleq
§ Slicing in Tuple
( istq
Is
lists
✗
✓
lists
lists
tap,eq tuples
tuples
values
unique
§ A Python set is the collection of the unordered items of
§ Each element in the set must be unique
§ Sets are mutable which means we can modify it after its creation
§ Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we
cannot directly access any element of the set by the index
§ However, we can print them all together, or we can get the list of elements by looping through the set
= { 30,40 }
50 10 30 50
10 30
40
20 40 GO 20 60
1°
30 50
10 30 50
2° 40
52 U SO 20 40 Go
60
si v82
union sets
of S2 -
Sj
SI - S2
Perton "
}
" "
" "
{ age":Ñ
name :
values
key
"
→ int
" "
bobbies : E
?
reading books
"
movies ?
watching
"
]
Dictionary Operations
:#
§ Accessing the dictionary values
§ Adding dictionary values
§ Deleting elements using del keyword
* positive ✗
→
1
① is divisible
by →
✗
itself
② number is divisible
by
]
* negative
=
-
-
steps
1)
input
② check if
every
number is
dividing the
[input%number==#