Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python_Unit1_Part2

The document provides an overview of Python control flow, including sequential, selection, and repetition structures. It explains various control statements such as if, for, while loops, and exception handling using try-except blocks. Additionally, it covers loop control statements like break and continue, as well as the importance of handling exceptions for improved program reliability and cleaner code.

Uploaded by

angelsonu2026
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)
2 views

Python_Unit1_Part2

The document provides an overview of Python control flow, including sequential, selection, and repetition structures. It explains various control statements such as if, for, while loops, and exception handling using try-except blocks. Additionally, it covers loop control statements like break and continue, as well as the importance of handling exceptions for improved program reliability and cleaner code.

Uploaded by

angelsonu2026
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/ 23

Ⅳ SEM BCA PYTHON

Python Control Flow

Program‘s control flow is the order in which the program‘s code executes. The control flow of
a Python program is regulated by conditional statements, loops, and function calls.
Python has three types of control structures:

• Sequential - default mode


• Selection - used for decisions and branching

• Repetition - used for looping, i.e., repeating a piece of code multiple times.

1. Sequential statements are a set of statements whose execution process happens in a


sequence. The problem with sequential statements is that if the logic has broken in any one of
the lines, then the complete source code execution will break.
Eg. a=20
b=10
c=a-b
print("Subtraction is : ",c)
2. Selection/Decision control statements
In Python, the selection statements are also known as Decision control statements or branching
statements.The selection statement allows a program to test several conditions and execute
instructions based on which condition is true.
Some Decision Control Statements in Python are: if, if-else and nested if

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 1


Ⅳ SEM BCA PYTHON

If statement : If statements are control flow statements that help us to run a particular code,
but only when a certain condition is met or satisfied. A simple if only has one condition to
check.

n = 10
if n % 2 == 0:
print("n is an even number")

If-Else statement : The if-else statement evaluates the condition and will execute the body
of if if the test condition is True, but if the condition is False, then the body of else is executed.

Eg, n = 10
if n % 2 == 0:
print("n is an even number")
Else:
print("n is an odd number")
if-elif-else: The if-elif-else statement is used to conditionally execute a statement or a block of
statements. While using if-elif statement at the end else block is added which is performed if
none of the above if-elif statement is true.

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 2


Ⅳ SEM BCA PYTHON

Syntax:-

if (condition):
statement

elif (condition):
statement

else:
statement

Eg.
x = 15
y = 12
if x == y:
Print(―both are equal‖)
elif x > y:

print("x is greater than y")


else:

print("x is smaller than y")

3. Iteration / Repetition statements


Repetition statements are used to repeat a code of programming instructions.

In Python, we generally have two loops/repetitive statements:

• for loop ( counting loop)


• while loop ( conditional loop)

3.1 For loop: The for loop is used to run a block of code for a certain number of times. It is
used to iterate over any sequences such as list, tuple, string, etc.
The syntax of the for loop is:

for <variable> in <sequence>:


# statement(s)

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 3


Ⅳ SEM BCA PYTHON

Here, variable accesses each item of sequence on each iteration. Loop continues until we reach
the last item in the sequence.

For eg,
For i in [1,2,3,4,5] :
Print (i)
Will give the output as
1
2
3
4
5
Range () Function : The range() is a built-in function generates a sequence of
numbers starting from the given start integer to the stop integer. Range() function can be used
along with for loop to generate the iterating sequence.
Syntax

range(start, stop, step)


Generate numbers between 0 to 6

for i in range(1,6):
print(i)

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 4


Ⅳ SEM BCA PYTHON

will generate a sequence [1,2,3,4,5] and the output of this program will be numbers 1 to 5.
Some Important points to remember about the Python range() function:
• range() function only works with the integers, i.e. whole numbers.
• All arguments must be integers. Users can not pass a string or float number or any other
type in a start, stop and step argument of a range().
• All three arguments can be positive or negative. A negative step implies that sequence
is generated in descending oeder.

