0% found this document useful (0 votes)
2 views20 pages

Python Lab Programs

The document provides various Python programming examples, including functions for arithmetic operations, finding the largest number, calculating the sum of even numbers, and determining factors and GCD. It also discusses recursion, its advantages and disadvantages, and compares recursion with iteration. Additionally, it covers error handling in Python with examples for voter age validation and marks range validation.

Uploaded by

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

Python Lab Programs

The document provides various Python programming examples, including functions for arithmetic operations, finding the largest number, calculating the sum of even numbers, and determining factors and GCD. It also discusses recursion, its advantages and disadvantages, and compares recursion with iteration. Additionally, it covers error handling in Python with examples for voter age validation and marks range validation.

Uploaded by

gayathricascas
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Parameters

We can pass different number of parameters to the function. Following example


illustrates the parameter passing to the function

Example 3.6.2 Write a Python program for creating simple calculator,

Solution :

def add(x, y):

return x + y

def sub(x, y):

return x – y

def mult(x,y)

return x * y

def div(x, y):

return x/y

print("Main Menu")

print("[Link]")

print("[Link]")

print("[Link]")

print("[Link]")

print("Enter your choice")

choice = int(input())

print("Enter first number")

num1 = int(input())

print("Enter second number: ")

num2 = int(input())
if choice = = 1:

print(num1,"+", num2,"=", add(num1,num2))

elif choice = = 2:

print(num1,"-", num2,"=", sub(num1,num2))

elif choice = = 3:

print(num1,"*",num2,"=", mult(num1,num2))

elif choice = = 4:

print(num1,"/", num2,"=", div(num1,num2))

else:

Output

Main Menu

[Link]

[Link]

[Link]

[Link]

Enter your choice

Enter first number

10

Enter second number:

20

10 + 20 = 30

>>>
Example 3.6.3 Write a python program to find the largest among the three
numbers.

Solution :

def largest(x, y,z):

if (x > y) and (x > z):

print("First Number is largest")

elif (y > x) and (y > z):

print("Second Number is largest")

else:

print("Third Number is largest")

print("Enter first number")

num1 = int(input())

print("Enter second number: ")

num2 = int(input())

print("Enter third number: ")

num3 = int(input())

print(largest(num1,num2,num3))

Example 3.6.4 Write a Python program using function to find the sum of first
'n' even numbers and print the result.

AU : Jan.-18, Marks 6

Solution :

# first n even numbers

# function to find sum of

# first n even numbers

def evensum(n):
step = 2

sum = 0

i=1

# sum of first n even numbers

while i < = n:

sum + = step

# next even number

step + = 2

i=i+1

return sum

# Driver Code

print("Enter value of n")

n = int(input())

print("sum of first", n, "even number is: ",evensum(n))

Output

Enter value of n

sum of first 3 even number is: 12

Example 3.6.5 Write a Python program using function to find the factors of a
given number.

Solution :

#define a function

def Find_factors(n):

# This function takes a number and prints the factors


print("The factors of,n,"are:")

for i in range(1, n + 1):

if n %i = = 0:

print(i)

print("Enter a number: ")

num=int(input())

Find_factors(num)

Output

Enter a number :

12

The factors of 12 are:

12

Example 3.6.6 Write a Python program using function to find the GCD of two
numbers

Solution :

# define gcd function

def gcd(a, b):

while(b):
a, b = b, a % b

return a

num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: ")).

print("The G.C.D of", num1,"and", num2,"is", gcd(num1, num2))

Output

Enter first number: 12

Enter second number: 15

The G.C.D of 12 and 15 is 3

3. Local and Global Scope


• The global variables are those variables that are declared and defined outside
the function and can be used inside the function.

• The local variables are those variables that are declared and defined inside a
function.

• A global variable is one that can be accessed anywhere. A local variable is the
opposite, it can only be accessed within its frame.

• The difference between the global and local is that global variables can be
accessed locally, but not modified locally inherently.

• For example : In the following program, variable a is global variable.

def fun():

print(a)

#global scope

a = 10 fun()

Output

10
Now consider following program, in which we try to change the value declared
outside the function

def f():

print(a)

a = 100 #Due to this statement the error is raised

# Global scope

a = 10

f()

print(a)

To make the above program work, we need to use global keyword. We only
need to use global keyword in a function if we want to do change that variable.

The corrected version of above program is as follows:

def f():

global a

print(a)

a = 100

# Global scope

a = 10

f()

print(a)

Output

10

100

4. Function Composition
• Function composition is a way of combining functions such that the result of
each function is passed as the argument of the next function.

• For example, the composition of two functions f and g is denoted f(g(x)). Here
x is the argument of g, the result of g is passed as the argument of f and the
result of the composition is the result of f.

For example

Step 1: Create a simple function for addition of two numbers.

def add(a,b):

return a+b

Step 2: Create a simple function for multiplication of two numbers

def mul(c,num):

return c*num

Step 3: Create a main function in which the two functions used in above two
steps are called.

def mainFun(x,y):

z = add(x,y)

result = mul(z, 10)

return result

The complete program will now look like this


Step 4: Now execute the above program by pressing F5 key. The output can be
obtained as follows -
Recursion
AU : Jan.-18, Dec.-19, Marks 10

Definition : Recursion is a property in which one function calls itself repeatedly


in which the values of function parameter get changed on each call.

Properties of Recursion

There are three important laws of recursion –

1. A recursive function must have a base case.


2. A recursive function must change its state and move toward the base case.

3. A recursive function must call itself, recursively.

Example 3.7.1 Display the numbers from 10 to 1 (ie, numbers in reverse order)
using recursion in python. Also draw the stack diagram representing the
execution of the program.

Solution :

def display(n):

if n < = 0:

return

else:

print(n)

display(n-1)

Output
The execution of above program can be diagrammatically shown as follows:

Example 3.7.2 Write a python program for recursive factorial function,

Solution :

def factorial(n):

if n = = 0:

return 1
else:

result = n * factorial(n-1)

return result

print(factorial(5))

Output

120

Example 3.7.3 Write a python program to display the Fibonacci series upto n
numbers using recursion

Note The Fibonacci numbers are 0,1,1,2,3,5,8,13,21,34,.., where each number


is a sum of the preceding two numbers.

AU : Jan.-18, Marks 8

Solution :

def fibonacci(n):

if(n < = 1);

return n

else:

return(fibonacci(n-1) + fibonacci(n-2))

print("Enter number of terms ")

n = int(input())

print("Fibonacci sequence is as follows...")

for i in range(n):

print (fibonacci(i))

Output
Example 3.7.4 Implement a recursive function in python for sieve of
Eratosthenes. The Sieve of Eratosthenes is a simple algorithm for finding all
prime numbers up to a specified integer.

AU : Dec.-19, Marks 10

Solution :

def Sieve(i,num):

if num = ri:

return 0

else:
if(num%i = = 0);

return 1

else:

return Sieve(i+1, num)

n = int(input("Enter last Number:"))

print("Prime Number Between 1 to n are: ")

for i in range(2,n+1):

if(Sieve(2,1)= =0):

print(i,end="")

Output

Enter last Number:50

Prime Number Between 1 to n are:

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

>>>

1. Advantages and Disadvantages


Advantages

1) It reduces the length of code.

