Python Programming chapter 2, Study notes of Programming Languages

Here the intermediate level topics are described lets move on it and get next chapter for more.

Typology: Study notes

2022/2023

Uploaded on 09/06/2022

Javid_shaik
Javid_shaik 🇮🇳

6 documents

1 / 24

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
2.1
Unit-2 Case Study, Conditionals and Recursion, Fruitful Functions
Syllabus
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.
Case Study, Conditionals and Recursion,
Fruitful Functions
Unit
2
S
I
A
G
R
O
U
P
Learning Objectives
ÿ The Turtle Module and the Functions used in it
ÿ Simple Repetition Statement like 'for'
ÿ Boolean Expressions and Various Logical Operators
ÿ Conditional Execution Statements like 'if' and Alternative Execution Statements like 'if-else'
ÿ Direct Recursion and Indirect Recursion
ÿ Boolean Functions and Leap of Faith
ÿ Checking Types in Function Arguments.
Introduction
In python, the term ‘Turtle’ possess features similar to a drawing board. The turtle specifies the attributes
like Location Attribute, Orientation Attribute, Pen Attribute. Turtle graphics is the simplest and popular way
of drawing pictures by giving commands to the turtle.
Conditional execution allows specific code to be executed based on certain condition and other code to
be skipped. If condition is satisfied the statements followed by it are executed. Otherwise, some statements
will be executed upon condition failure. If not, the control comes out or the execution terminates.
Recursion is the process (or) technique by which a function calls itself repeatedly. A function which calls
itself directly (or) indirectly is called as recursive function. The functions that return the values are called
fruitful functions and that do not return any value are called as non-fruitful functions.
Incremental development is a process of debugging the sessions by adding and testing the less lines of
code at a time.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18

Partial preview of the text

Download Python Programming chapter 2 and more Study notes Programming Languages in PDF only on Docsity!

UNIT-2 Case Study, Conditionals and Recursion, Fruitful Functions 2.

Syllabus

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.

Case Study, Conditionals and Recursion,

Fruitful Functions

Unit

SIA GROUP

Learning Objectives

ÿ The Turtle Module and the Functions used in it

ÿ Simple Repetition Statement like 'for'

ÿ Boolean Expressions and Various Logical Operators

ÿ Conditional Execution Statements like 'if' and Alternative Execution Statements like 'if-else'

ÿ Direct Recursion and Indirect Recursion

ÿ Boolean Functions and Leap of Faith

ÿ Checking Types in Function Arguments.

Introduction

In python, the term ‘Turtle’ possess features similar to a drawing board. The turtle specifies the attributes

like Location Attribute, Orientation Attribute, Pen Attribute. Turtle graphics is the simplest and popular way

of drawing pictures by giving commands to the turtle.

Conditional execution allows specific code to be executed based on certain condition and other code to

be skipped. If condition is satisfied the statements followed by it are executed. Otherwise, some statements

will be executed upon condition failure. If not, the control comes out or the execution terminates.

Recursion is the process (or) technique by which a function calls itself repeatedly. A function which calls

itself directly (or) indirectly is called as recursive function. The functions that return the values are called

fruitful functions and that do not return any value are called as non-fruitful functions.

Incremental development is a process of debugging the sessions by adding and testing the less lines of

code at a time.

2.2 PYTHON PROGRAMMING [J PUR]NTU-ANANTA

Warning: Xerox/Photocopying of this book is a criminal act. anyone found guilty is liaBlE to face lEGal proceedings.

Part-a Short QueStionS with SolutionS

Q1. What do you mean by turtle graphics?

Answer : Model Paper-I, Q1(c)

In python, the term ‘Turtle’ posses features similar to a drawing board. The turtle specifies the following attributes.

(a) Location Attribute

This attributes is concerned with the location of the turtle.

(b) Orientation Attribute

This attribute is concerned with the direction or orientation of the turtle.

(c) Pen Attribute

This attribute is concerned with the other attributes such as color, width and on/off state. Turtle graphics is the simplest and popular way of drawing pictures by giving commands to the turtle. In this programming language, the turtle module is required to be imported which is as shown below,

import turtle

Q2. Write about encapsulation.

Answer :

Encapsulation is a mechanism of binding data members and corresponding methods into a single module called class, inorder to protect them from being accessed by the outside code. An instance of a class can be called as an object and it is used to access the members of a class. In encapsulation, objects are treated as ‘block boxes’ since each object performs specific task.

