[go: up one dir, main page]

0% found this document useful (0 votes)
3 views26 pages

Ii MSC Python Unit Ii Notes

The document outlines the contents of a programming course focused on Python, covering topics such as decision making, loops, and functions. It details various programming constructs including if statements, loops, and function definitions, along with examples and syntax. The document serves as a comprehensive guide for understanding fundamental programming concepts in Python.

Uploaded by

RCW CS 18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views26 pages

Ii MSC Python Unit Ii Notes

The document outlines the contents of a programming course focused on Python, covering topics such as decision making, loops, and functions. It details various programming constructs including if statements, loops, and function definitions, along with examples and syntax. The document serves as a comprehensive guide for understanding fundamental programming concepts in Python.

Uploaded by

RCW CS 18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

DCS33– PROGRAMMING USING PYTHON

CONTENTS
UNIT - 2

Chapter Topic’s Page No


2.1 Python - Decision Making 1
2.1.1 If Statements 2
2.1.2 If...else statements 4

2.1.3 Nested If Statements 5

2.2 Python – Loops 6


2.2.1 Python nested loop 7

2.3 Types of Loops 9

2.3.1 While Loop Statements 9


2.3.2 for Loop Statements 11
2.3.3 Loop Control Statements 12
2.3.4 The break Statement 13

2.3.5 The continue Statement 14

2.4 Functions 14
2.4.1 Defining a Function 14

2.5 Call a function in python 16

2.6 Function Arguments 16


2.6.1 Required arguments 17
2.6.2 Keyword arguments 17
2.6.3 Default arguments 19
2.6.4 Variable-length arguments 21
2.7 Python Recursion 21
2.7.1 Python Recursive Function 21
DCS33-PROGRAMMING USING PYTHON UNIT II

2.1 Python - Decision Making

 Decision making is anticipation of conditions occurring while execution of the program


and specifying actions taken according to the conditions.
 Decision structures evaluate multiple expressions which produce TRUE or FALSE as
outcome.
 You need to determine which action to take and which statements to execute if outcome
is TRUE or FALSE otherwise.
 Following is the general form of a typical decision making structure found in most of the
programming languages −

 Python programming language assumes any non-zero and non-null values as TRUE,
and if it is either zero or null, then it is assumed as FALSE value.

 Python programming language provides following types of decision making statements.

1 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

S.No. Statement & Description

1 if statements

An if statement consists of a boolean expression followed by one or more


statements.

2 if...else statements

An if statement can be followed by an optional else statement, which executes


when the boolean expression is FALSE.

3 nested if statements

You can use one if or else if statement inside another if or else if statement(s).

2.1.1 If Statements

 The if statement contains a logical expression using which data is compared and a
decision is made based on the result of the comparison.

Syntax

if expression:
statement(s)

 If the Boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed.

 If Boolean expression evaluates to FALSE, then the first set of code after the end of the
if statement(s) is executed.

2 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

Flow Diagram

var1 = 100
if var1:
print "1 - Got a true expression value"
print var1

var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"

When the above code is executed, it produces the following result −

1 - Got a true expression value


100
Good bye!

3 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

2.1.2 If...else statements

 An else statement can be combined with an if statement.


 An else statement contains the block of code 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.

var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1

var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2

4 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

print "Good bye!"

When the above code is executed, it produces the following result −

1 - Got a true expression value


100
2 - Got a false expression value
0
Good bye!

2.1.3 Nested If Statements

 The elif statement allows you to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE.

 In a nested if construct, you can have an if...elif...else construct inside


another if...elif...else construct.

syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)

DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


5
DCS33-PROGRAMMING USING PYTHON UNIT II

Example
var = 100
if var == 200:
print "1 - Got a true expression value"
print var
elif var == 150:
print "2 - Got a true expression value"
print var
elif var == 100:
print "3 - Got a true expression value"
print var
else:
print "4 - Got a false expression value"
print var

print "Good bye!"

When the above code is executed, it produces the following result −

3 - Got a true expression value


100
Good bye!

2.2 Python – Loops

 The first statement in a function is executed first, followed by the second, and so on.
There may be a situation when you need to execute a block of code several number of
times.
 A loop statement allows us to execute a statement or group of statements multiple times.