2) It is very useful while applying the same pattern of solution.

3) It reduces unnecessary calling of function.

4) Big and complex iterative solutions are easy and simple with Python
recursion.

Disadvantages

1) Recursive functions are slower than iterative solutions.

2) It is hard to analyse or understand the code.


3) It may require a lot of memory space to hold intermediate results on the
system stack.

4) The computer memory may run out of memory if the recursive calls are not
properly checked.

2. Comparison of Recursions with Iteration


Recursion

1. The function is called itself repeatedly.

2. The intemal stack is used to store the set of local variables

3. Recursion is always applied to function

4. Slow in execution.

5. Recursion reduces the size of the code.

Iteration

1. The set of instructions is executed repeatedly

2. It does not use stack.

3. Iteration is applied to control statements such as for loops, while and do while
statements.

4. Fast in execution.

5. Iteration makes the code lengthyExperiment 7 : Implementing programs


using Strings. (reverse, palindrome, character count, replacing characters)

Solution :

Programming Examples Based on String


Example 3.8.2 Write a Python program to find the length of a string

Solution :

def str_length(str):

len = 0
for ch in str:

len + = 1

return len

print(“\t\t Program to find the length of a string”)

print(“Enter some string:”)

str = input()

print(“Length of a string is: “,str_length(str))

Output

Program to find the length of a string

Enter some string:

Python

Length of a string is : 6

>>>

Experiment 8 : Implementing programs using written modules and Python


Standard Libraries (pandas, numpy. Matplotlib, scipy)

Solution :

Refer section 4.5.2

Experiment 9 : Implementing real-time/technical applications using File


handling. (copy from one file to another, word count, longest word)

Solution :

Refer section 5.6


Experiment 10 : Implementing real-time/technical applications using
Exception handling. (divide by zero error, voter's age validity, student mark
range validation)

Solution :

Errors and Exceptions AU : Jan.-18, May-19, Dec.-19, Marks 1


Errors are normally referred as bugs in the program. They are almost always the
fault of the programmer. The process of finding and eliminating errors is called
debugging.

There are mainly two types of errors :

1. Syntax errors: The python finds the syntax errors when it parses the source
program. Once it find a syntax error, the python will exit the program without
running anything. Commonly occurring syntax errors are :

(i) Putting a keyword at wrong place

(ii) Misspelling the keyword

(iii) Incorrect indentation

(iv) Forgetting the symbols such as comma, brackets, quotes

(v) Empty block

2. Run time errors : If a program is syntactically correct - that is, free of syntax
errors – it will be run by the python interpreter. However, the program may exit
unexpectedly during execution if it encounters a runtime error. The run-time
errors are not detected while parsing the source program, but will occur due to
some logical mistake. Examples of runtime error are :

(i) Trying to access the a file which does not exists

(ii) Performing the operation of incompatible type elements

(iii) Using an identifier which is not defined

(iv) Division by zero Such type of errors are handled using exception handling
mechanism.

Voter's Age Validation


Python Program

try:

age = int(input("Enter your age: "))

if age > 18:

print("Eligible to vote!!!")

else:

print("Not eligible to vote!!!")

except ValueError as err:

print(err)

finally:

# code to be executed whether exception occurs or not

#typically for closing files and other resources

print("Good Bye!!!")

Output(Run 1)

Enter your age: 20

Eligible to vote!!!

Good Bye!!!

>>>

Output(Run 2)

Enter your age: twenty

invalid literal for int() with base 10: 'twenty'

Good Bye!!!

>>>
Marks Range Validation (0-100)
Python Program

while True :

try:

num = int(input("Enter a number between 1 and 100: "))

if num in range(1,100):

print("Valid number!!!")

break

else :

print("Invalid number. Try again.")

except :

print("That is not a number. Try again.")

Output

Enter a number between 1 and 100: -1

Invalid number. Try again.

Enter a number between 1 and 100-10000

Invalid number. Try again.

Enter a number between 1 and 100- five

This not a number . Try again

Enter a number between 1 and 100: 99

Valid number

>>>

You might also like