Ilovepdf Merged
Ilovepdf Merged
Ilovepdf Merged
Comments - Numeric Data types and Character sets – Expressions – Loops and Selection
Statements: Definite iteration: the for Loop - selection: if and if-else statements - Conditional
iteration: the while Loop
1. Introduction to Python
Python is a widely used general-purpose, high level programming language.
It was initially designed by Guido van Rossum in 1991 and developed by Python
Software Foundation. It was mainly developed for emphasis on code readability, and
its syntax allows programmers to express concepts in fewer lines of code.
Python is a programming and scripting language that lets you work quickly and
integrate systems more efficiently.
1
3. Difference between a scripting language and programming language
4. Features of Python
Python's features include −
Python is object-oriented: Structure supports such concepts as polymorphism,
operation overloading and multiple inheritance.
Indentation: Indentation is one of the greatest feature in python
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than
shell scripting
2
5. Working with Python
Python’s traditional runtime execution model: Source code you type is translated to byte
code, which is then run by the Python Virtual Machine (PVM). Your code is automatically
compiled, but then it is interpreted.
7. COMMENTS:
Single-line comments begins with a hash(#) symbol and is useful in mentioning that
the whole line should be considered as a comment until the end of line.
3
A Multi line comment is useful when we need to comment on many lines. In python,
triple double quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting.
Example:
print("Hello, World!") #This is a comment
"""
This is a comment
written in
more than just one line
"""
8. VARIABLES IN PYTHON
Creating Variables
Example
x=5
y = "John"
print(x)
print(y)
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
4
9. INPUT FUNCTION IN PYTHON
Example
Output
In Python, we need not declare a datatype while declaring a variable like C or C++. We can
simply just assign values in a variable. But if we want to see what type of numerical value is
it holding right now, we can use type(), like this:
5
print("The type of variable having value", b, " is ", type(b))
Output
The string is a sequence of characters. Python supports Unicode characters. Generally, strings
are represented by either single or double-quotes.
The list is a versatile data type exclusive in Python. In a sense, it is the same as the
array in /C++.
But the interesting thing about the list in Python is it can simultaneously hold different
types of data.
Formally list is an ordered sequence of some data written using square brackets([])
and commas(,).
6
#list of having both integers and strings
c= ["hey","you",1,2,3,"go"]
print(c)
Output
Dictionary
Python Dictionary is an unordered sequence of data of key-value pair form. It is similar to the
hash table type. Dictionaries are written within curly braces in the form key:value. It is very
useful to retrieve data in an optimized way among a large amount of data.
7
#print value having key=2
print(a[2])
#print value having key="age"
print(a["age"])
A boolean type can take either a True or a False value. The following
example illustrates how to use a boolean variable.
x = True;
y = False;
#Check the type of x and y.
print(type(x));
print(type(y));
Output->
Type of x <class 'bool'>
Type of y <class 'bool'>
Syntax:
Sets are of the type set. They are created by elements separated by commas enclosed in curly
brackets {}.
print(my_set)
print("Its data type:", type(my_set))
Output:
8
11. OPERATORS IN PYTHON
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
9
10
Python 'is' Operator
The 'is' operator evaluates to True if both the operand objects share the same memory
location.
The memory location of the object can be obtained by the "id()" function. If the "id()"
of both variables is same, the "is" operator returns True.
a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
c = a
# Comparing and printing return values
print(a is c)
print(a is b)
# Printing IDs of a, b, and c
print("id(a) : ", id(a))
print("id(b) : ", id(b))
print("id(c) : ", id(c))
It will produce the following output −
True
False
id(a) : 140114091859456
id(b) : 140114091906944
id(c) : 140114091859456
The 'is not' operator evaluates to True if both the operand objects do not share the same
memory location or both operands are not the same objects.
a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
c=a
11
print("id(b) : ", id(b))
print("id(c) : ", id(c))
Membership operators in Python are operators used to test whether a value exists in a
sequence, such as a list, tuple, or string.
Output
Yes, banana is a fruit!
12
12. EXPRESSIONS
Logical expression : a or b
Precedence Rules
13
13. SELECTION STATEMENTS
The if statement contains a logical expression using which data is compared and a decision is made
based on the result of the comparison.
Syntax:
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if statement is
executed. If boolean expression evaluates to FALSE, then the first set of code after the end of the if
statement(s) is executed.
-1 a is smaller
Finish
If..else statement
An else statement can be combined with an if statement. An else statement contains the
block of code (false block) that executes if the conditional expression in the if statement
resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only one else
Statement following if.
Syntax of if - else :
if test expression:
Body of if stmts
else:
Body of else stmts
Example of if - else:
a=int(input('enter the number'))
if a>5:
print("a is greater")
14
else:
print("a is smaller than the input given")
Output:
enter the number 2
a is smaller than the input given
If-elif-else:
The elif statement allows us to check multiple expressions for TRUE and execute a block of
code as soon as one of the conditions evaluates to TRUE. Similar to the else, the elif
statement is optional. However, unlike else, for which there can be at most one statement,
there can be an arbitrary number of elif statements following an if.
If test expression:
Body of if stmts
elif test expression:
Body of elif stmts
else:
Body of else stmts
Output:
enter the number5
enter the number2
enter the number9
a is greater
15
14. ITERATION:
There are two types of loops—those that repeat an action a predefined number of
times (definite iteration) and those that perform the action until the program
determines that it needs to stop (indefinite iteration).
While loop:
Loops are either infinite or conditional. Python while loop keeps reiterating a block of
code defined inside it until the desired condition is met.
The while loop contains a boolean expression and the code inside the loop is
repeatedly executed as long as the boolean expression is true.
The statements that are executed inside while can be a single line of code or a block
of multiple statements.
Syntax:
while expression:
Statement(s)
Example 1:
i=1
while i<=6:
print("Hello")
i=i+1
Example 2:
i=1
while i<=3:
print("Hello",end=" ")
j=1
while j<=1:
print("MCA",end="")
j=j+1
i=i+1
print()
16
Output:
Hello MCA
Hello MCA
Hello MCA
Example 3:
i=1
j=1
while i<=3:
print("Hello",end=" ")
while j<=1:
print("MCA",end="")
j=j+1
i=i+1
print()
Output:
Hello MCA
Hello
Hello
For loop:
Python for loop is used for repeated execution of a group of statements for the desired number
of times. It iterates over the items of lists, tuples, strings, the dictionaries and other iterable
objects
Sample Program:
numbers = [1, 2, 4, 6, 11, 20]
seq=0
for val in numbers:
seq=val*val
print(seq)
17
Output:
1
4
16
36
121
400
Output:
college 1 is A
college 2 is S
college 3 is A
college 4 is N
Output:
2
3
5
7
18
print ('Values are:')
for blocks in college.values():
print(blocks)
Output
Keys are:
MBA
MCA
MSC
Values are:
block1
block2
block3
Output:
A
S
A
N
Using the range function with the for loop range simplifies count-controlled for loops
Example:
Numbers from 0 through and up till, but not including, 5 are generated. Equivalent to:
Passing a second argument to range the first is used as the starting point and the second
19
is used as the ending limit
Output:
1
2
3
4
By default the range function increments by 1, passing a third argument defines the step
amount:
Example
The list of non-negative integers that are less than n=3 is [0,1,2] . Print the square of each number on a
separate line.
0
1
4
Input Format
The first and only line contains the integer,.
Constraints
Output Format
Print n lines, one corresponding to each i.
Sample Input 0
5
Sample Output 0
0
1
4
9
16
20
Nested For loop:
When one Loop defined within another Loop is called Nested Loops.
Syntax:
for val in sequence:
for val in sequence:
statements
statements
Output
1
22
333
4444
55555
--------------------------
# Example 2 of Nested For Loops (Pattern Programs)
for i in range(1,6):
for j in range(5,i-1,-1):
print(i, end=" ")
print('')
Output:
11111
2222
333
44
Break:
The break statement terminates the loop containing it and control of the program flows to the
statement immediately after the body of the loop. If break statement is inside a nested loop
(loop inside another loop), break will terminate the innermost loop.
The following shows the working of break statement in for and while loop:
21
# code inside while loop
If condition:
break (if break condition satisfies it jumps to outside loop)
# code inside while loop
# code outside while loop
Example:
for val in "ASAN COLLEGE":
if val == " ":
break
print(val)
print("The end")
Output:
A
S
A
N
The end
Output:
11
9
88
The number 88 is found
Continue:
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
for var in sequence:
# code inside for loop
if condition:
continue (if break condition satisfies it jumps to outside loop)
# code inside for loop
# code outside for loop
22
Example:
# Program to show the use of continue statement inside loops
for val in "string":
if val == "i":
continue
print(val)
print("The end")
Output:
s
t
r
n
g
The end
Output:
11
9
89
Pass:
In Python programming, pass is a null statement. The difference between a comment and pass
statement in Python is that, while the interpreter ignores a comment entirely, pass is not
ignored. pass is just a placeholder for functionality to be added later.
Example:
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass
23
pass
# having an empty for loop like this, would raise an error without the pass statement
24
Unit II: Strings and Text Files: Accessing Characters and substrings in strings - Data
encryption-Strings and Number systems- String methods – Text - Lists and Dictionaries:
Lists – Dictionaries – Design with Functions: A Quick review - Problem Solving with top-
Down Design - Design with recursive Functions - Managing a Program’s namespace -
Higher-Order Functions
1. STRINGS:
A string is a group a sequence of characters. We can use a pair of single or double quotes.
Every string object is of the type ‘str’.
>>> type("name")
<class 'str'>
>>> a=str('asan')
>>> a
'asan'
>>> a=str(asan)
>>> a[2]
'a'
String slices:
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0
Slicing will start from index and will go up to stop in step of steps.
Default value of start is 0,
Stop is last index of list
And for step default is 1
1
For Example 1−
Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Example 2:
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[1:6:2]
'opt'
>>> x[3:]
'puter'
>>> x[:5]
'compu'
>>> x[-1]
'r'
>>> x[-3:]
'ter'
>>> x[:-2]
'comput'
myfile.txt
yourfile.txt
2
String functions and methods:
1. isalnum() Returns true if string has at least 1 character and all characters are alphanumeric
and false otherwise.
2. isalpha() Returns true if string has at least 1 character and all characters are alphabetic and
false otherwise.
3. isdigit() Returns true if string contains only digits and false otherwise.
4. islower() Returns true if string has at least 1 cased character and all cased characters are in
lowercase and false otherwise.
5. isnumeric() Returns true if a string contains only numeric characters and false otherwise.
6. isspace() Returns true if string contains only whitespace characters and false otherwise.
8. isupper() Returns true if string has at least one cased character and all cased characters are
in uppercase and false otherwise.
9. replace(old, new [, max]) Replaces all occurrences of old in string with new or at most max
occurrences if max given.
10. split() Splits string according to delimiter str (space if not provided) and returns list of
substrings;
12. find() Finding the index of the first occurrence of a string in another string
s="Hi there!"
len(s)
9
s.count('e')
2
s.endswith('there!')
True
s.startswith('Hi')
True
3
s.find('the')
3
s.isalpha()
False
'abc!'.isalpha()
False
'abc'.isalpha()
True
'123'.isdigit()
True
words=s.split()
words
['Hi', 'there!']
" ".join(words)
'Hi there!'
s.upper()
'HI THERE!'
s.lower()
'hi there!'
s.replace('i','o')
'Ho there!'
DATA ENCRYPTION
4
Recall that the ord function returns the ordinal position of a character value in the
ASCII sequence, whereas chr is the inverse function.
#File: encrypt.py
plainText = input("Enter a one-word, lowercase message: ")
distance = int(input("Enter the distance value: "))
code = ""
for ch in plainText:
ordvalue = ord(ch)
cipherValue = ordvalue + distance
if cipherValue > ord('z'):
cipherValue = ord('a') + distance - (ord('z') - ordvalue + 1)
code += chr(cipherValue)
print(code)
# File: decrypt.py
code = input("Enter the coded text: ")
distance = int(input("Enter the distance value: "))
plainText = ""
for ch in code:
ordvalue = ord(ch)
cipherValue = ordvalue - distance
if cipherValue < ord('a'):
cipherValue = ord('z') - (distance - (ord('a') - ordvalue - 1))
plainText += chr(cipherValue)
print(plainText)
Output:
Enter a one-word, lowercase message: invaders
Enter the distance value: 3
lqydghuv
5
NUMBER SYSTEM
"""
File: binarytodecimal.py
Converts a string of bits to a decimal integer.
"""
bitString = input("Enter a string of bits: ")
decimal = 0
exponent = len(bitString) - 1
for digit in bitString:
decimal = decimal + int(digit) * 2 ** exponent
exponent = exponent - 1
print("The integer value is", decimal)
TEXT FILES
Text files are simple text where as the binary files contain binary data which is only
readable by computer.
In this type of file, Each line of text is terminated with a special character called EOL
(End of Line), which is the new line character (‘\n’) in python by default.
Text files:
We can create the text files by using the syntax:
Variable name=open (“file.txt”, file mode)
We declared the variable f to open a file named hello.txt. Open takes 2 arguments, the
file that we want to open and a string that represents the kinds of permission or
operation we want to do on the file
Here we used "w" letter in our argument, which indicates write and the plus sign that
means it will create a file if it does not exist in library
The available option beside "w" are "r" for read and "a" for append and plus sign means if it is
not there then create it File Operations
6
Writing Text to a File
f = open("myfile.txt", 'w')
f.write("First line.\nSecond line.\n")
f.close()
f = open("myfile.txt", 'r')
for line in f:
print(line)
Output:
First line.
Second line.
Using readline()
f = open("myfile.txt", 'r')
while True:
line = f.readline()
if line == "":
break
print(line)
Output
First line.
Second line.
7
LISTS
Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
>>> x=list()
>>> x
[]
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
List operations:
These operations include indexing, slicing, adding, multiplying, and checking for
membership
List Indexing
8
L = ['asan', 'college', 'ASAN!']
Output
List slices:
>>> list1=[1,2,3,4,5,6,7,8,9,10]
>>> list1[1:]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list1[:1]
[1]
>>> list1[2:5]
[3, 4, 5]
>>> list1[:6]
[1, 2, 3, 4, 5, 6]
>>> list1[1:2:4]
[2]
>>> list1[1:8:2]
[2, 4, 6, 8]
List methods:
Mutability:
A mutable object can be changed after it is created, and an immutable object can't.
The list data type has some more methods. Here are all of the methods of list objects:
del()
append()
extend()
insert()
pop()
remove()
Reverse()
Sort()
9
Delete: Delete a list or an item from a list
>>> x=[5,3,8,6]
>>> del(x[1]) #deletes the index position 1 in a list
>>> x
[5, 8, 6]
>>> del(x)
>>> x # complete list gets deleted
Insert: To add an item at the specified index, use the insert () method:
>>> x=[1,2,4,6,7]
>>> x.insert(2,10) #insert(index no, item to be inserted)
>>> x
[1, 2, 10, 4, 6, 7]
-------------------------
>>> x.insert(4,['a',11])
>>> x
[1, 2, 10, 4, ['a', 11], 6, 7]
Pop: The pop() method removes the specified index, (or the last item if index is not
specified) or simply pops the last item of list and returns the item.
>>> x=[1, 2, 10, 4, 6, 7]
>>> x.pop()
7
>>> x
[1, 2, 10, 4, 6]
-----------------------------------
>>> x=[1, 2, 10, 4, 6]
>>> x.pop(2)
10
>>> x
[1, 2, 4, 6]
10
Remove: The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]
>>> x.remove(33)
>>> x
[1, 2, 10, 4, 6]
>>> x.remove(4)
>>> x
[1, 2, 10, 6]
Aliasing:
1. An alias is a second name for a piece of data, often easier (and more useful) than
making a copy.
2. If the data is immutable, aliases don’t matter because the data can’t change.
For ex:
a = [81, 82, 83]
b = [81, 82, 83]
print(a == b)
print(a is b)
b=a
print(a == b)
print(a is b)
b[0] = 5
print(a)
Output:
11
True
False
True
True
[5, 82, 83]
Because the same list has two different names, a and b, we say that it is aliased. Changes
made with one alias affect the other. In the example above, you can see that a and b refer to
the same list after executing the assignment statement b = a.
Cloning Lists:
If we want to modify a list and also keep a copy of the original, we need to be able to
make a copy of the list itself, not just the reference. This process is sometimes called
cloning, to avoid the ambiguity of the word copy.
The easiest way to clone a list is to use the slice operator. Taking any slice of a creates
a new list. In this case the slice happens to consist of the whole list.
Example:
a = [81, 82, 83]
b = a[:] # make a clone using slice
print(a == b)
print(a is b)
b[0] = 5
print(a)
print(b)
Output:
True
False
[81, 82, 83]
[5, 82, 83]
Now we are free to make changes to b without worrying about a
Tuples
A tuple is a type of sequence that resembles a list, except that, unlike a list, a tuple is
immutable. You indicate a tuple literal in Python by enclosing its elements in
parentheses instead of square brackets.
12
>>> tuple(veggies)
('celery', 'beans')
Dictionaries:
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.
Key-value pairs
Unordered
Example:
>>> dict1 = {"brand":"asan","model":"college","year":2004}
>>> dict1
{'brand': 'asan', 'model': 'college', 'year': 2004}
13
Dictionary Operations
To access specific value of a dictionary, we must pass its key,
>>> dict1 = {"brand":"asan","model":"college","year":2004}
>>> x=dict1["brand"]
>>> x
'asan'
---------------------
To access keys and values and items of dictionary:
>>> dict1 = {"brand":"asan","model":"college","year":2004}
>>> dict1.keys()
dict_keys(['brand', 'model', 'year'])
>>> dict1.values()
dict_values(['asan', 'college', 2004])
>>> dict1.items()
dict_items([('brand', 'asan'), ('model', 'college'), ('year', 2004)])
-----------------------------------------------
>>> for items in dict1.values():
print(items)
asan
college
2004
brand
model
year
14
>>> for i in dict1.items():
print(i)
('brand', 'asan')
('model', 'college')
('year', 2004)
Add/change values: You can change the value of a specific item by referring to its key
name
>>> dict1 = {"brand":"asan","model":"college","year":2004}
>>> dict1["year"]=2005
>>> dict1
{'brand': 'asan', 'model': 'college', 'year': 2005}
15
FUNCTIONS
Function is a group of related statements that perform 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. It avoids
repetition and makes code reusable.
integer = -20
print('Absolute value of -20 is:', abs(integer))
Output:
Absolute value of -20 is: 20
Steps
1. Defining a function
2. Calling a function
def sum():
a=5
b=3
result = a + b
print("Sum - without parameters and no return:", result)
16
3. Function without parameters, with return type
def sum():
a=7
b=2
return a + b
def sum(a,b):
result = a + b
return result
Return Statement
The syntax of the return statement for these cases is the following:
return
Upon encountering a return statement, Python evaluates the expression and immediately
transfers control back to the caller of the function. The value of the expression is also sent
back to the caller.
If a function contains no return statement, Python transfers control to the caller after the last
statement in the function’s body is executed, and the special value None is automatically
returned.
Parameters are passed during the definition of function while Arguments are passed
during the function call.
1. Default Arguments:
Function arguments can have default values. We can provide a default value to an argument by using
the assignment operator (=).
Example:
def greet(name, msg="Good morning!"):
print("Hello", name + ', ' + msg)
17
greet("Asan")
greet("MCA", "Welcome to Python")
Output:
Hello Asan, Good morning!
Hello MCA, Welcome to Python
2. Keyword Arguments:
• Python allows functions to be called using keyword arguments. When we call functions in
this way, the order (position) of the arguments can be changed.
• Following calls to the above function are all valid and produce the same result.
# keyword arguments
greet(name = "ASAN",msg = "Good Morning")
Output:
Hello ASAN, Good Morning
Hello ASAN, Good Morning
Hello ASAN, Good Morning
Example:
greet(name="ASAN","Good Morning”)
:def greet(*names):
# names is a tuple with arguments
for name in names:
print("Hello", name)
18
Output:
Hello AAA
Hello BBB
Hello CCC
Hello DDD
def main():
"""The main function for this script."""
number = float(input("Enter a number: "))
result = square(number)
print("The square of", number, "is", result)
def square(x):
"""Returns the square of x."""
return x * x
19
Recursive Function:
• A function that calls itself is known as Recursive Function.
• The following image shows the working of a recursive function
Example:
• Factorial of a number
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Output:
The factorial of 3 is 6
20
Advantages of Recursion:
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration
.
Disadvantages of Recursion:
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.
1. Mapping
2. Filtering
3. Reducing
4. Using lambda to create anonymous functions
Mapping
Map in Python is a function that works as an iterator to return a result after applying a
function to every item of an iterable (tuple, lists, etc.).
It is used when you want to apply a single transformation function to all the iterable
elements.
map(function, iterables)
Example:
# Defining a function
def mul(i):
return i * i
Output:
21
Filtering
The filter() function returns an iterator where the items are filtered through a function
to test if the item is accepted or not.
Syntax
filter(function, iterable)
Parameter Values
def check_even(number):
if number % 2 == 0:
return True
return False
# converting to list
even_numbers = list(result)
print(even_numbers)
Reducing
In Python, reduce() is a built-in function that applies a given function to the elements
of an iterable, reducing them to a single value.
22
o The function argument is a function that takes two arguments and returns a single
value. The first argument is the accumulated value, and the second argument is the
current value from the iterable.
o The iterable argument is the sequence of values to be reduced.
o The optional initializer argument is used to provide an initial value for the
accumulated result. If no initializer is specified, the first element of the iterable is used
as the initial value.
Example
# Our Iterable
num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# add function is passed as the first argument, and num_list is passed as the second ar
gument
sum = reduce(add, num_list)
#converting to a list
addresult=list(sum)
print(addresult)
Output
55
65
23
Using lambda to create anonymous function
Example 1:
Output:
10
Example 2:
x = lambda a, b : a * b
print(x(5, 6))
Output:
30
One popular design strategy for programs of any significant size and complexity is called top-
down design.
This strategy starts with a global view of the entire problem and breaks the problem into
smaller, more manageable subproblems—a process known as problem decomposition.
As functions are developed to solve each subproblem, the solution to the overall problem is
gradually filled out in detail. This process is also called stepwise refinement
For example, the function countSentences takes a string as an argument and returns the
number of sentences in that string. Note that all functions except one are just one level below
24
main. Because this program does not have a deep structure, the programmer can develop it
quickly just by thinking of the results that main needs to obtain from its collaborators
In Python, there are libraries, variables, functions, and modules. So, there are high chances
that the name of a variable you choose already exists as the name of another variable,
function, or method. So, in such circumstances, we need to know how Python manages these
names. This concept is referred to as Namespace.
In Python, there are several types of namespaces that are used to organize objects and prevent
name conflicts. Here is a list of the different types of namespaces in Python, along with
examples of each:
1. Built-in namespace: This namespace contains objects that are built into Python,
such as the built-in functions and exception classes. For example,
the abs function and the Exception class are both part of the built-in namespace.
# Built-in namespace
print(abs(-10))
# prints the absolute value of -10 using the built-in function "abs"
25
2. Global namespace: This namespace contains objects that are defined at the top
level of a module or script. For example, variables and functions defined at the
top level of a module are part of the global namespace.
# Global namespace
x = 10
# creates a global variable named "x"
def foo():
# Local namespace
y = 20 # creates a local variable named "y"
print(y) # prints the value of the local variable "y"
foo()
4. Module namespace: This namespace contains objects that are defined within a
module. For example, variables, functions, and classes defined within a module
are part of the module namespace for that module.
# Module namespace
import math
print(math.pi)
5. Class namespace: This namespace contains objects that are defined within a
class. For example, methods and attributes defined within a class are part of the
class namespace for that class.
class MyClass:
# Class namespace
z = 30 # creates a class attribute named "z"
obj = MyClass()
print(obj.z) # prints the value of the class attribute "z"
26
DIFFERENT TYPES OF SCOPES IN PYTHON:
In Python, the built-in scope refers to the region of a program where the built-in functions
and variables are recognized and can be accessed.
Built-in Scope: The built-in functions and variables are defined by the Python interpreter and
are always available for use in your code. They include functions like print(), len(),
and range(), as well as variables like True, False, and None. Here is an example of how to
access built-in functions and variables in Python:
print(len('hello')) # prints 5
print(range(5)) # prints [0, 1, 2, 3, 4]
print(True) # prints True
print(None) # prints None
len = 5 # this will cause a SyntaxError because len is a built-in function and cannot be
reassigned
del True # this will cause a SyntaxError because True is a built-in variable and cannot be
deleted
Global Scope: A global scope refers to the region of a program where a variable is defined
and can be accessed from anywhere in the code. Here is an example of how to create and
access a global variable in Python:
x = 10 # x is a global variable
def foo():
print(x) # we can access the global variable x inside the function
foo()
print(x) # we can also access the global variable x outside the function
Local Scope: A local scope refers to the region of a program where a variable is defined and
can only be accessed within that region. Local scopes can be created within functions or
within class methods. Here is an example of how to create and access a local variable in
Python:
def foo():
x = 5 # x is a local variable
print(x) # we can access the local variable x inside the function
foo()
print(x) # this will cause an error because x is a local variable and is not defined outside the
function
27
Nested / Enclosed Scope: There is also a third type of scope in Python called a nested scope,
which refers to a local scope within another local scope. Nested scopes are created when one
function is defined inside another function.
Example
def outer():
def inner():
outer()
# Trying to access x and y from outside the functions will cause an error:
28
Unit III: Design with Classes: Getting inside Objects and Classes – Data-Modeling Examples
– Building a New Data Structure – The Two – Dimensional Grid - Structuring Classes with
Inheritance and Polymorphism-Graphical User Interfaces-The Behavior of terminal-Based
programs and GUI-Based programs - Coding Simple GUI-Based programs - Windows and
Window Components - Command Buttons and responding to events
class is a user-defined data type that contains both the data itself and the methods
classes serve as a template to create objects.
Objects:
The object is an entity that has state and behavior. It is an instance of a class that can access
the data.
Class Declaration
class ClassName:
# list of python class variables
# python class constructor
# python class method definitions
Example
class Person:
#initializing the instance variables
name = ""
age = 0
#defining constructor
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
def showAge(self):
print(self.age)
1
#Create another object of the same class
person2 = Person("Deepak", 102)
‘name’ and ‘age’ are two member variables of the class ‘Person’.
Every time we declare an object of this class, it will contain these two variables as its
member.
This part is optional as they can be initialized by the constructor.
Python Constructor
The self parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the first
parameter of any function in the class:
statements……..
We use an object and dot (.) operator to execute the block of code or action defined in the
instance method or variables
Person1.showAge()
2
2. __str__ Method
The __str__ method is a special method in Python classes that is used to define a
string representation of an object.
In Python, the __str__ method is called automatically when an object is used in a string
context, such as when it is printed, or when the built-in str() function is called on the
object.
For example, consider the following class My_person_class with an __str__ method defined:
class My_person_class:
def __init__(self, name, city, age):
self.name = name
self.city = city
self.age = age
def __str__(self):
return "{self.name} who lives in {self.city} is {self.age} years old"
Output
Operator overloading is a feature of Python that lets you use the same operator for
more than one task. This is also called polymorphism.
3
Overloading the Addition Operator- To overload the addition operator, you can define the
add method in your class.
The following example shows how to overload the addition operator for a class that represents
a point in two-dimensional space.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p1=Point(10,11)
p2=Point(20,21)
p3=p1+p2 //addition operator overloading
To overload the less than operator, you can define the lt method in your class.
The following example shows how to overload the less than operator for a class that
represents a rectangle.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
r1=Rectangle(2,5)
r2=Rectangle(5,10)
4
4. DATA MODELLING EXAMPLES
A simplified version of a savings account includes an owner’s name, PIN, and balance as
attributes.
The interface for a SavingsAccount class is listed in Table.
5
class SavingsAccount:
RATE = 0.02 # Single rate for all accounts
def __str__(self) :
"""Returns the string rep."""
result = 'Name: ' + self.name + '\n'
result += 'PIN: ' + self.pin + '\n'
result += 'Balance: ' + str(self.balance)
return result
def getBalance(self):
"""Returns the current balance."""
return self.balance
def getName(self):
"""Returns the current name."""
return self.name
def getPin(self):
"""Returns the current pin."""
return self.pin
def computeInterest(self):
"""Computes, deposits, and returns the interest."""
interest = self.balance * SavingsAccount.RATE
self.deposit(interest)
return interest
6
bank = SavingsAccount(("Wilma", "1001", 4000.00)
print(bank)
Output
Name: Wilma
PIN: 1001
Balance: 4000.00
Exception Handling
Python try...except Block
Syntax
try:
statements
except Exception1:
statements
except Exception2:
statements
else:
statements
finally:
statements
7
Example: Exception Handling Using try...except
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
For example,
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.")
Python includes several basic types of data structures, such as strings, lists, tuples, and
dictionaries.
Another useful data structure is a two-dimensional grid. A grid organizes items by position in
rows and columns
Array is basically a data structure that stores data in a linear fashion. There is no exclusive
array object in Python because the user can perform all the operations of an array using a list.
The array is an ordered collection of elements in a sequential manner.
8
Declaration of Two Dimensional Array
Example:
Output
[10,12,14]
[0,1,2]
Input to an array
from array import *
size = int(input())
array_input = []
for x in range(size):
array_input.append([int(y) for y in input().split()])
print(array_input)
Output
input.insert(1, [1,3,5,7,9])
print("Array after insertion of elements: ")
for x in input:
for y in x:
9
print(y,end = " ")
print()
Output
Delete values
del(input[1])
print("Array after Deletion of elements: ")
for x in input:
for y in x:
print(y,end = " ")
print()
10
7. INHERITANCE
Syntax
# define a superclass
class super_class:
# attributes and method definition
# inheritance
class sub_class(super_class):
# attributes and method of super_class
# attributes and method of sub_class
Here, we are inheriting the sub_class class from the super_class class.
def eat(self):
print("I can eat")
Output
I can eat
My name is Rohu
11
Method Overriding in Python Inheritance
However, what if the same method is present in both the superclass and subclass?
In this case, the method in the subclass overrides the method in the superclass. This concept is
known as method overriding in Python.
def eat(self):
print("I can eat")
Output
I like to eat bones
For example,
class Animal:
name = ""
def eat(self):
print("I can eat")
12
class Dog(Animal):
labrador.eat()
Output
I can eat
I like to eat bones
Uses of Inheritance
Since a child class can inherit all the functionalities of the parent's class, this allows
code reusability.
Inherits the methods and attributes from one or more parent classes.
Syntax
class Base_1:
#attributes and methods
class Base_2:
#attributes and methods
Example
class A:
def A(self):
print('This is class A.')
class B:
def B(self):
print('This is class B.')
class C(A,B):
def C(self):
13
print('This is class C which inherits features of both classes A and B.')
o = C()
o.A()
o.B()
o.C()
Output
This is class A.
This is class B.
This is class C which inherits features of both classes A and B.
8. DOCSTRING IN PYTHON
Docstring is a short form of documentation strings. These are string literals that are
used within a particular program or a piece of code.
Declaring Docstrings:
Docstrings are declared using triple double quotes “”” just below the method or class
definition.
It is recommended that all functions are provided with a docstring.
Accessing Docstrings:
def myProgram():
"""Demonstrate docstrings in Python."""
return None
print(myProgram.__doc__)
GUI displays all information, including text, graphically to its users and allows them to
manipulate this information directly with a pointing device
14
GUI Based Version
The GUI-based version of the program displays a window that contains various
components, also called widgets.
Some of these components look like text, while others provide visual cues as to their
use.
Programmers import breezypythongui into their applications and start writing GUI-
based programs the easy way.
Definition: breezypythongui is a module of classes that takes the pain out of writing
GUI-based programs.
15
breezypythongui is not a GUI builder, editor, or development environment. Instead,
it simplifies the user interface and event model for programmers by subclassing various
classes in Python’s tkinter framework.
Easy to use because you don’t need to know the details of tkinter resources.
Easy to install because it is contained in a Python module.
Flexible and extensible because the source code is provided.
class LabelDemo(EasyFrame):
"""Displays a greeting in a window."""
def __init__(self):
"""Sets up the window and the label."""
EasyFrame.__init__(self)
self.addLabel(text = "Hello world!", row = 0, column = 0)
def main():
"""Instantiates and pops up the window."""
LabelDemo().mainloop()
if __name__ == "__main__":
main()
16
Window Layout
Window components are laid out in the window’s two-dimensional grid. The grid’s
rows and columns are numbered from the position (0, 0) in the upper left corner of the
window.
A window component’s row and column position in the grid is specified when the
component is added to the window.
For example, the following program labels the four quadrants of the window shown in
Figure 8-5:
class LayoutDemo(EasyFrame):
"""Displays labels in the quadrants."""
def __init__(self):
"""Sets up the window and the labels."""
EasyFrame.__init__(self)
self.addLabel(text = "(0, 0)", row = 0, column = 0)
self.addLabel(text = "(0, 1)", row = 0, column = 1)
self.addLabel(text = "(1, 0)", row = 1, column = 0)
self.addLabel(text = "(1, 1)", row = 1, column = 1)
17
D) Command Buttons and responding to events
A command button is added to a window just like a label, by specifying its text and position in the
grid. A button is centered in its grid position by default. The method addButton accomplishes all this
and returns an object of type tkinter.Button.
The following program displays a single label and two command buttons. The buttons allow the user to
clear or restore the label. When the user clicks Clear, the label is erased, the Clear button is disabled,
and the Restore button is enabled. When the user clicks Restore, the label is redisplayed, the Restore
button is disabled, and the Clear button is enabled.
18
class ButtonDemo(EasyFrame):
"""Illustrates command buttons and user events."""
def __init__(self):
"""Sets up the window, label, and buttons."""
EasyFrame.__init__(self)
# Two command buttons in the second row, with event handler methods supplied.
self.clearBtn = self.addButton(text = "Clear", row = 1, column = 0, command = self.clear)
self.restoreBtn = self.addButton(text = "Restore", row = 1, column = 1, state = "disabled",
command = self.restore)
def restore(self):
"""Resets the label to 'Hello world!' and updates the button states."""
self.label["text"] = "Hello world!"
self.clearBtn["state"] = "normal"
self.restoreBtn["state"] = "disabled"
19