The data and functions available in a class are called as members of a class. The data defined in the class are called as member variables or data members and the functions defined are called as member functions.

The main idea behind the concept of encapsulation is to obtain high maintenance and to handle the application’s code.

Q3. How floor division is computed?

Answer : Model Paper-II, Q1(c)

Floor Division

In the floor division operation, the fractions obtained in the quotient are always truncated and rounded to the smallest whole number which is on its immediate left on the number line.

Example

25// 12 25.0//2.

Q4. What is a boolean expression?

Answer : Model Paper-III, Q1(c)

In python, a boolean expression is a logical/conditional expression which is evaluated to produce a boolean value as result. The boolean value can either be true or false. These values are of type "bool".

A true value is represented either by 1, nonzero string, nonzero tuple, nonzero list or nonzero dictionary. A false value is represented either by 0, empty string, empty tuple, empty list, empty dictionary or null object.

Examples

4 = = 4 True 4 = = 5 False True + False 1 False + False 0

2.4 PYTHON PROGRAMMING [J PUR]NTU-ANANTA

Warning: Xerox/Photocopying of this book is a criminal act. anyone found guilty is liaBlE to face lEGal proceedings.

Example

def fact(x): if x = = 1: return 1 else: return x * fact(x – 1) print(fact(5)) The output of above example will be, 120 In the above example, base case is fact(1) = 1 i.e., if x = = 1 the recursion will terminate. This is known as base case.

Q9. What are the advantages and disadvantages of recursive function?

Answer :

Advantages

  1. It can be used to simplify the program code.
  2. It divides a large problem into smaller problems.
  3. It is simple to create in comparison to iterations (nested).

Disadvantages

  1. Recursive functions are not easy in error handling.
  2. They take lot of space and memory.
  3. The logic of recursion is not easy to understand.

Q10. Write a Python program to accept two numbers, multiply them and print the result.

Answer : Model Paper-III, Q1(d)

Program

x = int(input("Enter the first number: ")) y = int(input("Enter the second number: ")) z = x*y print("The result after multiplication is:",z)

Output

UNIT-2 Case Study, Conditionals and Recursion, Fruitful Functions 2.

Part-B eSSaY QueStionS with SolutionS

2.1 Case study

2.1.1 the turtle Module

Q11. Write in brief about turtle module.

Answer : Model Paper-I, Q4(a)

In python, the term ‘Turtle’ posses features similar to a drawing board. The turtle specifies the following attributes.

(a) Location Attribute

This attribute is concerned with the location of the turtle.

(b) Orientation Attribute

This attribute is concerned with the direction or orientation of the turtle.

(c) Pen Attribute

This attribute is concerned with the other attributes such as color, width and on/off state. Turtle graphics is the simplest and popular way of drawing pictures by giving commands to the turtle. In this programming language, the turtle module is required to be imported which is as shown below,

import turtle Based on the attributes of turtle, the commands/functions that can be used for drawing the pictures are as follows,

(i) turtle.forward(...)

This function is used to move the turtle in forward direction by the specified distance. Example: turtle.forward(20)

(ii) turtle.backward(...)

This function is used to move the turtle in backward direction by the specified distance. Example: turtle.backward(20)

(iii) turtle.right(...)

This function is used to rotate the turtle towards right by the specified degrees. Example: turtle.right(30)

(iv) turtle.left(...)

This function is used to rotate the turtle towards left by the specified degrees. Example: turtle.left(60)

(v) trutle.shape(...)

This function is used to give the shape of the turtle as desired by the user. Example: turtle.shape(“turtle”) Here, the shape given to the turtle is turtle, but the standard shape of turtle is triangle.

(vi) turtle.exitonclick( )

This function is used to exit the turtle window as soon as the turtle finishes its task. Example: turtle.exitonclick( )

(vii) turtle.color(colorstring)

This function is used to provide different colors as desired by the user. Example: turtle.color(red)

UNIT-2 Case Study, Conditionals and Recursion, Fruitful Functions 2.

(ii) Iterating by Sequence Item

Example

Output

For each iteration in the above example, the list is iterated and the variable ‘x’ contains the list elements.

(iii) Iterating by Sequence Index

Example

Output

2.8 PYTHON PROGRAMMING [J PUR]NTU-ANANTA

Warning: Xerox/Photocopying of this book is a criminal act. anyone found guilty is liaBlE to face lEGal proceedings.

