You are on page 1of 23

SVCE TIRUPATI

COURSE MATERIAL

PYTHON PROGRAMMING
SUBJECT (19A05304T)

UNIT 2

COURSE B.TECH

SEMESTER 21

COMPUTER SCIENCE &


DEPARTMENT ENGINEERING

PREPARED BY
S SRINIVASULU
(Faculty Name/s) Assistant Professor

VERSION V-5

PREPARED / REVISED DATE 31-12-2020

BTECH_CSE_SEM 21
SVCE TIRUPATI

TABLE OF CONTENTS – UNIT 1


SNO CONTENTS PAGE
1 COURSE OBJECTIVES 1
2 PREREQUISITES 1
3 SYLLABUS 1
4 COURSE OUTCOMES 1
5 CO - PO/PSO MAPPING 1
6 LESSON PLAN 2
7 ACTIVITY BASED LEARNING 2
8 LECTURE NOTES 3
2.1 CASE STUDY 3
2.1.1 THE TURTLE MODULE 3
2.1.2 SIMPLE REPETITION 5
2.1.3 ENCAPSULATION 5
2.1.4 GENERALIZATION 6
2.1.5 INTERFACE DESIGN 6
2.1.6 REFACTORING 7
2.1.7 DOCSTRING 7
2.2 CONDITIONALS AND RECURSION 8
2.2.1 FLOOR DIVISION AND MODULUS 8
2.2.2 BOOLEAN EXPRESSIONS 8
2.2.3 LOGICAL OPERATORS 9
2.2.4 CONDITIONAL EXECUTION 9
2.2.5 ALTERNATIVE EXECUTION 9
2.2.6 CHAINED CONDITIONALS 10
2.2.7 NESTED CONDITIONALS 10
2.2.8 RECURSION 11
2.2.9 INFINITE RECURSION 11
2.2.10 KEYBOARD INPUT 11
2.3 FRUITFUL FUNCTIONS 12
2.3.1 RETURN VALUES 12
2.3.2 INCREMENTAL DEVELOPMENT 12
2.3.3 COMPOSITION 14
2.3.4 BOOLEAN FUNCTIONS 14

BTECH_CSE_SEM 21
SVCE TIRUPATI
2.3.5 MORE RECURSION 14
2.3.6 LEAP OF FAITH 15
2.3.7 CHECKING TYPES 15
9 PRACTICE QUIZ 16
10 ASSIGNMENTS 18
11 PART A QUESTIONS & ANSWERS (2 MARKS QUESTIONS) 18
12 PART B QUESTIONS 19
13 SUPPORTIVE ONLINE CERTIFICATION COURSES 19
14 REAL TIME APPLICATIONS 19
15 CONTENTS BEYOND THE SYLLABUS 20
16 PRESCRIBED TEXT BOOKS & REFERENCE BOOKS 21
17 MINI PROJECT SUGGESTION 21

BTECH_CSE_SEM 21
SVCE TIRUPATI
1. COURSE OBJECTIVES
The objectives of this course are to
1. To learn the fundamentals of Python.
2. To introduce a function-oriented programming paradigm through python.
3. To get training in the development of solutions using modular concepts.
4. To introduce the programming constructs of python.

2. PREREQUISITES
Students should have knowledge on
1. Should have mathematical knowledge
2. Should have logical thinking.
3. Should be familiar with problem solving approach

3. SYLLABUS
UNIT II
Case study: The turtle module, Simple Repetition, Encapsulation, Generalization, Interface
design, Refactoring, docstring.
Conditionals and Recursion: floor division and modulus, Boolean expressions, Logical
operators, Conditional execution, Alternative execution, Chained conditionals, Nested
conditionals, Recursion, Infinite Recursion, Keyboard input.
Fruitful Functions: Return values, Incremental development, Composition, Boolean functions,
More recursion, Leap of Faith, Checking types.

4. COURSE OUTCOMES
Student should be able to
1. Apply the conditional execution of the program.
2. Apply the principle of recursion to solve the problems
3. Implement modular programming to solve the problems .

5. CO-PO / PSO Mapping


PP PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 P10 PO11 PO12 PSO1 PSO2

CO1 3 3 3 2 2 3 2

CO2 3 3 3 2 2 3 2

CO3 3 3 3 2 2 3 2

6. LESSON PLAN