6 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

 The following diagram illustrates a loop statement –

2.2.1 Python nested loops.

 Python programming language allows using one loop inside another loop. Following
section shows few examples to illustrate the concept.

Syntax

for iterating_var in sequence:


for iterating_var in sequence:
statements(s)
statements(s)

The syntax for a nested while loop statement in Python programming language is as follows −

while expression:
while expression:
statement(s)
statement(s)

7 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

Example

The following program uses a nested for loop to find the prime numbers from 2 to 100 −

i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print i, " is prime"
i=i+1

print "Good bye!"

When the above code is executed, it produces following result −

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime

8 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Good bye!

2.3 Types of Loops

S.No. Loop Type & Description

1 while loop

Repeats a statement or group of statements while a given condition is TRUE. It tests the
condition before executing the loop body.

2 for loop

Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.

3 nested loops

You can use one or more loop inside any another while, for or do..while loop.

2.3.1 While Loop Statements

 A while loop statement in Python programming language repeatedly executes a target


statement as long as a given condition is true.

9 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

Syntax

The syntax of a while loop in Python programming language is

While expression: statement(s)

 Here, statement(s) may be a single statement or a block of statements.


 The condition may be any expression, and true is any non-zero value. The loop iterates
while the condition is true.
 When the condition becomes false, program control passes to the line immediately
following the loop.

Example
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1

print "Good bye!"

10 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

When the above code is executed, it produces the following result −

The count is: 0


The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
2.3.2 for Loop Statements

It has the ability to iterate over the items of any sequence, such as a list or a string.

Syntax
for iterating_var in sequence:
statements(s)

 If a sequence contains an expression list, it is evaluated first. Then, the first item in the
sequence is assigned to the iterating variable iterating_var.

 Next, the statements block is executed. Each item in the list is assigned to iterating_var,
and the statement(s) block is executed until the entire sequence is exhausted.

Flow Diagram

11 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

for letter in 'Python': # First Example


print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example
print 'Current fruit :', fruit

print "Good bye!"

When the above code is executed, it produces the following result −

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!

2.3.3 Loop Control Statements

 Loop control statements change execution from its normal sequence.

 When execution leaves a scope, all automatic objects that were created in that scope are
destroyed.

12 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

S.No. Control Statement & Description

1 break statement

Terminates the loop statement and transfers execution to the statement immediately
following the loop.

2 continue statement

Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating.

2.3.4 The break Statement

With the break statement we can stop the loop even if the while condition is true:

Example

Exit the loop when i is 3:

i=1
while i < 6:
print(i)
if i == 3:
break
i += 1

OUTPUT:

1
2
3

13 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

2.3.5 The continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

Example

Continue to the next iteration if i is 3:

i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)

OUTPUT:

1
2
4
5
6

2.4 Functions

 A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing.

2.4.1 Defining a Function

 In Python, a function is a group of related statements that performs 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.

14 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

 Furthermore, it avoids repetition and makes the code reusable.

Syntax of Function

def function_name(parameters):

"""docstring"""

statement(s)

Above shown is a function definition that consists of the following components.

Keyword def that marks the start of the function header.


A function name to uniquely identify the function. Function naming follows the same rules of
writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.

A colon (:) to mark the end of the function header.

Optional documentation string (docstring) to describe what the function does.

One or more valid python statements that make up the function body. Statements must have the
same indentation level (usually 4 spaces).

7. An optional return statement to return a value from the function.


Example of a function

def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")

15 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

2.5 Call a function in python

 Once we have defined a function, we can call it from another function, program or even
the Python prompt.

 To call a function we simply type the function name with appropriate parameters.

Example:

def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")

greet('Paul')

ouput:
>>> greet('Paul')
Hello, Paul. Good morning!

2.6 Function Arguments

You can call a function by using the following types of formal arguments −

 Required arguments

 Keyword arguments

 Default arguments

16 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

 Variable-length arguments

2.6.1 Required arguments

 Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the function
definition.

 To call the function printme(), you definitely need to pass one argument, otherwise it gives
a syntax error as follows −

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme()

When the above code is executed, it produces the following result −

Traceback (most recent call last):


File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)

