Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

Python - Session1

The document discusses various features and concepts related to the Python programming language. It describes key aspects like Python's creator Guido Van Rossum, its characteristics as an interpreted, high-level and cross-platform language. It also covers Python tokens like keywords, identifiers, literals, operators and punctuators as well as popular Python IDEs.

Uploaded by

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

Python - Session1

The document discusses various features and concepts related to the Python programming language. It describes key aspects like Python's creator Guido Van Rossum, its characteristics as an interpreted, high-level and cross-platform language. It also covers Python tokens like keywords, identifiers, literals, operators and punctuators as well as popular Python IDEs.

Uploaded by

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

1

PYTHON FEATURES
 Guido Van Rossum is known as the founder of Python programming.
 Python is a simple easy to use, general-purpose, high-level programming
language.
 Expressive language
 Interpreted programming language.
 Cross-platform language.
 It’s a Free and Open Source language.
 Multipurpose programming language.

2
3
4
Popular Python IDEs
• IDE stands for Integrated Development Environment and is defined as a
coding tool that helps to automate the process of editing, compiling,
testing, etc.

• In an SDLC it provides ease to the developer to run, write and debug the
code.

• It is specially designed for software development that consists of several


tools which is used for developing and testing the software.

5
Popular Python IDEs

•PyCharm
•Spyder
•PyDev
•Atom
•Wing
•Jupyter Notebook
•Thonny
•Rodeo
•Microsoft Visual Studio
•Eric

6
Python Character Set

7
Tokens
 1. Keywords
 2. Identifiers (Names)
 3. Literals or Values
 4. Operators
 5. Punctuators

8
1. Keywords
 Keywords are words that have some special meaning or significance in a programming
language.
 They can’t be used as variable names, function names, or any other random purpose.
 They are used for their special features

9
2. Identifiers (Names)
 Identifiers are the names given to any variable, function, class, list, methods, etc. for their
identification.
 Python is a case-sensitive language and it has some rules and regulations to name an
identifier.
• Python is case-sensitive. So case matters in naming identifiers. And hence apple and Apple are two
different identifiers.
• Identifier starts with a capital letter (A-Z) , a small letter (a-z) or an underscore( _ ). It can’t start with any
other character.
• Except for letters and underscore, digits can also be a part of identifier but can’t be the first character of it.
• Any other special characters or whitespaces are strictly prohibited in an identifier.
• An identifier can’t be a keyword.

10
Activity : Pick the correct identifiers

 GFG
 Gfg
 gfg
 _DS
 FILE50
 HJ14_JK
 DATA-REC
 29CLCT
 Break
 My.file

11
3.Literals/values
Data items that have a fixed value.
 (i) String Literals
 (ii)Numeric Literals
 (iii)Boolean Literals
 (iv)Special Literal
 (v)Literal Collections

12
 (i) String Literals
The text written in single, double, or triple quotes represents the string literals in Python.
For example: “Computer Science”, ‘sam’, etc. We can also use triple quotes to write multi-line strings.