• The step value must not be zero. If a step is zero, python raises an Error.
• Users can access items in a range() by index
Program example : Write a python program to print the multiplication table of 5 using For loop
# Program to print table of 5
Num = 5

for i in range(0,11):
print (num," x",i," =",5*i)

print(―Program over‖)
Output
5 x 0 = 0
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50 Program
over

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 5


Ⅳ SEM BCA PYTHON

3.2 While Loop : With the while loop we can execute a set of statements as long as a condition
is true.
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 that returns a Boolean value of true/false. The loop iterates while the condition
is true.
When the condition becomes false, program control passes to the line immediately following
the loop.
Steps in writing a While loop
The steps to create and use a while loop are:

• Create a variable that holds the initial value.


• Start a while loop with a condition that involves the variable created in step 1.

• Write the logic inside the while loop that should be executed if the condition is True.
The condition is always checked first and only if it‘s True, the logic inside of the while
loop will be executed otherwise the code that follows the while loop will be executed.

• Change the value of the variable created inside the while loop so that eventually the
condition becomes false and loop gets over.
• Repeat.

Eg,
i= 1 # counter variable that is assigned an initial value
while(i <4): # Logical condition that is to be checked
print(i)
i = i+1 # incrementing value of i
print(― end of while loop‖)

Output:
1
2
3
4

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 6


Ⅳ SEM BCA PYTHON

Write a python program to print the factorial of a number using while loop

num = int(input("enter a number: "))

fact = 1
i=1
while(i <= num):
fact = fact * i
i=i+1

print("factorial of ", num, " is ", fact)

Output :
enter a number: 4
factorial of 4 is 24

Loop Control / Jump Statements ( Break and Continue)

Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes,
there may arise a condition where you want to exit the loop completely, skip an iteration or
ignore that condition. These can be done by loop control statements. Loop control statements
change execution from its normal sequence. Python supports the following control statements.
• Break statement
• Continue statement
• Pass statement

Break Statement : The break statement terminates the loop containing it. 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.

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 7


Ⅳ SEM BCA PYTHON

Example: Python break


# Use of break statement inside loop
for val in "string":
if val == "i":
break
print(val)
print("The end")

Output
s
t
r
The end

Continue statement : 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.

Example: Python continue


# Program to show the use of continue statement inside loops
for val in "string":
if val == "i":
continue

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 8


Ⅳ SEM BCA PYTHON

print(val)
print("The end")
Output
s
t
r
n
g
The end

exit() Function : While writing a Python script, sometimes you‘ll recognize a need to stop
script execution at certain points during the execution. This can be done using Python exit
commands.
Commands you can use to exit a program in Python include:
• The quit() function
• The exit() function
• The sys.exit() function

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 9


Ⅳ SEM BCA PYTHON

Python‘s in-built exit() function is defined in site.py. It works only if the site module is
imported. Like quit(), exit() also raises SystemExit exception. Here, exit(0) implies a clean exit
without any issues, while exit(1) implies some issue, which was the only reason for exiting the
program.

Python command to exit program: exit() Example

for value in range(0,10):


# If the value becomes 6 then the program prints exit
if value == 6:
print(―exiting the program‖)
exit()
print(value)
Output :
0
1
2
3
4
5
Exiting the program

Exceptions in Python:
An exception in Python is an incident that happens while executing a program that causes the
regular course of the program's commands to be disrupted. When a Python code comes across a
condition it can't handle, it raises an exception. An object in Python that describes an error is
called an exception.
When a Python code throws an exception, it has two options: handle the exception immediately
or stop and quit
Different types of exceptions in python:
In Python, there are several built-in exceptions that can be raised when an error occurs during the
execution of a program. Here are some of the most common types of exceptions in Python:

SyntaxError: This exception is raised when the interpreter encounters a syntax error in the
code, such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
TypeError: This exception is raised when an operation or function is applied to an object of the
wrong type, such as adding a string to an integer.

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 10


Ⅳ SEM BCA PYTHON