Here, len ( ) and range ( ) are the built-in functions

len ( ) gives the total number of elements in the tuple and range ( ) provides the actual sequence to iterate over tuple elements.

len(array elements)

4

range (len(arrayelements))

[0, 1, 2, 3]

2.1.3 encapsulation, Generalization, Interface design, Refactoring, docstring

Q13. Explain in brief about the following,

(i) Encapsulation

(ii) Generalization.

Answer :

(i) Encapsulation

Encapsulation is a mechanism of binding data members and corresponding methods into a single module called class, inorder to protect them from being accessed by the outside code. An instance of a class can be called as an object and it is used to access the members of a class. In encapsulation, objects are treated as ‘block boxes’ since each object performs specific task.

The data and functions available in a class are called as members of a class. The data defined in the class are called as member variables or data members and the functions defined are called as member functions.

The main idea behind the concept of encapsulation is to obtain high maintenance and to handle the application’s code.

(ii) Generalization

Addition of parameters to a function is called generalization. This makes the function more general. Consider the below example,

def square (t, len):

for i in range (5):

t.fd(len)

t.lt(20)

square (Harry, 50)

Here, the parameters 't' i.e., the turtle and 'len' that is the length are added to function square( ). Actually, all the sides of a square are equal. But in this version it can be of any size.

Consider another example where polygon draws regular polygons with any number of sides rather than drawing squares.

def polygon(t, n, len): angle = 360/n for i in range (n):

t.fd(len) t.lt(angle)

polygon (Harry, 5, 20) The above code draws a 5-sided polygon with side length

  1. If function has more than few numeric arguments, their order must be ignored. In such case, it is better to use the names of parameters in argument list. polygon (Harry, n = 5, len = 20)

They are keyword arguments since they include the parameter names as keywords. With this, the programs become more readable. The arguments get assigned to parameters when function is called. Q14. Write short notes on the following, (i) Refactoring

(ii) Docstring. Answer : Model Paper-III, Q

(i) Refactoring Refactoring is the process of reconstructing or reusing the code without affecting the functionality. It is useful to cleanup the code to prepare it for easier extension. Consider the below example, def circle(t, r):

circumference = 2 * math.pi*r n = 20 len = circumference/n

polygon (t, n, len) Here the polygon draws a 20-sided polygon that approximates a circle. The polygon is reused to draw the circle. But arc is not as cooperative. Either polygon nor circle can be used to draw an arc. One approach would be to start a copy of polygon and then transform it into arc. The result will be as shown below,

def arc (t, r, angle): arc_len = 2 * math.pi.r*angle/ n = int(arc_len/3) + 1

step_len = arc_len/n step_angle = angle/n

for i in range(n): t.fd(step_len) t.lt(step_angle)

2.10 PYTHON PROGRAMMING [J PUR]NTU-ANANTA

Warning: Xerox/Photocopying of this book is a criminal act. anyone found guilty is liaBlE to face lEGal proceedings.

2.2 CondItIonals and ReCuRsIon

2.2.1 Floor division and Modulus, Boolean expressions, logical operators

Q15. Discuss about floor division and modulus.

Answer :

Floor Division

In the floor division operation, the fractions obtained in the quotient are always truncated and rounded to the smallest whole number which is on its immediate left on the number line.

Example

25// 12 25.0//2.

Modulus

The computation of modulus is different for different numeric types.

v The modulo of two integer numbers is the remainder of their integer division.

Example 17 % 3 = 2

v The modulo of two floating point numbers is obtained using the following formula.

− *divisor divisor

dividend dividend math.floor

v The modulo of two complex numbers is obtained using the following formula.

− (^) divisor divisor

dividend math .floor 

dividend .real*

Q16. Write about boolean expressions and logical operators.

Answer : Model Paper-I, Q4(b)

Boolean Expressions

In python, a boolean expression is a logical/conditional expression which is evaluated to produce a boolean value as result. The boolean value can either be true or false. These values are of type "bool".

A true value is represented either by 1, nonzero string, nonzero tuple, nonzero list or nonzero dictionary. A false value is represented either by 0, empty string, empty tuple, empty list, empty dictionary or null object.

Examples

4 = = 4 True 4 = = 5 False True + False 1 False + False 0

UNIT-2 Case Study, Conditionals and Recursion, Fruitful Functions 2.

Logical Operators

These operators negate or link two or more expressions. The list of standard type logical operators in highest to lowest precedence order is given below,

