0% found this document useful (0 votes)
5 views46 pages

Day 2

Uploaded by

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

Day 2

Uploaded by

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

Python Programming

Sunbeam Infotech www.sunbeaminfo.com


Data Types
-

Sunbeam Infotech www.sunbeaminfo.com


Need of Data Types

É==
§ 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

Sunbeam Infotech www.sunbeaminfo.com


Python Data Types

Data Types
=

① ② ③ ④ ⑤
Numeric Dictionary Boolean Sequence Set
= ← = ←

se

II
Integer ① Integer
Cleo list

Float Tuple
Float ② Geo

Complex
Geeeeo string et
Complex

Sunbeam Infotech www.sunbeaminfo.com


Literals

§ Literal is a raw data given in a variable or constant

§ 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 [: ]
"
" " "

§ We can use both single, double, or triple quotes for a string


§ E.g., name = “steve” or name = ‘steve’

Sunbeam Infotech www.sunbeaminfo.com


Literals

§ 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

Sunbeam Infotech www.sunbeaminfo.com


Type Hinting

§ 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

Sunbeam Infotech www.sunbeaminfo.com


Type Conversion

§ The process of converting the value of one data type (integer, string, float, etc.) to another data type is
called type conversion -

§ Python has two types of type conversion.


§ Implicit Type Conversion
§ Python automatically converts one data type to another data type

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)

Sunbeam Infotech www.sunbeaminfo.com


Type Conversion

§ 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

Sunbeam Infotech www.sunbeaminfo.com


0
Operators

Sunbeam Infotech www.sunbeaminfo.com


Operators

§ 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

Sunbeam Infotech www.sunbeaminfo.com


Arithmetic Operators

Operator Meaning Example

+ Add two operands or unary plus x+y+2


÷ - Subtract right operand from the left or unary minus x–y
v0
* Multiply two operands x*y

%
/ Divide left operand by the right one (always results into float) x/y

% Modulus - remainder of the division of left operand by the right x%y

Floor division - division that results into whole number adjusted to

÷
// x // y
the left in the number line

** Exponent - left operand raised to the power of right x**y

Sunbeam Infotech www.sunbeaminfo.com


Comparison operators
-

Operator Meaning Example

>
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

Greater than or equal to - True if left operand is greater than or


>=
O x >= y
equal to the right

Less than or equal to - True if left operand is less than or equal to


<=
O x <= y
the right

Sunbeam Infotech www.sunbeaminfo.com


Logical operators

Operator Meaning Example

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 =

the false false


" "" "" e

False Tree Tree


Passe tree false

false false
false false false
False

Sunbeam Infotech www.sunbeaminfo.com


Assignment Operators

Operator Meaning Example Operator Meaning Example

= x=5 x=5 **=


0 x **= 5 x = x ** 5

+= 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 <<= x <<= 5 x = x << 5

//= x //= 5 x = x // 5

Sunbeam Infotech www.sunbeaminfo.com


Bitwise operators

F
Operator Meaning Example

& Bitwise AND x & y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x >> 2 = 2 (0000 0010)

<< Bitwise left shift x << 2 = 40 (0010 1000)

Sunbeam Infotech www.sunbeaminfo.com


Special operators
-

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

Sunbeam Infotech www.sunbeaminfo.com


Membership Operators

Operator Meaning Example

in True if value/variable is found in the sequence 5 in x

not in True if value/variable is not found in the sequence =


5 not in x

Sunbeam Infotech www.sunbeaminfo.com


Functions

Sunbeam Infotech www.sunbeaminfo.com


Functions

§ In Python, a function is a group of related statements that performs a specific task


§ Functions help break our program into smaller and modular chunks
-

§ 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 : )
"

g- """docstring""" gun, , man .


= man ,

)
"

print (# carcanet { result }


statement(s)
=

body

define

Sunbeam Infotech www.sunbeaminfo.com


Docstrings

§ 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

Sunbeam Infotech www.sunbeaminfo.com


%
¥•
parameters

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"
=

value = tic , Pointcvauee : → +

print ( value
)→°oM÷e-
default value

Sunbeam Infotech www.sunbeaminfo.com


Function Types

§ Functions can divided into following two types:


§ Built-in functions
§ Functions that readily come with Python are called built-in functions
§ If we use functions written by others in the form of library, it can be termed as library functions
§ E.g., str(), int(), float() etc.

§ User defined functions


§ Functions that we define ourselves to do certain specific task are referred as user-defined functions
§ User-defined functions help to decompose a large program into small segments which makes program
easy to understand, maintain and debug
§ If repeated code occurs in a program. Function can be used to include those codes and execute when
needed by calling that function.
§ Programmers working on large project can divide the workload by making different functions

Sunbeam Infotech www.sunbeaminfo.com


Scope of variables

§ Scope of a variable is the portion of a program where the variable is recognized


§ Parameters and variables defined inside a function are not visible from outside the function. Hence,
they have a local scope.
§ The lifetime of a variable is the period throughout which the variable exists in the memory
§ The lifetime of variables inside a function is as long as the function executes
§ They are destroyed once we return from the function. Hence, a function does not remember the value
of a variable from its previous calls.

Sunbeam Infotech www.sunbeaminfo.com


Global Scope

§ 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()

Sunbeam Infotech www.sunbeaminfo.com


Local Scope

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)

