Python - Session1
Python - Session1
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.
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'''
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
Some operators require two operands while others require only one.
20
Unary Operators
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 += 3 x -= 3 x /= 3
25
Exercise
x += 3 x -= 3 x /= 3
26
Exercise (contd)
27
Exercise (contd)
28
Logical Operators
Logical operators are used to combine conditional statements:
29
Exercise
print(x > 3 and x < 10) print(x > 3 or x < 4) print(not(x > 3 and x < 10))
30
Exercise
print(x > 3 and x < 10) print(x > 3 or x < 4) print(not(x > 3 and x < 10))
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 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)
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
Ex:
x = ["apple", "banana"]
print("banana" in x)
# returns True because a sequence with the value "banana" is in the list
36
Membership Operators
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)
38
Ex:2
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)
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).
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.
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)
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.
48
PYTHON DATA TYPES
(Built-in Data Types)
Variables can store data of different types, and different types can do
different things.
49
Getting the Data Type
You can get the data type of any object by using the type() function:
Example
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)
Output Output
Hello World 20
<class ‘str’> <class ‘int’>
51
Setting the Specific Data Type – Casting
#display x: #display x:
print(x) print(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.
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
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
Example
print(a)
64
String Manipulations in Python –
Access Elements of 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
• Specify the start index and the end index, separated by a colon, to
return a part of the string.
Example
b = "Hello, World!"
print(b[2:5])
Output
llo 66
String Length
a = "Hello, World!"
print(len(a))
Output
13
67
String Methods
Output Output
hello, world! HELLO, WORLD!
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"
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:
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
74
PYTHON DATA TYPE
LIST – Negative Indexing
Example
print(thislist[-1])
Output
cherry
75
PYTHON DATA TYPE
LIST – Range of Indexes
Example
76
PYTHON DATA TYPE
LIST – Range of Indexes
Example
print(thislist[2:5])
Run example
print(thislist[:4])
78
PYTHON DATA TYPE
LIST – Range of Indexes
Example
print(thislist[:4])
79
PYTHON DATA TYPE
LIST
Example
print(thislist[2:])
80
PYTHON DATA TYPE
LIST
Example
print(thislist[2:])
81
Change Item Value
To change the value of a specific item, refer to the index number:
Example
82
Change Item Value
Example
thislist[1] = "blackcurrant"
print(thislist)
83
Add Items
To add an item to the end of the list, use the append() method:
84
Insert() method
85
Remove Item
['apple', 'cherry']
86
Pop()
The pop() method removes the specified index, (or the last item if index is not
specified):
87
Pop()
['apple', 'banana']
88
del()
['banana', 'cherry']
89
Predict the Output
90
Clear()
The clear() method empties the list:
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)
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 .
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:
Output
(‘apple’,’banana’,’cherry’)
98
Python Data Type
4. Tuple
99
Python Data Type
4. 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
Example
Print the second item in the tuple:
103
Python Data Type
4. Tuple -Access Tuple Items
Example
Print the second item in the tuple:
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
106
Python Data Type
4. Tuple -Change Tuple Values
Example
Convert the tuple into a list to be able to change it:
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:
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
• 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
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
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
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Output
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
>>> {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
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
A B
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)
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)
A B
A B
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)
A B
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.)
Conditional statements
Looping statements
144
Programming using
Python
f (unctions)
Programming, Functions May 25, 2024 145
Parts of a function
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.
Re-naming a Module
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
fib.py - C:\
__name__. 158
Importing Specific Functions
To import specific functions from a module
This
imports all names except those beginning
Programming May 25, 2024
160
Programming
https://docs.python.org/3/tutorial/modules.html
May 25, 2024 162
A sound Package
https://docs.python.org/3/tutorial/modules.html
May 25, 2024
Programming 163
xs
__init.py__
Programming
https://docs.python.org/3/tutorial/
May 25, 2024 165
modules.html
Importing Modules from Packages
import sound.effects.echo
sound.effects.echo.echofilter(
input, output,
delay=0.7, atten=4
)
echofilter(input, output,
delay=0.7, atten=4)
170