Python_Unit1_Part2
Python_Unit1_Part2
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:
• Repetition - used for looping, i.e., repeating a piece of code multiple times.
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.
Syntax:-
if (condition):
statement
elif (condition):
statement
else:
statement
Eg.
x = 15
y = 12
if x == y:
Print(―both are equal‖)
elif x > y:
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:
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
for i in range(1,6):
print(i)
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
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:
• 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
Write a python program to print the factorial of a number using while loop
fact = 1
i=1
while(i <= num):
fact = fact * i
i=i+1
Output :
enter a number: 4
factorial of 4 is 24
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.
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.
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
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.
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.
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.
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:
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.
Code
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Improved program reliability: By handling exceptions properly, you can prevent your
program from crashing or producing incorrect results due to unexpected errors or input.
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.
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.
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.
• 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.
Syntax
[body of function]
Return statement
Statements
#function call
<function-name>(<arguments>)
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.
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.
For eg, the user defined function calcsum calculates the sum of 2 numbers
#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'):
Hello Guest
Hello Steve
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):
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
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.
# take inputs
cel = 15
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.
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
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.
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 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
def f():
# local variable
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)
OUTPUT