1|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI
LECTUR REFERENC
WEEK TOPICS TO BE COVERED
E ES
1 Reassignment, Updating variables T1

2 The while statement, Break T1


1
3 Square roots, Algorithms. T1

4 len, Traversal with a for loop, Strings are immutable T1

5 Searching, Looping and Counting T1

6 String methods, The in operator, String comparison. T1

7 Reading word lists, Search, Looping with indices. T1

8 2 Reading word lists, Search, Looping with indices. T1

9 Lists are mutable, Traversing a list T1

10 List operations, List slices T1

11 3 List methods, Map filter and reduce, Deleting elements T1

12 Lists and Strings, Objects and values, Aliasing, List arguments. T1

7. ACTIVITY BASED LEARNING


Activity #1:

Activity#1

1. What is the difference between Python Arrays and lists?

2. How are classes created in Python? 

3. Write a program in Python to produce Star triangle.

Activity#2

1. Write a one-liner that will count the number of capital letters in a file.

2. Write a sorting algorithm for a numerical dataset in Python.

8. LECTURE NOTES
2.1 Case Study :

2|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI
2.1.1 Turtle Module: in python turtle is a module, which allows you to create images using
turtle graphics
How to use turtle module:
To work with turtle we follow the below steps
1. Import the turtle module
2. Create a turtle to control.
3. Draw around using the turtle methods.
4. Run
Import the turtle module:
To make use of the turtle methods and functionalities, we need to import turtle.
from turtle import *
# Or
import turtle
Create a turtle to control:
After importing the turtle library and making all the turtle functionalities available to us, we need
to create a new drawing board(window) and a turtle. Let’s call the window as wn and the turtle
as skk. So we code as:

wn = turtle.Screen()
wn.bgcolor("light green") n.title("Turtle")
skk = turtle.Turtle()

Draw around using the turtle methods:

METHOD PARAMETER DESCRIPTION

Turtle() None It creates and returns a new turtle


object

forward() Amount It moves the turtle forward by the


specified amount

backward() Amount It moves the turtle backward by the


specified amount

right() Angle It turns the turtle clockwise

left() Angle It turns the turtle counter clockwise

penup() None It picks up the turtle’s Pen

pendown() None Puts down the turtle’s Pen

up() None Picks up the turtle’s Pen

3|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI
down() None Puts down the turtle’s Pen

color() Color name Changes the color of the turtle’s pen

fillcolor() Color name Changes the color of the turtle will use
to fill a polygon

heading() None It returns the current heading

position() None It returns the current position

goto() x, y It moves the turtle to position x,y

begin_fill() None Remember the starting point for a


filled polygon

end_fill() None It closes the polygon and fills with the


current fill color

dot() None Leaves the dot at the current position

stamp() None Leaves an impression of a turtle shape


at the current location

shape() shapename Should be ‘arrow’, ‘classic’, ‘turtle’ or


‘circle’

Example code

# import turtle library

