Practical 2
Practical 2
1. Write a program to find nCr and nPr. Scan the value of n and r from the user. Use
recursive function for factorial calculation.
def factorial(n):
"""Recursive function to calculate factorial"""
if n == 0:
return 1
else:
return n * factorial(n-1)
Output:
Enter value of n: 5
Enter value of r: 4
nCr = 5.0
nPr = 120.0
2. Create a function isPrime(n) which returns 1 if n is prime and 0 if not prime. Scan
the value of n from the user.
def isPrime(n):
"""Function to check if a number is prime"""
if n < 2:
return 0
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return 0
return 1
Practical 2 1
# Get input from user
n = int(input("Enter a number: "))
# Check if n is prime
if isPrime(n):
print(f"{n} is prime")
else:
print(f"{n} is not prime")
Output:
Enter a number: 5
5 is prime
Enter a number: 6
6 is not prime
3. Execute the sample program given below. Note down your understanding about the
scope of variables.
def g(x):
def h():
x = 'abc'
x = x + 1
print('in g(x): x =', x)
h()
return x
x = 3
z = g(x)
The above code defines two functions, g(x) and h() , and then assigns a value to
x and calls g(x) . However, there is an issue with the code that will cause it to raise
a TypeError.
The issue is in the line x = x + 1 inside the h() function. Here, x is a string that is
being concatenated with an integer value 1. This is not a valid operation, and it will
raise a TypeError. Instead, if the intention is to increment the integer value of x by
1, x should be an integer to begin with.
4. Write a program with a function isPal () to check whether the input string is a
palindrome or not.
Practical 2 2
def isPal(s):
"""Function to check if a string is a palindrome"""
s = s.lower()
# Remove non-alphanumeric characters from string
s = ''.join(char for char in s if char.isalnum())
return s == s[::-1]
# Check if s is a palindrome
if isPal(s):
print(f"{s} is a palindrome")
else:
print(f"{s} is not a palindrome")
Output:
5. Execute the following program and explain what it does and Suggest a possible
improvement in the implementation.
The above code defines two functions, printMove(fr, to) and Towers(n, fr, to,
spare) , and then calls the Towers() function with arguments 4, 'P1', 'P2', and 'P3'.
However, there is no output when the code is run, because the Towers() function
does not return anything and the call to print() is commented out.
Practical 2 3