Sunbeam Infotech www.sunbeaminfo.com


Global Keyword

§ 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

Sunbeam Infotech www.sunbeaminfo.com


Nested Function
E-

§ Function within a function is called as nested function or inner function or


- -
local function
§ E.g.

def outer():
print(“inside outer”)
def inner():
print(”inside inner”)
inner()

outer()
# error
inner()

Sunbeam Infotech www.sunbeaminfo.com


Anonymous/Lambda Function

§ In Python, an anonymous function is a function that is defined without a name


§ While normal functions are defined using the def keyword in Python, anonymous functions are defined
using the lambda keyword
§ -
Hence, anonymous functions are also called lambda functions
§ Syntax
§ lambda arguments: expression

=€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

Sunbeam Infotech www.sunbeaminfo.com


Collections

Sunbeam Infotech www.sunbeaminfo.com


collections

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

Sunbeam Infotech www.sunbeaminfo.com


List - functions

§ 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()
-

§ sort items in a list in ascending order


§ remove()
§ removes an item from the list § reverse()
§ reverse the order of items in the list
§ pop()
← § copy()
§ returns and removes an element at the given
§ returns a shallow copy of the list
off
index
§
✓ clear()
-

§ removes all items from the list

Sunbeam Infotech www.sunbeaminfo.com


Accessing List Members

§ We can use the index operator [] to access an item in a list


§ In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4
§ Trying to access indexes other than these will raise an IndexError
§ The index must be an integer. We can't use float or other types, this will result in TypeError
§ Negative indexing
§ Python allows negative indexing for its sequences
§ The index of -1 refers to the last item, -2 to the second last item and so on

Sunbeam Infotech www.sunbeaminfo.com


numbers = [ 10,20 , 30,40 , ]
50

→ 0 I 5 3 4

☒ ☒ 17¥67

G -
3 - 2 -
I
=

index = length -
( negative index

numbers f- 3] = numbers [5-3]


numbers Co ] = 10 2-
numbers [a] I 50
List Slicing

§ We can access a range of items in a list by using the slicing operator

=
my_list = ['p','r','o','g','r','a','m','i','z']

# elements from index 2 to index 4


print(my_list[2:5])

# elements from index 5 to end


print(my_list[5:])

# elements beginning to end


print(my_list[:])

Sunbeam Infotech www.sunbeaminfo.com


Tuple
=

-
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

Sunbeam Infotech www.sunbeaminfo.com


Tuple Operations

§ 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

Sunbeam Infotech www.sunbeaminfo.com


Set

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

Sunbeam Infotech www.sunbeaminfo.com


Set Operations

§ Union of two Sets


§ Intersection of two sets
§ Difference between the two sets
§ Frozenset
§ Symmetric Difference of two sets

Sunbeam Infotech www.sunbeaminfo.com


00
10 30
10 30 50
20 10 30 50
¢0
20 4°
30 50 60 20 40 go
40 6-0
sin S2 sznst
S2
81
intersection

= { 30,40 }

50 10 30 50
10 30

40
20 40 GO 20 60

30 50
10 30 50
2° 40
52 U SO 20 40 Go
60
si v82

union sets
of S2 -
Sj
SI - S2

= { 10,20 , 30,40 , 50,60 } { 10,20 } { 50,60 }


Dictionary

§ Python Dictionary is used to store the data in a key-value pair format


§ The dictionary is the data type in Python, which can simulate the real-life data arrangement where
some specific value exists for some particular key
§ It is the mutable data-structure
§ The dictionary is defined into element Keys and values
§ Keys must be a single element
§ Value can be any type such as list, tuple, integer, etc.
§ In other words, we can say that a dictionary is the collection of key-value pairs where the value can be
any Python object

Sunbeam Infotech www.sunbeaminfo.com


Persons tring

Perton "
}
" "
" "

{ age":Ñ
name :
values
key
"

→ int
" "

bobbies : E
?
reading books
"

movies ?
watching
"

]
Dictionary Operations

§ Creating the dictionary

:#
§ Accessing the dictionary values
§ Adding dictionary values
§ Deleting elements using del keyword

Sunbeam Infotech www.sunbeaminfo.com


prime
-

* positive ✗

1
① is divisible
by →

itself
② number is divisible
by

]
* negative
=
-

① number is not divisible by any other number

-
steps

① start from 2 till the @ umber -

1)
input
② check if
every
number is
dividing the

[input%number==#

You might also like