2.6.2 Keyword arguments

 Keyword arguments are related to the function calls. When you use keyword arguments
in a function call, the caller identifies the arguments by the parameter name.

17 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

 This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters. You
can also make keyword calls to the printme() function in the following ways

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme( str = "My string")

When the above code is executed, it produces the following result −

My string

 The following example gives more clear picture. Note that the order of parameters does
not matter.

# Function definition is here


def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )

When the above code is executed, it produces the following result −

Name: miki

18 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

Age 50

2.6.3 Default arguments

 A default argument is an argument that assumes a default value if a value is not


provided in the function call for that argument.

 The following example gives an idea on default arguments, it prints default age if it is
not passed

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )

When the above code is executed, it produces the following result

Name: miki
Age 50
Name: miki
Age 35

2.6.4 Variable-length arguments

 To process a function for more arguments than you specified while defining the
function.

19 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

 These arguments are called variable-length arguments and are not named in the function
definition, unlike required and default arguments.

 Syntax for a function with non-keyword variable arguments is this −

def functionname([formal_args,] *var_args_tuple ):


"function_docstring"
function_suite
return [expression]

 An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments.

 This tuple remains empty if no additional arguments are specified during the function
call. Following is a simple example −

# Function definition is here


def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )

When the above code is executed, it produces the following result −

Output is:
10
Output is:

20 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

70
60
50

2.7 Python Recursion


 Recursion is the process of defining something in terms of itself.

 A physical world example would be to place two parallel mirrors facing each other. Any
object in between them would be reflected recursively.

2.7.1 Python Recursive Function

In Python, we know that a function can call other functions. It is even possible for the
function to call itself. These types of construct are termed as recursive functions.
The following image shows the working of a recursive function called recuse.

Following is an example of a recursive function to find the factorial of an integer.

Factorial of a number is the product of all the integers from 1 to that number. For example, the
factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Example of a recursive function

def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

21 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

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

 In the above example, factorial() is a recursive function as it calls itself.


 When we call this function with a positive integer, it will recursively call itself by
decreasing the number.
 Each function multiplies the number with the factorial of the number below it until it is
equal to one. This recursive call can be explained in the following steps.

factorial(3) # 1st call with 3

3 * factorial(2) # 2nd call with 2

3 * 2 * factorial(1) # 3rd call with 1

3*2*1 # return from 3rd call as number=1

3*2 # return from 2nd call

6 # return from 1st call

22 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

Shows a step-by-step process of what is going on:

2.8 Function with more than one return value.


 Python functions can return multiple values. These values can be stored in variables
directly. A function is not restricted to return a variable, it can return zero, one, two or
more values.
 For returning multiple values from a function, we can return tuple, list or dictionary objects as per
our requirement.

Method 1: Using tuple

def func(x):

y0 = x+ 1

y1 = x * 3

y2 = y0 ** 3

return (y0, y1, y2)

23
DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI
DCS33-PROGRAMMING USING PYTHON UNIT II

UNIT II - FLOW CONTROL & FUNCTIONS

Syllabus: [Regulation: 2021]


UNIT2: Flow Control: Decision Making-Loops-Nested Loops-Types of Loops. Functions:
Function Definition-Function Calling - Function Arguments - Recursive Functions - Function with
more than one return value.

PART-A QUESTIONS

1. What are control flow statements in Python?


2. Define if-else statement.
3. What is a break statement?
4. What is a continue statement?
5. Compare return value and composition.
6. What is recursion?
7. Draw the flow diagram of while loop.
8. Write the syntax of if and if-else statements.
9. Define function? Write its syntax
PART-B QUESTIONS
1. Write recursive function to find factorial of a number.
2. Explain break and continue statement with the help of for loop with an example.
3. Explain function arguments in detail.
4. What are the advantages and disadvantages of recursion function?
5. Explain Call a function in python.
6. Explain the syntax and flow chart of the following loop statements
(i) for loop
(ii) while loop

1 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT II

PART-C QUESTIONS

1. Explain conditional statements in detail with example


2. Explain in detail about iterations with example.
3. Explain the usage of else statements in loops
4. Explain in detail about using for loop in sequence.
5. Explain about loop control statement.
6. What are nested Loops? Explain with examples.

2 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI

You might also like