NameError: This exception is raised when a variable or function name is not found in the
current scope.
IndexError: This exception is raised when an index is out of range for a list, tuple, or other
sequence types.
KeyError: This exception is raised when a key is not found in a dictionary.
ValueError: This exception is raised when a function or method is called with an invalid
argument or input, such as trying to convert a string to an integer when the string does not
represent a valid integer.
AttributeError: This exception is raised when an attribute or method is not found on an object,
such as trying to access a non-existent attribute of a class instance.
IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails
due to an input/output error.
ZeroDivisionError: This exception is raised when an attempt is made to divide a number by
zero.
ImportError: This exception is raised when an import statement fails to find or load a module.
These are just a few examples of the many types of exceptions that can occur in Python.

Exceptions versus Syntax Errors


When the interpreter identifies a statement that has an error, syntax errors occur. Consider the
following scenario:
Code
1. string = "Python Exceptions"
2.
3. for s in string:
4. if (s != o:
5. print( s )
Output:
if (s != o:

SyntaxError: invalid syntax

Try and Except Statement - Catching Exceptions


In Python, we catch exceptions and handle them using try and except code blocks. The try clause
contains the code that can raise an exception, while the except clause contains the code lines that

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 11


Ⅳ SEM BCA PYTHON

handle the exception. Let's see if we can access the index from the array, which is more than the
array's length, and handle the resulting exception .
1. # Python code to catch an exception and handle it using try and except code blocks
2.
3. a = ["Python", "Exceptions", "try and except"]
4. try:
5. #looping through the elements of the array a, choosing a range that goes beyond the
length of the array
6. for i in range( 4 ):
7. print( "The index and element from the array is", i, a[i] )
8. #if an error occurs in the try block, then except block will be executed by the Python inte
rpreter
9. except:
10. print ("Index out of range")

Output:

The index and element from the array is 0 Python


The index and element from the array is 1 Exceptions
The index and element from the array is 2 try and except
Index out of range

Try with Else Clause

Python also supports the else clause, which should come after every except clause, in the try, and
except blocks. Only when the try clause fails to throw an exception the Python interpreter goes
on to the else block.

Finally Keyword in Python


The finally keyword is available in Python, and it is always used after the try-except block. The
finally code block is always executed after the try block has terminated normally or after the try
block has terminated for some other reason.
Here is an example of finally keyword with try-except clauses:

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 12


Ⅳ SEM BCA PYTHON

Code

1. # Python code to show the use of finally clause


2.
3. # Raising an exception in try block
4. try:
5. div = 4 // 0
6. print( div )
7. # this block will handle the exception raised
8. except ZeroDivisionError:
9. print( "Atepting to divide by zero" )
10. # this will always be executed no matter exception is raised or not
11. finally:
12. print( 'This is code of finally clause' )
Output:
Atepting to divide by zero

This is code of finally clause

Catching Specific Exception


A try statement can have more than one except clause, to specify handlers for different
exceptions. Please note that at most one handler will be executed. For example, we can add
IndexError in the above code. The general syntax for adding specific exceptions are –
try:

# statement(s)
except IndexError:

# statement(s)
except ValueError:

# statement(s)

Advantages of Exception Handling:

 Improved program reliability: By handling exceptions properly, you can prevent your
program from crashing or producing incorrect results due to unexpected errors or input.

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 13


Ⅳ SEM BCA PYTHON

 Simplified error handling: Exception handling allows you to separate error handling
code from the main program logic, making it easier to read and maintain your code.

 Cleaner code: With exception handling, you can avoid using complex conditional
statements to check for errors, leading to cleaner and more readable code.

 Easier debugging: When an exception is raised, the Python interpreter prints a


traceback that shows the exact location where the exception occurred, making it easier
to debug your code.

Disadvantages of Exception Handling:

 Performance overhead: Exception handling can be slower than using conditional


statements to check for errors, as the interpreter has to perform additional work to catch
and handle the exception.

 Increased code complexity: Exception handling can make your code more complex,
especially if you have to handle multiple types of exceptions or implement complex
error handling logic.

 Possible security risks: Improperly handled exceptions can potentially reveal sensitive
information or create security vulnerabilities in your code, so it‘s important to handle
exceptions carefully and avoid exposing too much information about your program.

User Defined Functions

Functions that readily come with Python are called built-in functions. If we use functions
written by others in the form of library, it can be termed as library functions.

All the other functions that user creates himself come under user-defined functions. So, our
user-defined function could be a library function to someone else.
• In Python, a user-defined function's declaration begins with the keyword def and
followed by the function name.
• The function may optionally take arguments(s)/parameters(s) as input within the
opening and closing parentheses, just after the function name followed by a colon.
Arguments are the information needed by function to perform its task. For eg, for the
function that calculates sum of 2 numbers, the 2 numbers to be added are passed as
arguments.

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 14


Ⅳ SEM BCA PYTHON

• After defining the function name and arguments(s) a block of program statement(s)
start at the next line and these statement(s) must be indented. Generally a Return
statement is the last line in body of a function that returns the result and the control
back to the calling program.
• The function is then called in the main program any number of times with different
arguments just by writing its name. Its important to remember that a function‘s body is
executed only when it is called and not when it is defined.

The syntax for writing user defined functions in Python is

Syntax

def <function-name>(<parameters >):


statements

[body of function]
Return statement

#main body of program

Statements
#function call
<function-name>(<arguments>)

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 15


Ⅳ SEM BCA PYTHON

Arguments and Parameters : The terms parameter and argument can be used for the same
thing: information that are passed into a function. From a function's perspective: A parameter
is the variable listed inside the parentheses in the function definition. An argument is the value
that are sent to the function when it is called.

Lets look at an example of user define function with the name Greet with the task of greeting
people with their name, the name is passed as an argument from calling environment.

def greet(name): # function definition


print ('Hello ', name) #the only statement inside function body

# main body of program


greet('Steve') # function call with an argument
greet(‗Monika‘) # function call again with a different argument
Output
Hello Steve
Hello Monika

Function with Return Value


In the above function Greet no value was returned to calling program ,such functions are called
Void functions but most of the time, we need the result of the function to be used in further
processes. In Non-Void type functions, when a function returns the execution control back to
program, it should also return a value.

A user-defined function can be made to return a value to the calling environment by putting an
expression in front of the return statement. In this case, the returned value has to be assigned to
some variable.

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 16


Ⅳ SEM BCA PYTHON

For eg, the user defined function calcsum calculates the sum of 2 numbers

def calcsum(a, b):


return a + b

#main program
X=10
Y=10
Total1=sum(10, 20) # variable(total1)assigned to catch the returned value
Total 2= sum(X,Y)
print(Total1)
print(Total2)
Output

30

20

Default Parameters :While defining a function, its parameters may be assigned default values.
This default value gets substituted if an appropriate actual argument is passed when the
function is called. However, if the actual argument is not provided, the default value will be
used inside the function.
The following greet() function is defined with the name parameter having the default
value 'Guest'. It will be replaced only if some actual argument is passed.
Example: Parameter with Default Value
def greet(name = 'Guest'):

print ('Hello', name)


# main body of program

greet() # will use default name


greet('Steve') # will ignore default
Output

Hello Guest
Hello Steve

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 17


Ⅳ SEM BCA PYTHON

Keyword Arguments : Mostly arguments are passes as Positional arguments, which means
values that are passed into a function is based on the order in which the parameters were listed
during the function definition. Here, the order is especially important as values passed into
these functions are assigned to corresponding parameters based on their position.
Keyword arguments (or named arguments) are values that, when passed into a function, are
identifiable by specific parameter names. A keyword argument is preceded by a parameter and
the assignment operator, = .
For eg,
def team(name, project):

print(name, "is working on an", project)


team(project = "Edpresso", name = 'FemCode') #order of arguments do not matter since they
are called by keywords

With keyword arguments, as long as you assign a value to the parameter, the positions of the
arguments do not matter.
Command-line arguments are simple parameters that are given on the system's command
line, and the values of these arguments are passed on to your program during program
execution. When a program starts execution without user interaction, command-line arguments
are used to pass values or files to it.
There are three different ways we can implement the concept of command-line argument in
Python. These are:
• Using the sys module

• Using the getopt module


• Using the argparse module

The following script allows us to pass in values from the command line into Python:
import sys

n = int(sys.argv[1])
print(n+1)

We save these few lines into a file and run it in command line with an argument:
$ python commandline.py 15

16
Then, you will see it takes our argument, converts it into an integer, adds one to it, and prints.

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 18


Ⅳ SEM BCA PYTHON

Example of Python Program Using User Defined function


Write a python program to convert Celcius to Fahrenheit using User defined function. Here a
user defined function name convertTemp uses a single value argument that is passed to it when
function is called
# Python program to convert Celsius to Fahrenheit

def convertTemp(c): #user-defined function


# find temperature in Fahrenheit
f = (c * 1.8) + 32
return f

# take inputs
cel = 15

# calling function and display result


fahr = convertTemp(cel)
print('%0.1f degrees Celsius is equivalent to %0.1f
degrees Fahrenheit' %(cel, fahr))

Recursive Functions

The term Recursion can be defined as the process of defining something in terms of itself. In
simple words, it is a process in which a function calls itself directly or indirectly.

Advantages of using recursion


 A complicated function can be split down into smaller sub-problems utilizing recursion.
 Sequence creation is simpler through recursion than utilizing any nested iteration.
 Recursive functions render the code look simple and effective.
Disadvantages of using recursion
 A lot of memory and time is taken through recursive calls which makes it expensive for
use.
 Recursive functions are challenging to debug.
 The reasoning behind recursion can sometimes be tough to think through.
Syntax:
def func(): <--
|
| (recursive call)
|

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 19


Ⅳ SEM BCA PYTHON

func() ----
# Program to print factorial of a number
Example
def recursive_factorial(n):
if n == 1:
return n
else:
return n * recursive_factorial(n-1)

# user input
num = 6

# check if the input is valid or not


if num < 0:
print("Invalid input ! Please enter a positive number.")
elif num == 0:
print("Factorial of number 0 is 1")
else:
print("Factorial of number", num, "=", recursive_factorial(num))

Scope and Lifetime of variables

The scopes of the variables depend upon the particular location where the variable is being
declared. Variables can be defined with the two types of scopes—
The place where we can locate a variable, and it is also accessible if needed, is named the
scope of a variable. Every variable in a program is not possible to be accessed at every location
in that program. It depends on how you have declared it in the program.
The scope of a variable defines the part of the program where you can enter an appropriate
identifier.

There are two primary scopes of variables in Python:

 Local variable
 Global variable

Local variables:

The local variables are declared and defined inside the function and are only accessible inside
it.
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 20
Ⅳ SEM BCA PYTHON

Global variables:

The global type of variables is the one that is determined and declared outside any of the
functions and is not designated to any function. They are accessible in any part of the program
by all the functions. Whenever you call a function, the declared variables inside it are carried
into scope. The global variables are accessible from inside any scope, global and local.

The lifetime of a variable in Python:

The variable lifetime is the period during which the variable remains in the memory of the
Python program. The variables' lifetime inside a function remains as long as the function runs.
These local types of variables are terminated as soon as the function replaces or terminates.

Local variable

example code

def msg():
msg1="Hello world , this is a local variable "
print(msg1)
msg()
print(msg1)

OUTPUT

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 21


Ⅳ SEM BCA PYTHON

def f():

# local variable

s = "I love Geeksforgeeks"

print("Inside Function:", s)

# Driver code

f()

print(s)

Output:
NameError: name 's' is not defined

Global Variable

example code

def cal(args):
s=0
for arg in args:
s=s + arg
print(s)
s=0
args=[19,20,29]
cal(args)
print("outside the func.",s)

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 22


Ⅳ SEM BCA PYTHON

OUTPUT

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 23

You might also like