Ilovepdf Merged

Download as pdf or txt
Download as pdf or txt
You are on page 1of 71

Unit I: Introduction : Fundamental ideas of Computer Science - Strings, Assignment, and

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

FUNDAMENTAL IDEAS OF COMPUTER SCIENCE (Algorithms and Information


Processing)
1. Algorithms
 The sequence of steps that describes each of these computational processes is called an
algorithm.
 Informally, an algorithm is like a recipe. It provides a set of instructions that tells us how to
do something, such as make change, bake bread, or put together a piece of furniture.
 More precisely, an algorithm describes a process that ends with a solution to a problem.
 The algorithm is also one of the fundamental ideas of computer science.
 An algorithm has the following features:
1. An algorithm consists of a finite number of instructions.
2. Each individual instruction in an algorithm is well defined.
3. An algorithm describes a process that eventually halts after arriving at a solution to a
problem. For example, the process of subtraction halts after the computing agent writes down
the difference between the two digits in the leftmost column of digits.
4. An algorithm solves a general class of problems. For example, an algorithm that describes
how to make change should work for any two amounts of money whose difference is greater
than or equal to $0.00.
2. Information Processing
 Information processing consists of locating and capturing information, using software to
manipulate it into a desired form, and outputting the data. An Internet search engine is an
example of an information-processing tool, as is any sophisticated information-retrieval
system.

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.

2. Writing first program


# Script Begins
Statement1
Statement2
Statement3
# Script Ends

1
3. Difference between a scripting language and programming language

Scripting Languages Programming Language


A scripting language is a type of A programming language is a computer
programming language that supports scripts, language which is used to communicate
which are small programs mainly used to with computers using a set of instructions.
automate the execution of a specific
function in a specific runtime environment.
Scripting languages are interpreted within Programming languages use compiler and
another program; for example, JavaScript do not require to be interpreted by another
has to be combined within HTML, then language or application; hence these
interpreted by the web browser. languages run independently and do not
depend on the parent program.
It is comparatively easy to write code in the It is comparatively difficult to write code in
scripting language, and it requires few lines a programming language, and it requires
of code for each task. numerous lines of code for each task.
Scripting languages, on the other hand, Programming languages use a compiler, it
demand line-by-line conversion. is a one-shot conversion.
Some popular examples are Perl, Python, Some popular examples are C, C++, Java,
JavaScript, etc. Scala, COBOL, etc.

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.

There are two modes for using the Python interpreter:


• Interactive Mode
• Script Mode

Running Python in interactive mode:


Without passing python script file to the interpreter, directly execute code to Python prompt.
Once you’re inside the python interpreter, then you can start.
>>> print("hello world")
hello world

Running Python in script mode:


Alternatively, programmers can store Python script source code in a file with the .py
extension, and use the interpreter to execute the contents of the file.

6. PYTHON CHARACTER SETS


 A character set is a set of valid characters acceptable by a programming language in
scripting.
 These are the characters we can use during writing a script in Python. Python supports
all ASCII / Unicode characters that include:

 Alphabets: All capital (A-Z) and small (a-z) alphabets.


 Digits: All digits 0-9.
 Special Symbols: Python supports all kind of special symbols like, ” ‘ l ; : ! ~ @ # $