Operator Syntax Determines not not exp negation or logical NOT of exp and exp1 and exp2 conjunction or logical AND of exp1 and exp or exp1 or exp2 disjunction or logical OR of exp1 and exp

Examples

2.2.2 Conditional execution, alternative execution, Chained Conditionals, nested Conditionals

Q17. What is conditional execution? Also explain about alternative execution.

Answer : Model Paper-II, Q4(b)

Conditional Execution

Conditional execution allows specific code to be executed based on certain condition and other code to be skipped. If condition is satisfied the statements followed by it are executed. Otherwise some other statements will be executed upon condition failure. If not the control comes out or the execution terminates.

if Statement

An if statement is a simple conditional execution statement that controls the flow of execution of various statements. It is the basic control statement and is mainly used to test the given condition logically. It performs execution of certain statements after satisfying the condition maintained by it. There must be atleast one or more number of statements after the "if" condition.

The following figure shows the flowchart of "if" statement, Start

True

If False Condition

Exit

Conditional Code Block

Figure (1): Flowchart of "if" Statement

UNIT-2 Case Study, Conditionals and Recursion, Fruitful Functions 2.

Example

Output

Q18. Describe about chained conditionals and nested conditionals.

Answer :

Chained Conditionals

The chained conditionals are simply a "chain" or combination or multiple conditions. They are used when there are more than two possibilities.

if-elif-else Statement

An if-elif-else is a chained conditional statement that contains, more than three choices. It evaluates multiple boolean expressions to true. It contains an "if" statement followed by "elif" statements and then the "else" statements. There can be many number of elif statements and else statements. But an else statement must end the condition statement.

The following figure shows the flowchart of if-elif-else statement,

If Condition 1

Elif Condition 2

True

True

False Else

Condition Code Block 1

Condition Code Block 2

Condition Code Block 3

Figure (1): Flowchart of "if-elif-else" Statement

2.14 PYTHON PROGRAMMING [J PUR]NTU-ANANTA

Warning: Xerox/Photocopying of this book is a criminal act. anyone found guilty is liaBlE to face lEGal proceedings.

Syntax

if condition1: statement(p) elif condition2: statement(q) elif condition3: statement(r) else: statement(t)

Example

Output

Nested Conditionals

The conditional when nested in another conditional then it is called nested conditional. Nested if statement is the conditional statements embedded/placed within one another i.e., one statement can be placed inside another statement. Nesting is required when a choice between two or more statements/options have to be made. This kind of nesting results in multi-way selection.

The following figure shows the flowchart of "nested if" statement,

True False

True False

Condition-

Condition-

Statement-1 Statement-

Statement-next

Statement-

Figure (2): Flowchart of "Nested-if" Statement

2.16 PYTHON PROGRAMMING [J PUR]NTU-ANANTA

Warning: Xerox/Photocopying of this book is a criminal act. anyone found guilty is liaBlE to face lEGal proceedings.

Example

Algorithm to print the factorial of a given number using recursive algorithm.

Step 1: Start

Step 2: Read n

Step 3: Call fact(n)

Step 4: goto fact(n)

Step 5: print fact f

Step 6: Stop.

Fact (n) → Recursion step

Step 1: If n = = 1

Step 2: Return 1

Step 3: Else

f = n*fact (n–1)

Step 4: Return f.

Suppose, Take n = 5 Factorial of 5 = 5×4×3×2 ×1 = 120

fact (5)

If 5 = 1 No f = 5* fact (5–1) =5*fact (4)

fact (4)

If 4 = = 1 No f = 5* 4* fact (4–1) f = 5* 4* fact (3)

fact (3)

If 3 = = 1 No f = 5* 4* 3* fact (3–1) f = 5* 43 fact (2)

fact (2)

2 = = 1 No f = 5* 4* 3* 2* fact (2–1) f = 5* 4* 3* 2* fact (1)

fact (1)

1 = = 1 return 1 i.e., 5* 4* 3* 2* 1 = 120

UNIT-2 Case Study, Conditionals and Recursion, Fruitful Functions 2.

Example

Output

Q20. Write about infinite recursion.

Answer :

The recursion calls continue till the base case is encountered and recursion terminates. Hence the base case, recursion call and termination of recursion are independent and are necessary for a successful recursion. If the base case is not used then the recursion continues and recursion call is made infinite number of times. This is called infinite recursion.