import turtle
my_window = turtle.Screen()
my_window.bgcolor("blue") # creates a graphics window my_pen = turtle.Turtle()
my_pen.forward(15)
my_pen.left(90) my_pen.forward(75) my_pen.color("white”)
my_pen.pensize(12)
Output:-

4|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI

Run :

To run the turtle we call the method turtle. done().

2.1.2 Simple Repetition:


Performing the same action repeatedly is called simple repetition.
For ex let’s consider a square or rectangle to draw. The following steps to be performed
repeatedly.
bob.fd (100)
bob.lt (90)
bob.fd (100)
bob.lt (90)
bob.fd (100)
bob.lt (90)
bob.fd (100)

The above steps can be reduced using simple repetition statement for as follows. for i in
range(4):
bob.fd (100)
bob.lt(90)

2.1.3 Encapsulation:
Wrapping a piece of code up in a function is called encapsulation. The benefits of encapsulation
are,
 it attaches a name to the code.
 We can reuse the code, (i.e we can call a function instead of copy and paste the body)
For ex: code to drawing the square
def square(t):
for i in range(4):
t.fd(100)
t.lt(90)
bob = turtle.Turtle() square(bob)

2.1.4 Generalization:
Adding a parameter to a function is called generalization. because it makes the function more
general: in the previous version, the square is always the same size; in this version it can be any
size.

5|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI

def square(t, length):


for i in range(4):
t.fd(length) t.lt(90)
bob = turtle.Turtle()

square(bob, 100)

the following one also a generalization. Instead of drawing squares, polygon draws regular
polygons with any number of sides.
Here is a solution:

def polygon(t, n, length):


angle = 360 / n for i in range(n):
t.fd(length) t.lt(angle)

bob = turtle.Turtle()
polygon(bob, 7, 70)

2.1.5 Interface Design:


The interface of a function is a summary of how it is used: what are the parameters?
What does the function do? And what is the return value? An interface is “clean” if it allows the
caller to do what they want without dealing with unnecessary details.

For ex: write circle, which takes a radius, r, as a parameter.


Here is a simple solution that uses polygon to draw a 50-sided polygon:
import math

def circle(t, r):


circumference = 2 * math.pi * r n = 50
length = circumference / n

polygon(t, n, length)

 The first line computes the circumference of a circle with radius r using the formula 2πr.
 n is the number of line segments in our approximation of a circle, so length is the length
of each segment. Thus, polygon draws a 50-sided polygon that approximates a circle with
radius r.

 One limitation of this solution is that n is a constant, which means that for very big
circles, the line segments are too long, and for small circles, we waste time drawing very
small segments. One solution would be to generalize the function by taking n as a
parameter.

6|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI
def circle(t, r):
circumference = 2 * math.pi * r
n = int(circumference / 3) + 1
length = circumference / n

polygon(t, n, length)

2.1.6 refactoring:
It is a process of rearranging a program to improve interfaces and facilitate code reuse is called
refactoring
for ex: Lets take above discussion , When we write circle, we can able to reuse polygon because
a many-sided polygon is a good approximation of a circle. But arc is not as cooperative; we can’t
use polygon or circle to draw an arc.
One alternative is to start with a copy of polygon and transform it into arc. The result might look
like this:
def polygon(t, n, length):
angle = 360.0 / n polyline(t, n, length, angle)
def arc(t, r, angle):
arc_length = 2 * math.pi * r * angle / 360
n = int(arc_length / 3) + 1
step_length = arc_length / n
step_angle = float(angle) / n

polyline(t, n, step_length, step_angle)

Finally, we can rewrite circle to use arc:


def circle(t, r):
arc(t, r, 360)

2.1.7 doc string:


docstring is a string at the beginning of a function that explains the interface (“doc”is short for
“documentation”).

Example:
def polyline(t, n, length, angle):
"""Draws n line segments with the given length and angle (in degrees) between them. t is a
turtle.
"""
for i in range(n):
t.fd(length)
t.lt(angle)
By convention, all docstrings are triple-quoted strings, also known as multiline strings because
the triple quotes allow the string to span more than one line

2.2. Conditionals and Recursion

7|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI
2.2.1 floor division and modulus:
The floor division operator ’ //’ divides two numbers and rounds down to an integer. For
example:
Conventional division returns a floating-point number as follows
>>> minutes = 105
>>> minutes / 60 1.75
But Floor division returns the integer number of hours, dropping the fraction part:
>>> minutes = 105
>>> hours = minutes // 60
>>> hours 1
modulus operator, %, which divides two numbers and returns the remainder:
>>> remainder = minutes % 60
>>> remainder 45

2.2.2 Boolean Expressions:


A boolean expression is an expression that is either true or false.
The following examples use the operator ==, which compares two operands and produces True if
they are equal and False otherwise:
>>> 5 == 5
True
>>> 5 == 6
False
True and False are special values that belong to the type bool; they are not strings:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
The == operator is one of the relational operators; the others are: x != y # x is not equal to y
x > y # x is greater than y x < y # x is less than y
x >= y # x is greater than or equal to y x <= y # x is less than or equal to y

2.2.3 Logical Operators:


There are three logical operators:
and, or, and not. The semantics (meaning) of these operators is similar to their meaning in
English.
For example:
x > 0 and x < 10 is true only if x is greater than 0 and less than 10.
n%2 == 0 or n%3 == 0 is true if either or both of the conditions is true, that is, if the
number is divisible by 2 or 3.
not : operator negates a boolean expression,
not (x > y) is true ,if x > y is false, that is, if x is less than or equal to y.

Note: In Python, Any nonzero number is interpreted as True:


>>> 42 and True True

2.2.4 Conditional Execution:


8|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI
In order to write useful programs, we almost always need the ability to check conditions and
change the behavior of the program accordingly.

if statement:
if test expression:
statement(s)
 Here, the program evaluates the test expression and will execute statement(s) only if the
test expression is True.
 If the test expression is False the statement(s) is not executed.

For ex:
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")

2.2.5 Alternative Execution:


A second form of the if statement is “alternative execution”, in which there are two possibilities
and the condition determines which one runs. The syntax looks like this:
Syntax of if...else
if test expression:
Body of if

else:

Body of else

For ex:
num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")

 The if..else statement evaluates test expression and will execute the body of if only only
when the test condition is true. If the condition is False the body of else is executed.

2.2.6 Chained Conditionals


Sometimes there are more than two possibilities and we need more than two branches. One way
to express a computation like that is a chained conditional:
To implement chained conditional we use keyword “elif”.
Syntax of if...elif...else

if test expression:
Body of if
elif test expression:

9|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI
Body of elif

else:

Body of else

Note: If the condition for if is False, it checks the condition of the next elif block and so on. If all
the conditions are False , the body of else is executed.

For Ex:
x=10
y=20
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')

2.2.7 Nested Conditionals:


One conditional can also be nested within another.

For ex:
if x == y:
print('x and y are equal')
elif x>y:
print('x is greater than y ')
else:
print('x is less than y ')

2.2.8 Recursion:
Recursion means a function to call itself.
For example:
def countdown(n):
if n <= 0:
print('Blastoff!')
else:
print(n) countdown(n-1)
countdown(3)

The output looks like this:


3
2
1
Blastoff!

2.2.9 Infinite Recursion:


10|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI
If a recursion never reaches a base case, it goes on making recursive calls forever, and the
program never terminates. This is known as infinite recursion.
Here is a minimal program with an infinite recursion:

def recurse():
recurse()

2.2.10 Keyboard Input:


Python provides a built-in function called input() to read a value from key board.
For ex:
print('Enter your name:')
x = input()
print('Hello, ' + x)

Syntax :
input(prompt)
Example:
Use the prompt parameter to write a message before the input:
x = input('Enter your name:')
print('Hello, ' + x)
Note: input() function always reads string input. There to read int or float input values we should
convert string input to the respective types using functions int(), float() ect..

For ex:
str_a = input(“enter value”)
b = 10
c = int(str_a) + b
print ("The value of c = ",c)

o/p:
enter value:
42
The value of c =52

2.3. Fruitful Functions


2.3.1 Return values:
The return keyword is to exit a function and return a value.
Syntax:
Return or return value:

For ex :

def myfunction():
return 3+3
print(myfunction())
output:

11|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI
6.

2.3.2 Incremental Development:


incremental development is to avoid long debugging sessions by adding and testing only a small
amount of code at a time(i.e. develop complex programs step by step).

For ex develop a program to find distance between two points

In Step1 we just define function with empty body as follows


def distance(x1, y1, x2, y2):
return 0.0

 To test the new function, call it with sample arguments:


>>> distance(1, 2, 4, 6)
 The output is 0.0 as there is no code to compute distance.

 At this point we have confirmed that the function is syntactically correct, and we can start
adding code to the body.

In step 2 it is to find the differences x2 − x1 and y2 − y1. The next version stores those values in
temporary variables and prints them:
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
print('dx is', dx)
print('dy is', dy)
return 0.0

In step 3 we compute the sum of squares of dx and dy:


def distance(x1, y1, x2, y2):
dx = x2 - x1 dy = y2 - y1
dsquared = dx**2 + dy**2
print('dsquared is: ', dsquared)
return 0.0
Again, you would run the program at this stage and check the output (which should be 25).

In step 4, you can use math.sqrt to compute and return the result:

def distance(x1, y1, x2, y2):


dx = x2 - x1 dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result

The key aspects of the process are:


12|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI
 Start with a working program and make small incremental changes. At any point, if there
is an error, you should have a good idea where it is.
 Use variables to hold intermediate values so you can display and check them.
 Once the program is working, you might want to remove some of the scaffolding or
consolidate multiple statements into compound expressions, but only if it does not make
the program difficult to read.

2.3.3 Composition:
A complex program developed in small functions separately and writes function calls to them in
proper sequence to achieve the functionality of complex program is called composition.
For ex: we want a function to compute the area of the circle.
Assume that the center point is stored in the variables xc and yc, and the perimeter point is in xp
and yp.
The first step is to find the radius of the circle, which is the distance between the two points. We
just wrote a function, distance, that does that:
radius = distance(xc, yc, xp, yp)
The next step is to find the area of a circle with that radius; we just wrote that, too:
result = area(radius)
Encapsulating these steps in a function, we get:
def circle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
The temporary variables radius and result are useful for development and debugging, but once
the program is working, we can make it more concise by composing the function calls:
def circle_area(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))

2.3.4 Boolean Functions


Functions can return Booleans.
For example:
def is_divisible(x, y): if x % y == 0: return True
else:
return False
>>> is_divisible(6, 4) False
>>> is_divisible(6, 3) True

2.3.5 More Recursion:


The function calls it self is called recursion .
For ex consider factorial of a number.
The definition of factorial says that the factorial of 0 is 1, and the factorial of any other value n
is, n multiplied by the factorial of n-1.
def factorial(n):
if n == 0:
return 1
13|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI
else:

recurse = factorial(n-1)
result = n * recurse

return result

2.3.6 Leap of Faith:


Leap of Faith means when you come to a function call, instead of following the flow of
execution, you assume that the function works correctly and returns the right result.
For example built in functions .i.e. When you call math.cos or math.exp, you don’t examine the
bodies of those functions.

2.3.7 Checking Types:


What happens if we call factorial and give it 1.5 as an argument?
>>> factorial(1.5)
RuntimeError: Maximum recursion depth exceeded
Why because In the first recursive call, the value of n is 0.5. In the next, it is -0.5. From there, it
gets smaller (more negative), but it will never be 0.

To avoid this situation we have to check input type using the built-in function isinstance() to
verify the type of the argument.
For ex:
def factorial (n):
if not isinstance(n, int):
print('Factorial is only defined for integers.')
return None
elif n < 0:
print('Factorial is not defined for negative integers.')
return None
elif n == 0:
return 1
else:
return n * factorial(n-1)

14|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI
The first base case handles non integers; the second handles negative integers. In both cases, the
program prints an error message and returns None to indicate that something went wrong:
>>> factorial('fred')
Factorial is only defined for integers.
None
>>> factorial(-2)
Factorial is not defined for negative integers.
None
If we get past both checks, we know that n is positive or zero, so we can prove that the recursion
terminates.
This program demonstrates a pattern sometimes called a guardian. The first two conditionals act
as guardians, protecting the code that follows from values that might cause an error. The
guardians make it possible to prove the correctness of the code.

9. Practice Quiz
1. What do we use to define a block of code in Python language?
A. Key
B. Brackets
C. Indentation
D. None of these
2. What is the maximum possible length of an identifier?
A. 16
B. 32
C. 64
D. None of these above
3. Which of the following is not a keyword in Python language?
A. val
B. raise
C. try
D. with
4. Which of the following operators is the correct option for power(ab)?
A. a ^ b
B. a**b
C. a ^ ^ b
D. a ^ * b
5. Study the following program:
x = 1  
while True:  
    if x % 5 = = 0:  
        break  
    print(x)   
    x + = 1  
What will be the output of this code?
A. error
B. 2 1
C. 0 3 1
15|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI
D. None of these

6. Study the following function:


import math  
abs(math.sqrt(36)) 
What will be the output of this code?
A. Error
B. -6
C. 6
D. 6.0

7. Study the following program:


a = 1  
while True:  
    if a % 7 = = 0:  
        break  
    print(a)  
    a += 1  
Which of the following is correct output of this program?
A. 1 2 3 4 5
B. 1 2 3 4 5 6
C. 1 2 3 4 5 6 7
D. Invalid syntax
8. Study the following program:
d = {0: 'a', 1: 'b', 2: 'c'}  
for i in d:  
    print(i)  
What will be the output of this statement?
A. a b c
B. 0 1 2
C. 0 a   1 b   2 c
D. None of these above
9. Which of the following option is not a core data type in the python language?
A. Dictionary
B. Lists
C. Class
D. All of the above

10.In order to store values in terms of key and value we use what core data type.
A. list
B. tuple
C. class
D. Dictionary

10. Assignments

16|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI

S.No Question BL CO
1 Write a python script to draw circle using turtle module 6 1
2 Discuss the conditional statements with suitable example 2 2
Discuss the following
3 2 3
1. incremental Development 2. Composition

11. Part A- Question & Answers


S.No Question& Answers BL CO
1 Write the syntax of if-else statements.
Ans.
Syntax:
if expression:
Statement 2 1
else:
Statement

2 Give the use of return () statement with a suitable example


Ans.
Syntax: 2 2
return[expression];

3 Justify the effects of slicing operations on an array


Ans. Python supports the slicing of arrays. It is the creation of a new sub-
array from the given array on the basis of the user-defined starting and
ending indices. We can slice arrays by either of the following ways. 2 2
Array slicing can be easily done following the Python slicing method.
For which the syntax is given below.
arr[ start : stop : step ]
4 What is Nested Function?
Ans.
A nested function is simply a function within another function, and is
sometimes called an "inner function".
def function1(): # outer function 1 1
print ("Hello from outer function")
def function2(): # inner function
print ("Hello from inner function")

5 What is recursion?
Ans.
1 1
 Recursion is the process of defining something in terms of itself.

12. Part B- Questions


S.No Question BL CO
1 Explain steps involved to use turtle module and also write a program to 2 1
draw circle?

2 Discuss encapsulation and Design a program to implement it using turtle? 2 1

17|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI
3 Write a note on Composition? 2 1

13. Supportive Online Certification Courses


1. THE JOY OF COMPUTING USING PYTHON –NPTEL
https://nptel.ac.in/courses/106/106/106106182/#
2. Python 3 programming- Coursera
https://www.coursera.org/specializations/python-3-programming
3. Professional certificate in Introduction to Python Programming
https://www.edx.org/professional-certificate/introduction-to-python-programming
14. Real Time Applications
S.No Application CO
1 Web Development 6

2 Game Development 6

3 Machine Learning and Artificial Intelligence 3

4 Data Science and Data Visualization 3

5 Desktop GUI 6

6 Web Scraping Applications 6

7 Audio and Video Applications 5

8 CAD Applications 6

9 Embedded Applications 6

15. Contents Beyond the Syllabus


1)  Argument packing and unpacking in Python
Packing :
When we don’t know how many arguments need to be passed to a python function, we
can use Packing to pack all arguments in a tuple.

# A Python program to demonstrate use # of packing


# This function uses packing to sum
# unknown number of arguments
def mySum(*args):
sum = 0
for i in range(0, len(args)):
sum = sum + args[i]
return sum

# Driver code
print(mySum(1, 2, 3, 4, 5))
18|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI
print(mySum(10, 20))

unpacking:
Background
Consider a situation where we have a function that receives four arguments. We want to
make call to this function and we have a list of size 4 with us that has all arguments for
the function. If we simply pass list to the function, the call doesn’t work.
We can use * to unpack the list so that all elements of it can be passed as different
parameters.
# A sample function that takes 4 arguments and prints them
def fun(a, b, c, d):
print(a, b, c, d)

# Driver Code
my_list = [1, 2, 3, 4]
# Unpacking list into four arguments
fun(*my_list)

2) Python Indentation
 Indentation refers to the spaces at the beginning of a code line.
 Python uses indentation to indicate a block of code.
 
 
 
  3) lambda function in python

 A lambda function is a small anonymous function.


 A lambda function can take any number of arguments, but can only have one expression.
Syntax
lambda arguments : expression
The expression is executed and the result is returned:
Example
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
Lambda functions can take any number of arguments:
Example
Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))

16. Prescribed Text Books & Reference Books


Text Book
1. Allen B. Downey, “Think Python”, 2nd edition, SPD/O’Reilly, 2016.
References:
1. Martin C.Brown, “The Complete Reference: Python”, McGraw-Hill, 2018.
2. Kenneth A. Lambert, B.L. Juneja, “Fundamentals of Python”, CENGAGE, 2015.
19|P P - U N I T - 2

BTECH_CSE_SEM 21
SVCE TIRUPATI
3. R. Nageswara Rao, “Core Python Programming”, 2nd edition, Dreamtech Press, 2019

17. Mini Project Suggestion


Alarm Clock
In this application, you can input YouTube links in a text file and design the application to
read the file. If you set a particular time in the alarm clock, it will pick a random YouTube
link from the text file and play the YouTube video.

20|P P - U N I T - 2

BTECH_CSE_SEM 21

You might also like