%^`&*()_+–={}[]\.
 White Spaces: White spaces like tab space, blank space, newline, and carriage
return.

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

 Python has no command for declaring a variable.


 A variable is created the moment you first assign a value to it.

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

Many Values to Multiple Variables


 Python allows you to assign values to multiple variables in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
One Value to Multiple Variables

Example

x = y = z = "Orange"
print(x)
print(y)
print(z)

4
9. INPUT FUNCTION IN PYTHON

The input() function allows user input.

Example

Use the prompt parameter to write a message before the input:

x = input('Enter your name:')


print('Hello, ' + x)

Output

10. Python Data Types

Data Types Classes Description

Numeric int, float, complex holds numeric values

String str holds sequence of characters

Sequence list, tuple, range holds collection of items

Mapping dict holds data in key-value pair form

Boolean bool holds either True or False

Set set hold collection of unique items

Numeric Data types

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:

#create a variable with integer value.


a=100
print("The type of variable having value", a, " is ", type(a))

#create a variable with float value.


b=10.2345

5
print("The type of variable having value", b, " is ", type(b))

#create a variable with complex value.


c=100+3j
print("The type of variable having value", c, " is ", type(c))

Output

String Data Types

The string is a sequence of characters. Python supports Unicode characters. Generally, strings
are represented by either single or double-quotes.

a = "string in a double quote"


b= 'string in a single quote'
print(a)
print(b)

# using ',' to concatenate the two or several strings


print(a,"concated with",b)

#using '+' to concate the two or several strings


print(a+" concated with "+b)

List Data type

 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(,).

#list of having only integers


a= [1,2,3,4,5,6]
print(a)

#list of having only strings


b=["hello","john","reese"]
print(b)

6
#list of having both integers and strings
c= ["hey","you",1,2,3,"go"]
print(c)

#index are 0 based. this will print a single character


print(c[1]) #this will print "you" in list c

Output

Tuple data type


The tuple is another data type which is a sequence of data similar to a list. But it is
immutable. That means data in a tuple is write-protected. Data in a tuple is written using
parenthesis and commas.

#tuple having only integer type of data.


a=(1,2,3,4)
print(a) #prints the whole tuple

#tuple having multiple type of data.


b=("hello", 1,2,3,"go")
print(b) #prints the whole tuple

#index of tuples are also 0 based.

print(b[4]) #this prints a single element in a tuple, in this case "go"

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.

#a sample dictionary variable

a = {1:"first name",2:"last name", "age":33}

#print value having key=1


print(a[1])

7
#print value having key=2
print(a[2])
#print value having key="age"
print(a["age"])

Boolean data type

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'>

Set data type


Sets in Python are an unordered collection of elements. They contain only unique elements.
They are mutable, i.e. their values can be modified.

Syntax:

Sets are of the type set. They are created by elements separated by commas enclosed in curly
brackets {}.

# Python program for demonstrating sets.

my_set = {1, 8, "Scaler", "F", 0, 8}

print(my_set)
print("Its data type:", type(my_set))

Output:

{0, 1, 'F', 8, 'Scaler'}


Its data type: <class 'set'>

8
11. OPERATORS IN PYTHON

Python divides the operators in the following groups:

 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.

Example of Python Identity 'is' Operator

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

Python 'is not' Operator

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.

Example of Python Identity 'is not' Operator

a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
c=a

# Comparing and printing return values


print(a is not c)
print(a is not b)

# Printing IDs of a, b, and c


print("id(a) : ", id(a))

11
print("id(b) : ", id(b))
print("id(c) : ", id(c))

It will produce the following output −


False
True
id(a) : 140559927442176
id(b) : 140559925598080
id(c) : 140559927442176

Membership operators in Python are operators used to test whether a value exists in a
sequence, such as a list, tuple, or string.

# using "in" operator


fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Yes, banana is a fruit!")

# using "not in" operator


if "orange" not in fruits:
print("Yes, orange is not in the list of fruits")

Output
Yes, banana is a fruit!

Yes, orange is not in the list of fruits

12
12. EXPRESSIONS

 An expression in Python is any valid combination of operators, literals and variables.

In python there can be the following types of expressions:

 Arithmetic expression : a+b

 Relational expression : a>b

 Logical expression : a or b

 String expression : “1+1”

 Compound expression: a+b>c**d

Precedence Rules

 Exponentiation has the highest precedence and is evaluated first.


 Unary negation is evaluated next, before multiplication, division, and remainder.
 Multiplication, both types of division, and remainder are evaluated before addition
and subtraction.
 Addition and subtraction are evaluated before assignment.
 With two exceptions, operations of equal precedence are left associative, so they are
evaluated from left to right. Exponentiation and assignment operations are right
associative, so consecutive instances of these are evaluated from right to left.
 You can use parentheses to change the order of evaluation

13
13. SELECTION STATEMENTS

Selection statements, or control statements, that allow a computer to make choices

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.

Example: Python if Statement


a=3
if a > 2:
print(a, "is greater")
print("done")
a = -1
if a < 0:
print(a, "a is smaller")
print("Finish")
Output:
3 is greater
Done

-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.

Syntax of if – elif - else :

If test expression:
Body of if stmts
elif test expression:
Body of elif stmts
else:
Body of else stmts

Example of if - elif – else:


a=int(input('enter the number'))
b=int(input('enter the number'))
c=int(input('enter the number'))
if a>b:
print("a is greater")
elif b>c:
print("b is greater")
else:
print("c is greater")

Output:
enter the number5
enter the number2
enter the number9
a is greater

Exercise for if--else

Given an integer, n , perform the following conditional actions:


 If n is odd, print Weird
 If n is even and in the inclusive range of 2 to 5, print Not Weird
 If n is even and in the inclusive range of 6 to 20, print Weird
 If n is even and greater than 20, print Not Weird

15
14. ITERATION:

 A loop statement allows us to execute a statement or group of statements multiple


times as long as the condition is true. Repeated execution of a set of statements with
the help of loops is called 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).

In Python Iteration (Loops) statements are of three types:


1. While Loop
2. For Loop
3. Nested For Loops

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

Iterating over a list:


#list of items
list = ['A','S','A','N']
i=1
#Iterating over the list
for item in list:
print ('college ',i,' is ',item)
i = i+1

Output:
college 1 is A
college 2 is S
college 3 is A
college 4 is N

Iterating over a Tuple:


tuple = (2,3,5,7)
print ('These are the first four prime numbers ')
#Iterating over the tuple
for a in tuple:
print (a)

Output:
2
3
5
7

Iterating over a dictionary:


#creating a dictionary
college = {"MBA":"block1","MCA":"block2","MSC":"block3"}

#Iterating over the dictionary to print keys


print ('Keys are:')

for keys in college:


print (keys)

#Iterating over the dictionary to print values

18
print ('Values are:')
for blocks in college.values():
print(blocks)

Output

Keys are:
MBA
MCA
MSC
Values are:
block1
block2
block3

Iterating over a String:


#declare a string to iterate over
college = 'ASAN'
#Iterating over the string
for name in college:
print (name)

Output:
A
S
A
N

Using the range function with the for loop range simplifies count-controlled for loops

The Python range() function returns a sequence of numbers, in a given range.


Syntax
for <variable> in range(<lower bound>, <upper bound + 1>):
<loop body>

Example:

for num in range(5):


print num

Numbers from 0 through and up till, but not including, 5 are generated. Equivalent to:

for num in [0, 1, 2, 3, 4]:


print num

Passing a second argument to range the first is used as the starting point and the second

19
is used as the ending limit

for num in range(1, 5):


print num

Output:
1
2
3
4

By default the range function increments by 1, passing a third argument defines the step
amount:

for num in range(1, 10, 2):


print num
Output:
1
3
5
7
9
Exercise
Task
The provided code stub reads and integer, , from STDIN. For all non-negative integers i<n, print i2.

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

# Example 1 of Nested For Loops (Pattern Programs)


for i in range(1,6):
for j in range(0,i):
print(i, end=" ")
print('')

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:

for var in sequence:


# code inside for loop
if condition:
break (if break condition satisfies it jumps to outside loop)
# code inside for loop
# code outside for loop

while test expression

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

# Program to display all the elements before number 88


for num in [11, 9, 88, 10, 90, 3, 19]:
print(num)
if(num==88):
print("The number 88 is found")
print("Terminating the loop")
break

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

while test expression


# code inside while loop
If condition:
continue(if break condition satisfies it jumps to outside loop)
# code inside while loop
# code outside while 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

# program to display only odd numbers


for num in [20, 11, 9, 66, 4, 89, 44]:
# Skipping the iteration when number is even
if num%2 == 0:
continue
# This statement will be skipped for all even numbers
print(num)

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

Output: #no output

for x in [0, 1, 2]:

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'

>>> fruit = 'banana'

>>> letter = fruit[1]

String slices:

A segment of a string is called a slice. Selecting a slice is similar to selecting a character:

Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0

in the beginning of the string and -1 at the end.

Syntax:[Start: stop: steps]

 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−

str = 'Hello World!'

print (str) # Prints complete string


print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character print
str * 2 # Prints string two times
print (str + "TEST") # Prints concatenated string

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'

Testing for a substring using in operator

fileList = ["myfile.txt", "myprogram.exe", "yourfile.txt"]


for fileName in fileList:
if ".txt" in fileName:
print(fileName)
Output:

myfile.txt

yourfile.txt

2
String functions and methods:

There are many methods to operate on String.

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.

7. istitle() Returns true if string is properly “titlecased” 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;

11. count() Occurrence of a string in another string

12. find() Finding the index of the first occurrence of a string in another string

13. swapcase() Converts lowercase letters in a string to uppercase and viceversa

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!'

" Hi there ".strip()


'Hi there'

DATA ENCRYPTION

 Data encryption to protect information transmitted on networks.


 The sender encrypts a message by translating it to a secret code, called a cipher text.
At the other end, the receiver decrypts the cipher text back to its original plaintext
form.
 Simple encryption method called Caesar cipher.
 This encryption strategy replaces each character in the plaintext with the character
that occurs a given distance away in the sequence. For example, if the distance value
of a Caesar cipher equals three characters, the string "invaders" would be encrypted as
"lqydghuv". To decrypt this cipher text back to plaintext, you apply a method that
uses the same distance value but looks to the left of each character for its replacement.

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

Enter the coded text: lqydghuv


Enter the distance value: 3
invaders

5
NUMBER SYSTEM

Converting Binary to Decimal

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

Enter a string of bits: 1111


The integer value is 15
Enter a string of bits: 101
The integer value is 5

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)

For ex: f= open ("hello.txt","w+")

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

Reading Text from a File

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

 It is a general purpose most widely used in data structures


 List is a collection which is ordered and changeable and allows duplicate members.
 (Grow and shrink as needed, sequence type, sortable).
 To use a list, you must declare it first. Do this using square brackets and separate
values with commas.
 We can construct / create list in many ways.

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

Basic List Operations:

List Indexing

Assuming following input −

8
L = ['asan', 'college', 'ASAN!']

Output

L[2] gives ASAN!

L[-2] gives college (Negative: count from the right)

L[1:] gives [‘college’,’ASAN!’] (Slicing fetches sections)

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

Append: Append an item to a list


>>> x=[1,5,8,4]
>>> x.append(10)
>>> x
[1, 5, 8, 4, 10]

Extend: Append a sequence to a list.


>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 3, 6, 9, 1]

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]

Reverse: Reverse the order of a given list.


>>> x=[1,2,3,4,5,6,7]
>>> x.reverse()
>>> x
[7, 6, 5, 4, 3, 2, 1]

Sort: Sorts the elements in ascending order


>>> x=[7, 6, 5, 4, 3, 2, 1]
>>> x.sort()
>>> x
[1, 2, 3, 4, 5, 6, 7]
-----------------------
>>> x=[10,1,5,3,8,7]
>>> x.sort(reverse=True)
>>> x
[10,8,7,5,3,1,]

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.

>>> fruits = ("apple", "banana")


>>> fruits
('apple', 'banana')

>>> meats = ("fish", "poultry")


>>> meats
('fish', 'poultry')

>>> food = meats + fruits


>>> food
('fish', 'poultry', 'apple', 'banana')

>>> veggies = ["celery", "beans"]

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}

Operations and methods:


Methods that are available with dictionary are tabulated below. Some of them have already
been used in the above examples.

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

>>> for items in dict1.keys():


print(items)

brand
model
year

14
>>> for i in dict1.items():
print(i)
('brand', 'asan')
('model', 'college')
('year', 2004)

Some more operations like:


 Add/change
 Remove
 Length
 Delete

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}

Remove(): It removes or pop the specific item of dictionary.


>>> dict1 = {"brand":"asan","model":"college","year":2005}
>>> print(dict1.pop("model"))
college
>>> dict1
{'brand': 'asan', 'year': 2005}

Delete: Deletes a particular item.


>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> del x[5]
>>> x
{1: 1, 2: 4, 3: 9, 4: 16}

Length: we use len() method to get the length of dictionary.


>>>x={1: 1, 2: 4, 3: 9, 4: 16}
>>> y=len(x)
>>> y
4

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.

Two types of Functions:


1. Built-in functions - Functions that are built into Python.

Ex: abs(), ascii(), bool()………so on….

integer = -20
print('Absolute value of -20 is:', abs(integer))
Output:
Absolute value of -20 is: 20

2. User-defined functions - Functions defined by the users themselves.

Steps
1. Defining a function
2. Calling a function

Syntax for defining a function

Types of Parameter Passing techniques in Function

1. Function without parameters, no return type

def sum():
a=5
b=3
result = a + b
print("Sum - without parameters and no return:", result)

# Calling the function


sum()

2. Function with parameters, no return type

def sum(a, b):


result = a + b
print("Sum - with parameters and no return):", result)

# Calling the function


sum(10, 20)

16
3. Function without parameters, with return type

def sum():
a=7
b=2
return a + b

# Calling the function and store the result


result = sum()
print("Sum - without parameters and with return:", result)

4. Function with parameters, with return type

def sum(a,b):
result = a + b
return result

# Calling the function and store the result


result = sum(20,30)
print("Sum - with parameters and with 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 and arguments:

 Parameters are passed during the definition of function while Arguments are passed
during the function call.

Three different forms of Function Arguments :


1. Default Arguments.
2. Keyword Arguments.
3. Arbitrary Arguments/Variable Length Arguments.

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

# keyword arguments (out of order)


greet(msg = "Good Morning",name = "ASAN")

#1 positional, 1 keyword argument


greet("ASAN", msg = "Good Morning")

Output:
Hello ASAN, Good Morning
Hello ASAN, Good Morning
Hello ASAN, Good Morning

• Having a positional argument after keyword arguments will result in errors.

Example:

greet(name="ASAN","Good Morning”)

Output: SyntaxError: non-keyword arg after keyword arg

3. Arbitrary Arguments / Variable Length Arguments:


• Sometimes, we do not know in advance the number of arguments that will be passed into a
function.
• Python allows us to handle this kind of situation through function calls with an arbitrary
number of arguments.
• In the function definition, we use an asterisk (*) before the parameter name to denote this
kind of argument.

:def greet(*names):
# names is a tuple with arguments
for name in names:
print("Hello", name)

greet("AAA", "BBB", "CCC", "DDD")

18
Output:
Hello AAA
Hello BBB
Hello CCC
Hello DDD

Main function in Python

 main() as it is usually denoted. It essentially serves as a starting point for the


execution of a program.
 In Python, it is not necessary to define the main function every time you write a
program.
 This is because the Python interpreter executes from the top of the file unless a
specific function is defined.
 Hence, having a defined starting point for the execution of your Python program is
useful to better understand how your program works.

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

# The entry point for program execution


if __name__ == "__main__":
main()

 It is not a compulsion to have a a Main Function in Python, however, In the above


example, you can see, there is a function called ‘main()’.
 This is followed by a conditional ‘if’ statement that checks the value of __name__,
and compares it to the string “__main__“. On evaluation to True, it executes main().

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.

HIGHER ORDER FUNCTIONS IN PYTHON

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.

Syntax of Map in Python

map(function, iterables)

In the above syntax:


 function: It is the transformation function through which all the items of the iterable will
be passed.
 iterables: It is the iterable (sequence, collection like list or tuple) that you want to map.

Example:

# Defining a function
def mul(i):
return i * i

# Using the map function


x = map(mul, (3, 5, 7, 11, 13))
print (x)
print(list(x))

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

 Function- Function to be run for each item in the iterable


 iterable- The iterable to be filtered

# returns True if the argument passed is even

def check_even(number):
if number % 2 == 0:
return True

return False

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# if an element passed to check_even() returns True, select it


result= filter(check_even, numbers)

# converting to list
even_numbers = list(result)

print(even_numbers)

# Output: [2, 4, 6, 8, 10]

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.

The syntax for reduce() is as follows:

reduce(function, iterable[, initializer])

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

# Function that returns the sum of two numbers


def add(a, b):
return a + b

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

# Passing 10 as an initial value


sum = reduce(add, num_list, 10)
#converting to a list
addresult=list(sum)
print(addresult)

Output

55
65

23
Using lambda to create anonymous function

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


 while normal functions are defined using the def keyword in Python, anonymous
functions are defined using the lambda keyword.
 Hence, anonymous functions are also called lambda functions.
 Lambda functions can have any number of arguments but only one expression. The
expression is evaluated and returned. Lambda functions can be used wherever
function objects are required.

Syntax of Lambda Function:

lambda arguments: expression

Example 1:

# Program to show the use of lambda functions


double = lambda x: x * 2
print(double(5))

Output:
10

Example 2:

x = lambda a, b : a * b
print(x(5, 6))

Output:
30

Use of Lambda Function in python:


• We use lambda functions when we require a nameless function for a short period of time.

PROBLEM SOLVING WITH TOP DOWN DESIGN

 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

Example – Design of a text analysis program

 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

MANAGING A PROGRAM’S NAMESPACE

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

3. Local namespace: This namespace is created whenever a function is called, and


it contains objects that are defined within the function. For example, variables
and functions defined within a function are part of the local namespace for that
function. The local namespace is specific to the function call, and it is destroyed
when the function returns.

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)

# prints the value of pi from the "math" module

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

Note: It is not possible to reassign or delete built-in functions or variables in Python.


Attempting to do so will result in a SyntaxError.

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

x = 10 # x is a local variable in the outer function

def inner():

y = 5 # y is a local variable in the inner function

print("Inner Function: y =",y) # y is accessible within inner

print("Inner Function: x =”,x) # x is accessible within inner because of nested scope

inner() # Call inner function within the outer function

# y is not accessible here, it is local to the inner function

print("Outer Function: x =",x) # x is accessible within outer function

# Calling the outer function

outer()

# Trying to access x and y from outside the functions will cause an error:

# print(x) # Error: NameError: 'x' is not defined

# print(y) # Error: NameError: 'y' is not defined

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

1. CLASSES AND OBJECTS


Class

 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.

Steps to use class and Objects

1. Define and declare a class


2. Create an object
3. Access its members

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

#defining instance class methods


def showName(self):
print(self.name)

def showAge(self):
print(self.age)

#end of the class definition

# Create an object of the class


person1 = Person("Allen", 23)

1
#Create another object of the same class
person2 = Person("Deepak", 102)

#call member methods of the objects


person1.showAge()
person2.showName()

Step1: Class declaration

Python class variables

 ‘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 __init__ function defined above is called the class constructor.


 This special function is automatically called when an instance (object) of the class is created.
 It is used to initialize the class variables.
 The constructor method starts with def __init__. Afterward, the first parameter must be ‘self’,
as it passes a reference to the instance of the class itself. You can also add additional parameters
like the way it is shown in the example. ‘personName’ and ‘personAge’ are two parameters to
sent when a new object is to be created.

The self Parameter

 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:

Python class methods

Methods are declared in the following way:

def method_name(self, parameter 1, parameter 2, …….)

statements……..

return value (if required)

Step 2: Creating an Object


Syntax: objectName = ClassName()

Step 3: Access its members

 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.

How to call a __str__ function in python

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

person1 = My_person_class("Tom","USA", 30)


print(person1)

Output

Tom who lives in USA is 30 years old

3. OPERATOR OVERLOADING IN PYTHON

 Operator overloading is a feature of Python that lets you use the same operator for
more than one task. This is also called polymorphism.

Magic Methods and Their Usage


 In Python, operator overloading is implemented using special functions or methods
called magic methods.
 For example, the addition operator (+) is overloaded using the __add__ method, and
the less than operator (<) is overloaded using the __lt__method.
 Magic methods are called automatically by Python when a particular operator is used
with a user-defined object.

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

def __add__(self, other):


x = self.x + other.x
y = self.y + other.y
return Point(x, y)

p1=Point(10,11)
p2=Point(20,21)
p3=p1+p2 //addition operator overloading

print(p3.x, p3.y) #Output 30 32

Overloading the Less Than Operator–

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

def __lt__(self, other):


return self.area() < other.area()

r1=Rectangle(2,5)
r2=Rectangle(5,10)

print(r1<r2) #Output True

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 __init__(self, name, pin, balance = 0.0):


self.name = name
pin = pin
self.balance = balance

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 deposit(self, amount):


"""Deposits the given amount and returns None."""
self.balance += amount
return None

def withdraw(self, amount):


"""Withdraws the given amount. Returns None if successful, or an error message if
unsuccessful."""
if amount < 0:
return "Amount must be >= 0"
elif self.balance < amount:
return "Insufficient funds"
else:
self.balance -= amount
return None

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

5. PYTHON ERROR AND EXCEPTION


 Errors represent conditions such as compilation error, syntax error, error in the logical
part of the code, library incompatibility, infinite recursion, etc.
 Errors are usually beyond the control of the programmer and we should not try to handle
errors.
 Exceptions can be caught and handled by the program.Errors that occur at runtime
(after passing the syntax test) are called exceptions or logical errors.

For instance, they occur when we


 try to open a file(for reading) that does not exist (FileNotFoundError)
 try to divide a number by zero (ZeroDivisionError)
 try to import a module that does not exist (ImportError) and so on.

Exception Handling
Python try...except Block
Syntax
try:
statements
except Exception1:
statements
except Exception2:
statements
else:
statements
finally:
statements

 A single try block can be followed by several except blocks.


 When an exception occurs, it is caught by the except block.
 Multiple except blocks can be used to handle multiple exceptions.
 We cannot write except blocks without a try block.
 When there is no exception, else block is executed after try block.
 Finally block is always executed

7
Example: Exception Handling Using try...except
try:
numerator = 10
denominator = 0

result = numerator/denominator

print(result)

except:
print("Error: Denominator cannot be 0.")

# Output: Error: Denominator cannot be 0.

Catching Specific Exceptions in Python


 For each try block, there can be zero or more except blocks. Multiple except blocks
allow us to handle each exception differently.
 The argument type of each except block indicates the type of exception that can be
handled by it.

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.")

# Output: Index Out of Bound

6. BUILDING A NEW DATA STRUCTURE: The Two Dimensional Grid

 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.

Syntax to declare an array:


array-name = []

8
Declaration of Two Dimensional Array

array-name = [ [d1, d2, .... dn], [e1, e2, .... en] ]

Example:

array_input = [ [10,12,14] ,[0,1,2] ]


print(array_input[0]) # printing elements of row 0
print(array_input[1]) # printing elements of row 1

Output

[10,12,14]
[0,1,2]

Python Built-in Array Module

Arrays are handled by a Python object-type module array.

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

Inserting elements into an array


from array import *
input = [[1,1,1,1], [12,12,12,12]]
print("Array before insertion of elements: ")
print(input)

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

from array import *


input = [[1,1,1,1], [12,12,12,12], [0,2]]
print("Array before Deletion of elements: ")
print(input)

del(input[1])
print("Array after Deletion of elements: ")
for x in input:
for y in x:
print(y,end = " ")
print()

10
7. INHERITANCE

 Inheritance allows us to create a new class from an existing class.


 The new class that is created is known as subclass (child or derived class) and the
existing class from which the child class is derived is known as superclass (parent or
base class).

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.

Example : Python Inheritance


class Animal:

# attribute and method of the parent class


name = ""

def eat(self):
print("I can eat")

# inherit from Animal


class Dog(Animal):

# new method in subclass


def display(self):
# access name attribute of superclass using self
print("My name is ", self.name)

# create an object of the subclass


labrador = Dog()

# access superclass attribute and method


labrador.name = "Rohu"
labrador.eat()

# call subclass method


labrador.display()

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.

Example: Method Overriding


class Animal:

# attributes and method of the parent class


name = ""

def eat(self):
print("I can eat")

# inherit from Animal


class Dog(Animal):

# override eat() method


def eat(self):
print("I like to eat bones")

# create an object of the subclass


labrador = Dog()

# call the eat() method on the labrador object


labrador.eat()

Output
I like to eat bones

The super() Method in Python Inheritance


 Previously we saw that the same method in the subclass overrides the method in the
superclass.
 However, if we need to access the superclass method from the subclass, we use
the super() method.

For example,
class Animal:

name = ""

def eat(self):
print("I can eat")

# inherit from Animal

12
class Dog(Animal):

# override eat() method


def eat(self):

# call the eat() method of the superclass using super()


super().eat()

print("I like to eat bones")

# create an object of the subclass


labrador = Dog()

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.

Multiple Inheritance in Python

Inherits the methods and attributes from one or more parent classes.

Syntax

class Base_1:
#attributes and methods
class Base_2:
#attributes and methods

class DerivedClass(Base_1, 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:

These strings can be accessed using a __doc__ method of the object.

def myProgram():
"""Demonstrate docstrings in Python."""
return None

print(myProgram.__doc__)

9. GRAPHICAL USER INTERFACES

 GUI displays all information, including text, graphically to its users and allows them to
manipulate this information directly with a pointing device

A) The Behavior of Terminal-Based Programs and GUI-Based Programs

 A terminal-based program prompts users to enter successive inputs,


 whereas a GUI program puts users in change, allowing them to enter inputs in any
order and waiting for them to press a command button or select a menu option

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.

Event Driven Programming


 GUI-based program opens a window and waits for the user to manipulate window
components with the mouse. These user-generated events, such as mouse clicks, trigger
operations in the program to respond by pulling in inputs, processing them, and
displaying results. This type of software system is event-driven, and the type of
programming used to create it is called event-driven programming.

B) Coding Simple GUI based Programs

 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.

from breezypythongui import EasyFrame

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

C) Windows and Window Components

Windows and Their Attributes


A window has several attributes. The most important ones are its
• title (an empty string by default)
• width and height in pixels
• resizability (true by default)
• background color (white by default)

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)

Types of Window Components and Their Attributes


GUI programs use several types of window components, or widgets as they are commonly
called. These include labels, entry fields, text areas, command buttons, drop-down menus,
sliding scales, scrolling list boxes, canvases, and many others

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)

# A single label in the first row.


self.label = self.addLabel(text = "Hello world!", row = 0, column = 0, columnspan = 2,
sticky = "NSEW")

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

# Methods to handle user events.


def clear(self):
"""Resets the label to the empty string and updates the button states."""
self.label["text"] = ""
self.clearBtn["state"] = "disabled"
self.restoreBtn["state"] = "normal"

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"

# Main function to run the GUI.


def main():
ButtonDemo().mainloop()

# Run the program.


if __name__ == "__main__":
main()

19

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy