Professional Documents
Culture Documents
Unit 1 To 5 Aktu Python
Unit 1 To 5 Aktu Python
Of
Python
Topic
Introduction: The Programming Cycle for Python , Python IDE, Interacting with
Python Programs , Elements of Python, Type Conversion.
I 08
Basics: Expressions, Assignment Statement, Arithmetic Operators, Operator
Precedence, Boolean Expression..
Topic
Topic
#include<stdio.h> a= 10
void main() b=20
{ print(a+b)
int a, b ;
a = 10;
b= 20;
printf(“The sum:%d”,(a+b));
}
Features of Python
9
Cont….
10
2.Freeware and open Source:- We can use Python software without any
license and it is freeware. Therefore , anyone can freely use the code to
write new programs.
3.Platform Independent:- Once we write a python program, it can run on
any platform without rewriting once again. Internally PVM is responsible
to convert into machine understandable form.
4. Portability:- Python program are portable. I.e. we can migrate from
one platform to another platform very easily . Python programs will
provide same results on any platform.
Cont……
11
Limitations of Python
12
Cont….
14
Steps3:- After clicking on all Release under Downloads browser through the
page to the bottom. You will see a list of python release.
Steps4:- Click on python 3.4.2 and download it.
Step5:- Open the folder where you have downloaded the python 3.4 version
and double click on it to start the installation.
Step6:- After clicking on it you will see python first windows to set up
python 3.4.2.
Steps7:- Click on next and you will see second window which tells you to
specify the location where you want install python.
Cont….
15
IDENTIFIERS
16
Digits (0 to 9)
Underscore symbol(_)
By mistake if we are using any other symbol like$ then we will get
syntax error.
Cash= 10 (right)
Ca$h = 20 (Wrong)
Identifiers
17
TOTAL = 999
Print(total) #10
Print(TOTAL) #999
Characteristics of the identifiers
18
Reserved Words
20
Import, from, as, class, def, pass, global, nonlocal, lambda, del,
with
Cont…..
21
Note:-
1. All Reserved words in Python contain only alphabet symbols.
2. Except the following 3 Reserved words, all contain only lower case
alphabet symbols.
e.g. True, False, None.
For example
a = true(Wrong)
b = True(Right)
Write a program to show the reserved keywords
in python
22
>>>import keyword
>>>keyword.kwlist
Output:-
‘False’, ‘True’, ‘None’, ‘and’, ‘as’, ‘assert’, ‘break’, ‘class’,
‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’,
‘from’, ‘if’, ‘global’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’,
‘not’, ‘or’, ‘ pass’, ‘raise’, ‘return’, ‘ try’, ‘while’, ‘with’, yield’
Data Types
23
We can mainly categories in two types i.e. mutable and immutable data types.
Mutable means we can change its state or contents and immutable objects cannot.
Mutable Data Types
List
Dictionary
Byte array
Float
Complex
String
Tuple
Set
Bool
Integer data types(Immutable)
24
We can represent int value in
following ways:-
25
4. Hexadecimal Form(Base-16)
26
The allowed digits are: 0to9, a-f (both lower and upper cases are allowed)
Literals value should be prefixed with 0x or 0X
For example:-
P = 100
Q = 0o100
R = 0X10c
S = 0B1010
Print(P) # 100
Print(Q) # 64
Print (R) # 268
Print(S) # 10
Float data type(Immutable)
27
• We can use float data type to represent floating point values
(decimal values)
e.g. f = 1.234
print(type(f))
print (f)
Output :-
<class ‘float’>
1.234
Note:- we can represent int value in decimal, binary, octal,
hexadecimal, form but we can represent float values only by
using decimal form.
Complex data type(immutable)
28
Bool Data type(immutable)
29
Type casting
32
a=5
n = float(a)
print(n)
print(type(n))
a = 5.9
n = int(a)
print(n)
print(type(n))
Introduction to Data Structure
Conti….
36
a=5
n = str(a)
print(n)
print(type(n))
a = "5"
n = int(a)
print(n)
print(type(n))
Introduction to Data Structure
List(Mutable)
37
Tuple
38
Set(Immutable)
43
Operators in Python
44
Write a program to perform arithmetic operator
46
a = 10
b=5
print(a+b) 15
print(a-b) 5
print(a*b)50
print(a/b)2.0
print(a**a)100
print(a//b)2
Print(a%3)1
Relational or Comparison Operators
47
48
a=10
b=20
print("a > b is ",a>b)False
print("a >= b is ",a>=b)False
print("a <= b is ",a<=b)True
Print(“a==b is “,a==b)False
Print(“a<b is “,a<b)True
Logical Operators
49
Boolean types.
• For example:-
Print(4&5) valid
Print(10.5&5.6)Type error: unsupported operand
type(s) for &: ‘float’ and ‘float’
Table for Bitwise operators
52
Operators Descriptions
l Bitwise OR operator
& Bitwise AND operator
^ Bitwise NOT operator
~ Bitwise NOT operator
<< Bitwise left operator
>> Bitwise right operator
Precedence and Associativity of Operators in Python
53
() Parentheses left-to-right
** Exponent right-to-left
Multiplication/
* / % left-to-right
division/modulus
+ – Addition/subtraction left-to-right
Conditional statement in python
55
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Conti…
60
Conti….
61
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
Conti….
62
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
conti….
64
i = 15
if (i == 15):
if (i < 20):
print("i is smaller than 20")
if (i < 25):
print("i is smaller than 25 too")
else:
print("i is greater than 20")
Conti…
65
elif statements:
Syntax:
i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
Loops
In general, statements are executed sequentially: The
first statement in a function is executed first,
followed by the second, and so on. There may be a
situation when you need to execute a block of code
several number of times.
A loop statement allows us to execute a statement or
group of statements multiple times.
Conti…
67
Example:
i=1
while (i < 6):
print(i)
i += 1
number = 2
while (number < 5) :
print("Thank you")
number = number+1
Python For Loops
69
var = 10
while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break
print ("Good bye!”)
The range() Function
76
Example:
for x in range(2, 6):
print(x)
print(range(10))
print(list(range(10)))
print(list(range(2, 8)))
print(list(range(2, 20, 3)))
Conti….
78
Use it in an if statement
txt = ”Hello AI students"
if ”students" in txt:
print("Yes, ‘student' is present.")
Check if NOT
84
String1 = ”PadhAI”
print("Initial String: ")
print(String1)
print(String1[0])
print(String1[-1])
String Slicing
88
Example
b = "Hello, World!"
print(b[-5:-2])
Deleting/Updating from a String
91
Example:
String1 = "Hello AI students"
print(String1)
String1[2] = 'p'
print(String1)
Error
Traceback (most recent call last):
File “/home/360bb1830c83a918fc78aa8979195653.py”, line
10, in
String1[2] = ‘p’
TypeError: ‘str’ object does not support item assignment
Updating Entire String
93
#Upper case
a = "Hello, World!"
print(a.upper())
#Lower Case
a = "Hello, World!"
print(a.lower())
Conti…
99
#Remove Whitespace
Example
The strip() method removes any whitespace from the
beginning or the end:
a = " Hello, World! "
print(a.strip())
Conti….
100
#Replace String
The replace() method replaces a string with another
string:
a = "Hello, World!"
print(a.replace("H", "J"))
Conti….
101
#String Concatenation
a = "Hello"
b = "World"
c=a+b
print(c)
Python Functions
102
Creating a Function
In Python a function is defined using the def keyword:
Example:
def my_function():
print("Hello from a function")
#Calling a Function
my_function()
Conti…
104
#Arguments
Information can be passed into functions as
arguments.
Arguments are specified after the function name,
inside the parentheses. You can add as many
arguments as you want, just separate them with a
comma.
Conti….
105
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Conti….
106
Example
This function expects 2 arguments, and gets 2
arguments:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
Conti….
107
my_function("Emil")
Arbitrary Arguments, *args
108
def myFun(*argv):
for arg in argv:
print(arg)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Passing a List as an Argument
112
my_function(fruits)
Conti….
113
#Return Values
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Conti…
114
def square_value(num):
return num**2
print(square_value(2))
print(square_value(-4))
Python Scope
115
myfunc()
Conti….
116
If you operate with the same variable name inside and outside
of a function, Python will treat them as two separate variables,
one available in the global scope (outside the function) and
one available in the local scope (inside the function):
x = 20
def my_function():
x = 30
print(x)
my_function()
print(x)
Global Keyword
118
Also, use the global keyword if you want to make a change to a global
variable inside a function.
To change the value of a global variable inside a function, refer to the
variable by using the global keyword:
x = 300
def my_func():
global x
x = 200
my_func()
print(x)
Python Lambda Functions
120
x = lambda a : a + 10
print(x(5))
# Multiply argument a with argument b and return the
result:
x = lambda a, b : a * b
print(x(5, 6))
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Python Data Structures
123
List Items:
List items are ordered, changeable, and allow
duplicate values.
List items are indexed, the first item has index [0],
the second item has index [1] etc.
Conti…
127
Ordered:
When we say that lists are ordered, it means that the
items have a defined order, and that order will not
change.
If you add new items to a list, the new items will be
placed at the end of the list.
Conti….
128
Changeable:
The list is changeable, meaning that we can change,
add, and remove items in a list after it has been
created.
Allow Duplicates:
Since lists are indexed, lists can have items with the
same value:
Conti…
129
<class 'list'>
Conti…
132
Access Items:
List items are indexed and you can access them by
referring to the index number:
Example
Print the second item of the list:
Note: The first item has index 0.
My_list = ["apple", "banana", "cherry"]
Conti….
134
Negative Indexing:
Negative indexing means start 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:
my_list = ["apple", "banana", "cherry"]
Conti…
135
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.
my_list=
["apple", "banana", "cherry", "orange", "kiwi", "melon", "man
go"]
print(my_list[2:5])
Note: The search will start at index 2 (included) and end at
index 5 (not included).
Conti…
136
Example
Print all items in the list, one by one:
list1 = ["apple", "banana", "cherry"]
for x in list1:
print(x)
Loop Through the Index Numbers
153
DO YOURSELF
List Comprehension
155
fruits =
["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
Conti….
157
With list comprehension you can do all that with only one line
of code:
Syntax
newlist = [expression for item in iterable if condition == True]
print(newlist)
Conti…
158
Iterable
The iterable can be any iterable object, like a list,
tuple, set etc.
Example
You can use the range() function to create an iterable:
newlist = [x for x in range(10)]
You can also customize your own function by using the keyword
argument key = function.
The function will return a number that will be used to sort the list
(the lowest number first):
Example
Sort the list based on how close the number is to 50:
def my_func(n):
return abs(n - 50)
Example:
tuple1 = ("apple", "banana", "cherry")
print(tuple1)
Tuple Items
173
Ordered
When we say that tuples are ordered, it means that the
items have a defined order, and that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change,
add or remove items after the tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the
same value:
Conti…
175
Tuple Length
To determine how many items a tuple has, use
the len() function:
Example
Print the number of items in the tuple:
tuple2 = ("apple", "banana", "cherry")
print(len(tuple2))
Conti…
176
#NOT a tuple
tuple4 = ("apple")
print(type(tuple4))
Conti…
177
tuple9 =
("apple", "banana", "cherry", "orange", "kiwi", "melo
n", "mango")
print(tuple9[:4])
print(tuple9[2:])
Range of Negative Indexes
183
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)
Add Items
187
Example1
tuple12 = ("apple", "banana", "cherry")
y = list(tuple12)
y.append("orange")
tuple12 = tuple(y)
Example2
tuple12 = ("apple", "banana", "cherry")
y = ("orange",)
tuple12 += y
print(tuple12)
Remove Items
189
print(green) ?
print(tropic) ?
print(red) ?
Loop Tuples
194
Do yourself
Join Tuples
197
Unordered
Unordered means that the items in a set do not have a
defined order.
Set items can appear in a different order every time you use
them, and cannot be referred to by index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot
change the items after the set has been created.
Once a set is created, you cannot change its items, but you
can remove items and add new items.
Duplicates Not Allowed
Conti…
202
print(set2)
Conti…
203
print(len(set3))
Conti…
204
for x in set2:
print(x)
Conti…
207
print("banana" in set4)
Change Items
Once a set is created, you cannot change its items, but
you can add new items.
Conti…
208
Add Items
To add one item to a set use the add() method.
set3 = {"apple", "banana", "cherry"}
set3.add("orange")
print(set3)
Add Sets
209
To add items from another set into the current set, use
the update() method.
set5 = {"apple", "banana", "cherry"}
set6 = {"pineapple", "mango", "papaya"}
set5.update(set6)
print(set5)
Remove Set Items
210
set7.remove("banana")
print(set7)
Conti…
211
Loop Items
You can loop through the set items by using
a for loop
Loop through the set, and print the values
set11 = {"apple", "banana", "cherry"}
for x in set11:
print(x)
Join Two Sets
214
set1.update(set2)
print(set1)
Dictionary
216
Ordered.
Changeable.
Duplicates are not allowed.
thisdict
= {"brand": "Ford","model": "Mustang","year": 1964,"yea
r": 2020}
print(thisdict)
Conti…
219
Dictionary Length
To determine how many items a dictionary has, use
the len() function:
print(len(thisdict))
Conti…
220
Accessing Items
You can access the items of a dictionary by referring to its
key name, inside square brackets:
thisdict
= {"brand": "Ford","model": "Mustang","year": 1964}
x = thisdict["model"]
OR
x = thisdict.get("model")
Conti…
222
Get Keys
The keys() method will return a list of all the keys in the
dictionary.
Syntax: x = thisdict.keys()
car = {"brand": "Ford","model": "Mustang","year": 1964}
x = car.keys()
print(x)
car["color"] = "white"
print(x)
Conti…
223
Get Values
The values() method will return a list of all the values
in the dictionary.
Syntax: x = thisdict.values()
car =
{"brand": "Ford","model": "Mustang","year": 1964}
x = car.values()
print(x)
car["year"] = 2020
print(x)
Conti….
224
car =
{"brand": "Ford","model": "Mustang","year": 1964}
x = car.values()
print(x)
car["color"] = "red"
print(x)
Conti…
225
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict
dictionary")
Conti….
226
Change Values
You can change the value of a specific item by referring to
its key name:
Example:
thisdict= {"brand": "Ford","model": "Mustang","year": 196
4}
thisdict["year"] = 2018
Conti…
227
Update Dictionary
The update() method will update the dictionary with the items
from the given argument.
The argument must be a dictionary, or an iterable object with
key: value pairs.
Example:
thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
thisdict.update({"year": 2020})
Conti…
228
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)
Conti…
229
Removing Items
There are several methods to remove items from a dictionary:
The pop() method removes the item with the specified key
name:
Example:
Thisdict = { "brand": "Ford","model": "Mustang","year":1964}
thisdict.pop("model")
print(thisdict)
Conti…
230
The del keyword removes the item with the specified key
name:
thisdict
= {"brand": "Ford","model": "Mustang","year": 1964}
del thisdict["model"]
print(thisdict)
The del keyword can also delete the dictionary
completely:
del thisdict
print(thisdict)
Conti…
231
thisdict.clear()
print(thisdict)
Conti….
232
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1,
because: dict2 will only be a reference to dict1, and changes
made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in
Dictionary method copy().
thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
mydict = thisdict.copy()
print(mydict)
Conti…
236
mydict = dict(thisdict)
print(mydict)
Conti…
237
Nested Dictionaries
A dictionary can contain dictionaries, this is called
nested dictionaries.
Create a dictionary that contain three dictionaries:
myfamily = {"child1" :
{"name" : "Emil","year" : 2004},"child2" :
{ "name" : "Tobias", "year" : 2007},"child3" :
{"name" : "Linus","year" : 2011}}
Conti…
238
UNIT 5
Iteration
241
Python Iterators
An iterator is an object that contains a countable
number of values.
An iterator is an object that can be iterated upon,
meaning that you can traverse through all the values.
Technically, in Python, an iterator is an object which
implements the iterator protocol, which consist of the
methods __iter__() and __next__().
Iterator vs Iterable
242
Example 1:
def recursion1(n):
if(n>0):
result = n+recursion1(n-1)
print(result)
else:
result = 0
return result
Example 2:
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = int(input(“enter the number”))
print(factorial(num))
Advantages of Recursion
248
n = int(input(“enter number”))
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
for i in range(n)
Print(recur_fibo(i))
Tower of Hanoi
251
a={}
for i in range(0,8):
a[i]=eval(input("Enterno."))
no=eval(input("Enter no. tosearch:"))
for i in range(0,8):
if a[i] == no:
flag = 1
break
if flag == 1:
print("no.isavailableinlist")
else:
Binary search:
254
arr = [ 2, 3, 4, 10, 40 ]
x = 10
result = binary_search(arr, x)
if result != -1:
print("Element is present at index”, str(result))
else:
print("Element is not present in array")
Selection sort
257
length = len(array)
for i in range(length-1):
minIndex = i
for j in range(i+1, length):
if array[j]<array[minIndex]:
minIndex = j
array[i], array[minIndex] = array[minIndex], array[i]
return array
array = [21,6,9,33,3]
print("The sorted array is: ", selection_sort(array))
Join / Merge lists ( two or more)
259
def mergeSort(myList):
if len(myList) > 1:
mid = len(myList) // 2
left = myList[:mid]
right = myList[mid:]
mergeSort(left)
mergeSort(right)
i=0
j=0
k=0
Conti….
265
UNIT 4
Program to print all prime numbers in a given
range:
268
lower = 900
upper = 1000
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
Sieve of Eratothenes:
269
Close Files:
It is a good practice to always close the file when you
are done with it.
f = open(”hello.txt", "r")
print(f.readline())
f.close()
Conti…
281