def recursion (n): if n > 0: recursion (n) else: recursion (n – 1) Such type of situation can be avoided by setting a limit on number of recursive calls. If a function executes infinite number of times then an error is raised.

Q21. How input is received from the user? Explain.

Answer : Model Paper-III, Q5(a)

A built in function called input in python is used to accept the input entered by the user through keyboard. This function stops the program and waits for user to type some input. When user enters some input the program will resume back and the input returns the data typed by user as a string.

text = input( ) Hallo text 'Hallo' Before receiving the input from user, it would be a better idea to prompt user what to type. The prompt can be passed as an argument to input.

x = input ('Enter your company name') Enter your company name SIA PUBLISHERS

x 'SIA PUBLISHERS'

UNIT-2 Case Study, Conditionals and Recursion, Fruitful Functions 2.

In the above program, a function cube is defined. It accepts 'a' as parameter and contains an expression to compute cube of 'a'. The expression is preceded by return keyword. This means the function computes cube of a and returns the result using the return keyword. The function gets executed and the output will be printed when the function is called.

The print statement at the end will call the function to print the result. The function call is provided with the parameter value.

In Python, return statement is executed in the following ways,

  1. Initially the expression is evaluated and the resultant value is generated.
  2. Then this value is passed to the calling function.
  3. Finally it leaves the function and control is set back to the called function.

In Python, a temporary variable can also be used instead of directly returning the expression to be evaluated. This simplifies the process of debugging.

Example 1

def cube(x): y = x * x * x return y print(cube(3)) The output of above example is, 27 In python, function like 'abs' is also a fruitful function, as it returns a value.

Example 2

abs(–25) 25 The statements/code occurring after the return statements are not evaluated(never read). Hence, those statements are called as dead code.

In Python, a fruitful function must return a value. Hence, it is necessary for the function to encounter atleast a single return statement. If it does not encounter, it returns a none value.

Program

Output

In the above program, if(x = 0), it does not satisfy either case. Hence, function does not encounter either return statements and it returns a 'None' value. None value is a special value of None type.

In Python, a function which does not contain any return statement (non-fruitful function) will also return this None type value.

2.20 PYTHON PROGRAMMING [J PUR]NTU-ANANTA

Warning: Xerox/Photocopying of this book is a criminal act. anyone found guilty is liaBlE to face lEGal proceedings.

Q23. Discuss about incremental development.

Answer :

Incremental development is a process of debugging the sessions by adding and testing the less lines of code at a time. Consider an example of determining the distance between two points that are specified by the coordinates (x 1 , y 1 ) and (x 2 , y 2 ). As given by the Pythagorean theorem, the distance is as follows,

Distance = ] x 2 – x 1 g^2 +^ y 2 – y 1 h^2

The first thing to be considered is the appearance of distance function in python. In such case the inputs are two points that can be represented by using four numbers. The return value will be the distance represented by floating-point value. The outline of the function is as follows,

def distance (p1, q1, p2, q2): return 0. The above statement returns zero rather than computing distances. But the syntax of it is correct and it even runs. Call it with sample arguments to test the new function.

distance (2, 3, 8, 5)

Some more code can be added to the body. One reasonable step would be to find the differences p 2 – p 1 and q 2 – q 1. The next step would be to store them in temporary variables and print them.

def distance (p1, q1, p2, q2): d 1 = p 2 – p 1 d 2 = q 2 – q 1 print('d 1 = ', d 1 ) print('d 2 = ', d 2 ) return 0. The above function displays d 1 = 6 and d 2 = 2. So it is clear that function has received correct arguments and it is even performing first computation correctly. Now compute the sum of squares d 1 and d 2.

def distance (p1, q1, p2, q2): d 1 = p 2 – p 1 d 2 = q 2 – q 1 dsquare = d 1 ** 2 + d 2 ** 2 print ('dsquare = ', dsquare) return 0. The above code must be tested whether it returns the correct result. Finally use math.sqrt to compute and return the result. def distance(p1, q1, p2, q2): d 1 = p 2 – p 1 d 2 = q 2 – q 1 dsquare = d 1 ** 2 + d 2 ** 2 res = math.sqrt (dsquare) return res If the above code works correctly then coding is assumed to be complete. It does not print anything rather it returns the result. While writing the code initially a line or two lines of code must be written at a time.

Programmer will write and debug bigger chunks based on the experience. In both the ways incremental development saves lot of debugging time.