# String Literals
a = 'Hello'
b = "Geeks"
c = ‘‘NPTEL is a very good
learning platform'''

print(a) Text1 = 'welcome to\n


print(b) DON BOSCO School'
print(c) print(Text1)

13
(ii) Numeric Literals: These are the literals written in form of numbers.
Python supports the following numerical literals:
• Integer Literal: It includes both positive and negative numbers along with 0. It doesn’t
include fractional parts. It can also include binary, decimal, octal, hexadecimal literal.
• Float Literal: It includes both positive and negative real numbers. It also includes
fractional parts.
• Complex Literal: It includes a+bi numeral, here a represents the real part and b
represents the complex part.

14
Activity : Identify the correct literals
 1234
 41
 +97
 -17
 0o10
 0o28
 0o19
 0o987
 0XBK9
 2.0
 17.5
 -13.0
 +17/2
 17,250.26.2
 17,250.262

15
Activity : Identify the correct literals
Solution
 1234
 41
 +97
 -17
 0o10
 2.0
 17.5
 -13.0

16
 Boolean Literals – True / False

c = True + 10
print(c)

a = 10
b = (a==10)
print(b)

17
 Special Literals: Python has a special literal ‘None’. It is used to denote nothing, no
values, or the absence of value.

a = None
print(a)

18
 Literals Collections: Literals collections in python includes list, tuple, dictionary, and
sets.

1.List: It is a list of elements represented in square brackets with commas in between. These variables can be
of any data type and can be changed as well.
2.Tuple: It is also a list of comma-separated elements or values in round brackets. The values can be of any
data type but can’t be changed.
3.Dictionary: It is the unordered set of key-value pairs.
4.Set: It is the unordered collection of elements in curly braces ‘{}’.

19
4.Operators in Python

Operator: An operator is a symbol that specifies a specific action.


Operand: An operand is a data item on which the operator acts.

Some operators require two operands while others require only one.

20
Unary Operators

The + operator in Python can be utilized in a unary form.

print +3
print +3.0
print +3j

print -4
print -4.0
21
print -4j
Binary Operators
Arithmetic Operators

Ex-1
Ex-2
x = 15
y=2 x=5
y=2
print(x // y) 22

print(x % y)
#the floor division // rounds the result down to the nearest whole
Binary Operators
Arithmetic Operators

Ex-1 Solution: 7
x = 15
y=2

print(x // y)

#the floor division // rounds the result down to the nearest whole
number

Ex-2 Solution: 1

x=5
y=2

print(x % y)
23
Assignment Operators
Assignment operators are used to assign values to variables:

24
Exercise

x=5 x=5 x=5

x += 3 x -= 3 x /= 3

print(x) print(x) print(x)

25
Exercise

x=5 x=5 x=5

x += 3 x -= 3 x /= 3

print(x) print(x) print(x)

Solution : 2 Solution :1.66666666667


Solution : 8

26
Exercise (contd)

x=5 x=5 x=5 x=5

x%=3 x//=3 x **= 3 x *= 3


print(x) print(x)
print(x) print(x)

27
Exercise (contd)

x=5 x=5 x=5 x=5

x%=3 x//=3 x **= 3 x *= 3


print(x) print(x)
print(x) print(x)
Solution : 2 Solution : 1 Solution : 125 Solution : 15

28
Logical Operators
 Logical operators are used to combine conditional statements:

29
Exercise

x=5 x=5 x=5

print(x > 3 and x < 10) print(x > 3 or x < 4) print(not(x > 3 and x < 10))

30
Exercise

x=5 x=5 x=5

print(x > 3 and x < 10) print(x > 3 or x < 4) print(not(x > 3 and x < 10))

Solution : True Solution : False


Solution : True

31
Identity Operators
 Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location:

Ex- 1
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x

print(x is z)

print(x is y)

print(x == y) 32
Identity Operators
 Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location:

Ex- 1
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x Solution :

print(x is z) True

# returns True because z is the same object as x


False
True
print(x is y)

# returns False because x is not the same object as y, even if they have the same content

print(x == y)

# to demonstrate the difference betweeen "is" and "==": this comparison returns True 33
because x is equal to y
Ex- 2

x = ["apple", "banana"]
y = ["apple", "banana"]
z=x

print(x is not z)

# returns False because z is the same object as x

print(x is not y)

# returns True because x is not the same object as y, even if they have the same
content

print(x != y)

# to demonstrate the difference betweeen "is not" and "!=": this comparison returns
False because x is equal to y

34
x = ["apple", "banana"]
y = ["apple", "banana"] Solution :
z=x
False
print(x is not z) True
False
# returns False because z is the same object as x

print(x is not y)

# returns True because x is not the same object as y, even if they have the same
content

print(x != y)

# to demonstrate the difference betweeen "is not" and "!=": this comparison returns
False because x is equal to y

35
Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Ex:

x = ["apple", "banana"]

print("banana" in x)

# returns True because a sequence with the value "banana" is in the list

36
Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Ex:1

x = ["apple", "banana"]
Solution :
print("banana" in x) True

# returns True because a sequence with the value "banana" is in the list

37
Ex:2

x = ["apple", "banana"]

print("pineapple" not in x)

# returns True because a sequence with the value "pineapple" is


not in the list

38
Ex:2

x = ["apple", "banana"] Solution :


True
print("pineapple" not in x)

# returns True because a sequence with the value "pineapple" is


not in the list

39
Python variables
 Unlike other programming languages, Python has no
command for declaring a variable.
 A variable is created the moment you first assign a value
to it.

x = 5
y = "John"
print(x)
print(y)

40
Python variables (contd)

 Variables do not need to be declared with any particular


type and can even change type after they have been set.

x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)

41
Variable Names - Rules
 A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).

Rules for Python variables:


 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different
variables)

42
Assign Value to Multiple Variables
 Python allows you to assign values to multiple variables in one line.
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Output
Orange
Banana
Cherry
 And you can assign the same value to multiple variables in one line.
x = y = z = "Orange"
print(x)
print(y)
print(z)
Output
Orange
Orange 43

Orange
Output Variables
The Python print statement is often used to output variables.

• To combine both text and a variable, Python uses the + character:

x = "awesome"
print("Python is " + x)

Output
Python is awesome Python is awesome

• You can also use the + character to add a variable to another variable:

x = "Python is "
y = "awesome"
z = x + y
print(z)
Output
Python is awesome 44
Output Variables (contd)

For numbers, the + character works as a mathematical operator:

x = 5
y = 10
print(x + y)

Output
15

45
Question ?
Predict the Output
x=5
y = "John"
print(x + y)

46
Question ?
Predict the Output - Answer
x=5
y = "John"
print(x + y)

If you try to combine a string and a number, Python will give you an error:

47
Exercise-1
1. Create a variable named carname and assign the value Volvo to it.

2.Create a variable named x and assign the value 50 to it.

3.Display the sum of 5 + 10, using two variables: x and y.

4.Create a variable called z, assign x + y to it, and display the result.

5.Remove the illegal characters in the variable name:


2my-first_name = “John”

48
PYTHON DATA TYPES
(Built-in Data Types)
 Variables can store data of different types, and different types can do
different things.

 Few of the built-in data types in Python listed below:

Numeric Types: Int, float


Text Type: str
Sequence Types: list, tuple

Mapping Type: dict

49
Getting the Data Type

You can get the data type of any object by using the type() function:

Example

Print the data type of the variable x:


x = 5
print(type(x))

Output

<class ‘int’> 50
Setting the Data Type
 In Python, the data type is set when you assign a value to a variable:

x = "Hello World" x = 20

#display x: #display x:
print(x) print(x)

#display the data type of x: #display the data type of x:


print(type(x)) print(type(x))

Output Output
Hello World 20
<class ‘str’> <class ‘int’>

51
Setting the Specific Data Type – Casting

x = str("Hello World") x = int(20)

#display x: #display x:
print(x) print(x)

#display the data type of x: #display the data type of x:


print(type(x)) print(type(x))

Output Output
Hello World 20
<class ‘str’> <class ‘int’>

52
PYTHON DATA TYPES

Numbers
Strings
List
Tuple
Dictionary

53
DATA TYPES IN PYTHON
1. Numbers
There are three numeric types in Python:
 int
 float
 complex

Variables of numeric types are created when you assign a value to them:

54
DATA TYPES IN PYTHON
1. Numbers
Example
x = 1
y = 35656222554887711
z = -3255522
a = 1.0
b = -35.59
c = 12E4
d = 3+5j

print(type(x))
print(type(y))
print(type(z))
print(type(a))
print(type(b))
print(type(c))
print(type(d)) 55
DATA TYPES IN PYTHON
1. Numbers (contd)
Example
x = 1
y = 35656222554887711
z = -3255522
a = 1.0
b = -35.59
c = 12E4
d = 3+5j
print(type(d)) <class ‘complex’>
Output
print(type(x)) <class ‘int’>
print(type(y)) <class ‘int’>
print(type(z)) <class ‘int’>
print(type(a)) <class ‘float’>
print(type(b)) <class ‘float’>
56
print(type(c)) <class ‘float’>
DATA TYPES IN PYTHON
1. Numbers (contd)
 Complex Numbers – Real Part & Imaginery Part
 A complex number is represented by “ x + yi “.
 The real part can be accessed using the function real() and imaginary part can be
represented by imag().
Creating a simple complex number in python

57
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
x = 1 # int
y = 2.8 # float
z = 1j # complex

#convert from int to float: Note: You cannot convert complex numbers into
a = float(x) another number type.

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x) Output

print(a)
print(b)
print(c)

print(type(a))
58
print(type(b))
print(type(c))
Exercise :
Which function converts a value to String ?

c1 = 3 + 6j
c2 = 6 + 15j
print("Addition of two complex number =", c1 + c2)

>>> bool(0)

59
Exercise :
Which function converts a value to String ?
X = str(3.5)

c1 = 3 + 6j
c2 = 6 + 15j
print("Addition of two complex number =", c1 + c2)
Output
Addition of two complex number = (9+21j)
>>> bool(0)
False

60
DATA TYPES IN PYTHON
2.Python Strings

• Python does not have a character data type, a single


character is simply a string with a length of 1.
• String literals in python are surrounded by either single
quotation marks, or double quotation marks.

'hello' is the same as "hello".

61
DATA TYPES IN PYTHON
2.Python Strings (Examples)

Example 1: Example 2

print("Hello") a = "Hello"
print('Hello') print(a)

Output Output
Hello Hello
Hello

62
DATA TYPES IN PYTHON
2.Multiline Strings

You can assign a multiline string to a variable by using three quotes.

Example

You can use three double quotes:


Output
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.""“

print(a)

In the output, the line breaks are inserted at the


same position as in the code.
63
String Manipulations in Python

 Access Elements of String


 Slicing
 String length
 String Methods : lower , upper , replace
 Concatenation

64
String Manipulations in Python –
Access Elements of String

Square brackets can be used to access elements of the string.

Example

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"
print(a[1])

Output

65
String Manipulations in Python –
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.

Example

Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

Output
llo 66
String Length

To get the length of a string, use the len() function.

a = "Hello, World!"
print(len(a))

Output

13

67
String Methods

The lower() method returns the string in lower


case: The upper() method returns the string in upper case:

a = "Hello, World!" a = "Hello, World!"


print(a.lower()) print(a.upper())

Output Output
hello, world! HELLO, WORLD!

The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))
Output
Jello, World! 68
String Concatenation
To concatenate, or combine, two strings you can use the + operator.

Example
Merge variable a with variable b into
variable c:

a = "Hello"
b = "World"
c = a + b
print(c)

Output

HelloWorld 69
Exercise 2
1. Use the len method to print the length of the string.
x = "Hello World"

2. Get the first character of the string txt.


txt = "Hello World”

70
PYTHON DATA TYPE
3. LIST
• A list is a collection which is ordered and changeable(mutable).
• In Python lists are written with square brackets.

Create a List:

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


print(thislist)

Output
['apple', 'banana', 'cherry']

71
PYTHON DATA TYPE
LIST –Access Items
Access Items
You access the list items by referring to the index number:

Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]

72
PYTHON DATA TYPE
LIST – Access Items(Contd)

Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Output
banana

73
PYTHON DATA TYPE
LIST – Negative Indexing
Negative indexing means beginning from the end,
-1 refers to the last item, -2 refers to the second last item etc.

Example

Print the last item of the list:


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

74
PYTHON DATA TYPE
LIST – Negative Indexing

Example

Print the last item of the list:


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

print(thislist[-1])

Output
cherry

75
PYTHON DATA TYPE
LIST – 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
list with the specified items.

Example

Return the third, fourth, and fifth item:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

76
PYTHON DATA TYPE
LIST – Range of Indexes

Example

Return the third, fourth, and fifth item:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[2:5])
Run example

['cherry', 'orange', 'kiwi'] 77


PYTHON DATA TYPE
LIST
Example

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[:4])

78
PYTHON DATA TYPE
LIST – Range of Indexes

Example

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[:4])

This example returns the items from the beginning to "orange":

['apple', 'banana', 'cherry', 'orange']

79
PYTHON DATA TYPE
LIST
Example

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[2:])

80
PYTHON DATA TYPE
LIST
Example

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[2:])

['cherry', 'orange', 'kiwi', 'melon', 'mango']

81
Change Item Value
To change the value of a specific item, refer to the index number:

Example

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


Change the second item in the above list to black currant?

82
Change Item Value

Example

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


Change the second item in the above list to black currant?

thislist[1] = "blackcurrant"
print(thislist)

['apple', 'blackcurrant', 'cherry']

83
Add Items
To add an item to the end of the list, use the append() method:

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


thislist.append("orange")
print(thislist)

['apple', 'banana', 'cherry', 'orange']

84
Insert() method

To add an item at the specified index, use the insert() method:

Insert an item as the second position:

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


thislist.insert(1, "orange")
print(thislist)

['apple', 'orange', 'banana', 'cherry']

85
Remove Item

The remove() method removes the specified item:

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


thislist.remove("banana")
print(thislist)

['apple', 'cherry']

86
Pop()

The pop() method removes the specified index, (or the last item if index is not
specified):

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


thislist.pop()
print(thislist)

87
Pop()

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


thislist.pop()
print(thislist)

['apple', 'banana']

88
del()

The del keyword removes the specified index:

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


del thislist[0]
print(thislist)

['banana', 'cherry']

89
Predict the Output

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


del thislist

90
Clear()
The clear() method empties the list:

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


thislist.clear()
print(thislist)

91
Copy a List
Make a copy of a list with Make a copy of a list with the list() method:
the copy() method:
thislist = ["apple", "banana", "cherry"]
thislist = ["apple", "banana", "cherry"] mylist = list(thislist)
mylist = thislist.copy() print(mylist)
print(mylist)

['apple', 'banana', 'cherry'] ['apple', 'banana', 'cherry']

92
Join Two Lists
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
Join both the lists .

93
Join Two Lists
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
Join both the lists .

list1 = ["a", "b" , "c"] list1 = ["a", "b" , "c"]


list2 = [1, 2, 3] list2 = [1, 2, 3]

list3 = list1 + list2 list1.extend(list2)


print(list3) print(list1)

['a', 'b', 'c', 1, 2, 3] ['a', 'b', 'c', 1, 2, 3]

94
95
96
97
Python Data Type
4. Tuple
 A tuple is a collection which is ordered
and unchangeable(immutable).
 In Python tuples are written with round brackets.

Example
Create a Tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple)

Output
(‘apple’,’banana’,’cherry’)

98
Python Data Type
4. Tuple

Create an Empty Tuple ?

99
Python Data Type
4. Tuple

Create an Empty Tuple ?

tup1 = ()

100
Create Tuple With One Item
• To create a tuple with only one item,you have add a comma after the
item, unless Python will not recognize the variable as a tuple.

thistuple = ("apple",)
print(type(thistuple))
Output
<type 'tuple'>

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

101
Create Tuple With One Item

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

Output

<type 'str'>

102
Python Data Type
4. Tuple -Access Tuple Items

You can access tuple items by referring to the index


number, inside square brackets:

Example
Print the second item in the tuple:

thistuple = ("apple", "banana", "cherry")

103
Python Data Type
4. Tuple -Access Tuple Items

You can access tuple items by referring to the index


number, inside square brackets:

Example
Print the second item in the tuple:

thistuple = ("apple", "banana", "cherry")

print(thistuple[1])

Output
banana

104
List(Mutable) Vs Tuple(Immutable)
thislist =
["apple", "banana", "cherry", "orange", "kiwi", thistuple =
"melon", "mango"] ("apple", "banana", "cherry", "orange", "kiwi", "melo
print(thislist) n", "mango")
Output print(thistuple)
['apple', ‘banana', 'cherry', 'orange', 'kiwi', Output
'melon', 'mango'] ("apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango")
print(type(thislist)) print(type(thistuple))
Output Output
<type 'list'> <type 'tuple'>
thistuple[1] = "grapes"
thislist[1] = "tomato" print(thistuple)
print(thislist) Output
Output TypeError: 'tuple' object does not support item
['apple', 'tomato', 'cherry', 'orange', 'kiwi', assignment
'melon', 'mango']
105
Python Data Type
4. Tuple -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.

106
Python Data Type
4. Tuple -Change Tuple Values

Example
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)

Output
('apple', 'kiwi', 'cherry') 107
Remove Items
Tuples are unchangeable(immutable), so you
cannot remove items from it, but you can delete the
tuple completely:

Example
The del keyword can delete the tuple completely:

thistuple = ("apple", "banana", "cherry")


del thistuple
print(thistuple)

Output
NameError: name 'thistuple' is not defined 108
Advantages of tuple over list
 Iterating through tuple is faster than with list, since tuples are
immutable.
 Tuples that consist of immutable elements can be used as key for
dictionary, which is not possible with list
 If you have data that is immutable, implementing it as tuple will
guarantee that it remains write-protected.

109
Python Data Type
5.Dictionary

• A dictionary is a collection which is unordered,


changeable and indexed.

• In Python dictionaries are written with curly brackets.

• Python Dictionary are defined into two elements Keys and


Values.
 Keys will be a single element
 Values can be a list or list within a list, numbers, etc.

• Keys are unique within a dictionary while values may not be.
• The values of a dictionary can be of any type, but the keys must be of
an immutable data type such as strings, tuples.
110
Python Data Type
5.Dictionary

Example

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Output

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

111
112
Dictionary Creation
 D=dict()
 D=([(1,”hi”),(2,”hello”),(3,”welcome”)])
 D=dict(r0llno=12,name=“xxxx”)

113
114
Python Data Type
5.Dictionary- Accessing Items
You can access the items of a dictionary by referring to its key name,
inside square brackets:

Example

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)

Output
Mustang

115
Python Data Type
5.Dictionary- Change Values

You can change the value of a specific item by referring to its key name:

Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

thisdict["year"] = 2018

print(thisdict)
Output

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

116
Python Data Type
5.Dictionary- Adding Items
Adding an item to the dictionary is done by using a new index key and assigning
a value to it:
Example

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)

Output

{'color': 'red', 'brand': 'Ford', 'model': 'Mustang', 'year': 1964}


117
Python Data Type
5.Dictionary- Removing Items

Example

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

Output

{'color': 'red', 'brand': 'Ford', 'year': 1964}


118
Dictionary Operators and Builtin functions
Len()
In operator
Clear()
Get()
Items()
Keys()
Values()
Pop()
Popitem()

119
SETS
Sets

 Set: object that stores a collection of data in same way as mathematical set
All items must be unique
Set is unordered
Elements can be of different data types
Sets

 Indentified by curly braces


 {'Alice', 'Bob', 'Carol'}
 {'Dean'} is a singleton
 Can only contain unique elements
 Duplicates are eliminated
 Immutable like tuples and strings
Sets do not contain duplicates

 >>> cset = {11, 11, 22}


 >>> cset
{11, 22}
Sets are immutable

 >>> aset = {11, 22, 33}


Union of two
 >>> bset = aset sets
 >>> aset = aset | {55}
 >>> aset
{33, 11, 22, 55}
 >>> bset
{33, 11, 22}
Sets have no order

 >>> {1, 2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 5, 6, 7}
 >>> {11, 22, 33}
{33, 11, 22}
Sets do not support indexing

 >>> myset = {'Apples', 'Bananas', 'Oranges'}


 >>> myset
{'Bananas', 'Oranges', 'Apples'}
 >>> myset[0]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
myset[0]
TypeError: 'set' object does not support indexing
Creating a Set

 set function: used to create a set


For empty set, call set()
For non-empty set, call set(argument) where argument is an object that
contains iterable elements
 e.g., argument can be a list, string, or tuple
 If argument is a string, each character becomes a set element
For set of strings, pass them to the function as a list
 If argument contains duplicates, only one of the duplicates will appear in the set
Getting the Number of and Adding
Elements
 len function: returns the number of elements in the set
 Sets are mutable objects
 add method: adds an element to a set
 update method: adds a group of elements to a set
 Argument must be a sequence containing iterable elements, and each of the
elements is added to the set
Deleting Elements From a Set

 remove and discard methods: remove the specified item from the set
 The item that should be removed is passed to both methods as an argument
 Behave differently when the specified item is not found in the set
 remove method raises a KeyError exception
 discard method does not raise an exception
 clear method: clears all the elements of the set
Using the for Loop, in, and not in
Operators With a Set
 A for loop can be used to iterate over elements in a set
General format: for item in set:
The loop iterates once for each element in the set
 The in operator can be used to test whether a value exists in a set
Similarly, the not in operator can be used to test whether a value does not exist
in a set
Examples

 >>> alist = [11, 22, 33, 22, 44]


 >>> aset = set(alist)
 >>> aset
{33, 11, 44, 22}
 >>> aset = aset + {55}
SyntaxError: invalid syntax
Boolean operations on sets (I)

 Union of two sets

A B

 Contains all elements that are in set A or in set B


Finding the Union of Sets

 Union of two sets: a set that contains all the elements of both sets
 To find the union of two sets:
Use the union method
 Format: set1.union(set2)

Use the | operator


 Format: set1 | set2

Both techniques return a new set which contains the union of both sets
Finding the Intersection of Sets

 Intersection of two sets: a set that contains only the elements found in both
sets
 To find the intersection of two sets:
 Use the intersection method
 Format: set1.intersection(set2)
 Use the & operator
 Format: set1 & set2
 Both techniques return a new set which contains the intersection of both sets
Boolean operations on sets (II)

 Intersection of two sets

A B

 Contains all elements that are in both sets A and B


Boolean operations on sets (III)

 Difference of two sets

A B

 Contains all elements that are in A but not in B


Finding the Difference of Sets

 Difference of two sets: a set that contains the elements that appear in the
first set but do not appear in the second set
 To find the difference of two sets:
 Use the difference method
 Format: set1.difference(set2)
 Use the - operator
 Format: set1 - set2
Boolean operations on sets (IV)

 Symmetric difference of two sets

A B

Contains all elements that are either


 in set A but not in set B or
 in set B but not in set A
Finding the Symmetric Difference of
Sets
 Symmetric difference of two sets: a set that contains the elements that are not
shared by the two sets
 To find the symmetric difference of two sets:
 Use the symmetric_difference method
 Format: set1.symmetric_difference(set2)
 Use the ^ operator
 Format: set1 ^ set2
 sets A = {1,2,3,4,5} and B = {2,4,6}. The symmetric difference between these sets
is {1,3,5,6}. (A – B) ∪ (B – A)
 A-B = {1,3,5}
 B-A = {6}
 (A-B)U(B-A) = {1,3,5,6}
Boolean operations on sets (V)

 >>> aset = {11, 22, 33}


 >>> bset = {12, 23, 33}
 Union of two sets
 >>> aset | bset
{33, 22, 23, 11, 12}
 Intersection of two sets:
 >>> aset & bset
{33}
Boolean operations on sets (VI)

 >>> aset = {11, 22, 33}


 >>> bset = {12, 23, 33}
 Difference:
 >>> aset – bset
{11, 22}
 Symmetric difference:
 >>> aset ^ bset
{11, 12, 22, 23}
Finding Subsets and Supersets

 Set A is subset of set B if all the elements in set A are included in set B
 To determine whether set A is subset of set B
 Use the issubset method
 Format: setA.issubset(setB)
 Use the <= operator
 Format: setA <= setB
Finding Subsets and Supersets (cont’d.)

 Set A is superset of set B if it contains all the elements of set B


 To determine whether set A is superset of set B
 Use the issuperset method
 Format: setA.issuperset(setB)
 Use the >= operator
 Format: setA >= setB
Control Structures

 Conditional statements

 Looping statements

144
Programming using
Python
f (unctions)
Programming, Functions May 25, 2024 145
Parts of a function

Programming, Functions May 25, 2024 146


Types of function arguments

147
148
Variable length /Arbitrary Arguments
 In Python, sometimes, there is a situation where we need to pass multiple
arguments to the function. Such types of arguments are called arbitrary
arguments or variable-length arguments.
 We use variable-length arguments if we don’t know the number of
arguments needed for the function in advance.

149
OUTPUT:

150
Anonymous/Lambda Function
 Declare a function without any name. The nameless property function is
called an anonymous function or lambda function.
 Defined using Lambda Function

Syntax:
 The reason behind the using
 Lambda : Argument_list : Expression anonymous function is for instant use,
 Ex: lambda n : n+n that is, one-time usage.

 In opposite to a normal function, a


double=lambda x:x*2 Python lambda function is a
single expression. But, in a lambda
print(double(5)) body, we can expand with
expressions over multiple lines
using parentheses or a multiline
Ans: 10
string. 151
Programming using Python

Modules and Packages

Python Programming Welcome 152


What is a Module?
• Consider a module to be the same as a code library.
• A file containing a set of functions you want to include in your
application.

Create a Module Use a Module

Re-naming a Module

Create a alias name using as

import mymodule as mx

mx.greeting(“xxx”) 153
Import From Module

Note: When importing using the from keyword, do not use the module
name when referring to elements in the module.
Example: person1["age"], not mymodule.person1["age"]

154
Modules
 As program gets longer, need to organize them for easier
access and easier maintenance.
 Reuse same functions across programs without copying its
definition into each program.
 Python allows putting definitions in a file
 use them in a script or in an interactive instance of the interpreter
 Such a file is called a module
 definitions from a module can be imported into other modules or
into the main module

Programming May 25, 2024


155
Modules

 A module is a file containing Python definitions and


statements.
 The file name is the module name with the suffix .py
appended.
 Within a module, the module’s name is available in the
global variable __name__.

Programming May 25, 2024


156
Modules Example

fib.py - C:\

Programming May 25, 2024


157
Modules Example

Within a module, the


module’s name is
available as the value of
Programming
the global variable
May 25, 2024

__name__. 158
Importing Specific Functions
 To import specific functions from a module

 This brings only the imported functions in the current


symbol table
 No need of modulename. (absence of fib. in the example)
Programming May 25, 2024
159
Importing ALL Functions

 To import all functions from a module, in the


current symbol table

 This
imports all names except those beginning
Programming May 25, 2024
160

with an underscore (_).


Package
 A Python package is a collection of Python modules.
 Another level of organization.
 Packages are a way of structuring Python’s module
namespace by using dotted module names.
 The module name A.B designates a submodule named B in a
package named A.
 The use of dotted module names saves the authors of multi-
module packages like NumPy or Pillow from having to worry about
each other’s module names.

Programming May 25, 2024 161


A sound Package

Programming
https://docs.python.org/3/tutorial/modules.html
May 25, 2024 162
A sound Package

What are these files


with funny names?

https://docs.python.org/3/tutorial/modules.html
May 25, 2024
Programming 163
xs
__init.py__

 The __init__.py files are required to make Python treat directories


containing the file as packages.
 This prevents directories with a common name, such as string,
unintentionally hiding valid modules that occur later on the module search
path.
 __init__.py can just be an empty file
 It can also execute initialization code for the package

Programming May 25, 2024 164


Importing Modules from Packages

Programming
https://docs.python.org/3/tutorial/
May 25, 2024 165
modules.html
Importing Modules from Packages
import sound.effects.echo

 Loads the submodule sound.effects.echo


 It must be referenced with its full name:

sound.effects.echo.echofilter(
input, output,
delay=0.7, atten=4
)

Programming May 25, 2024 166


Importing Modules from Packages
from sound.effects import echo
 This also loads the submodule echo
 Makes it available without package prefix
 It can be used as:
echo.echofilter(
input, output,
delay=0.7, atten=4
)

Programming May 25, 2024 167


Importing Modules from Packages
from sound.effects.echo import
echofilter

 This loads the submodule echo, but this makes its


function echofilter() directly available.

echofilter(input, output,
delay=0.7, atten=4)

Programming May 25, 2024 168


Popular Packages

 pandas, numpy, scipy, matplotlib, …


 Provide a lot of useful functions

Programming May 25, 2024 169


THANK YOU

170

You might also like