Python Functions




1.     Write a program to generate prime numbers with the help of a function to test prime or not.

def genprime(no):
    flag=1
    for i in range(2,no):
      if no%i==0:
          flag=0
          break
    return flag

x=int(input("\nEnter  any number"))
ans=genprime(x)
if ans==1:
    print("The number is prime no")
else:
    print("The number is non prime no")



2.     Write a python program that removes any repeated items from a list so that each item appears at most once. For instance, the list [1,1,2,3,4,3,0,0] would become [1,2,3,4,0].

l=[1,1,2,3,4,3,0,0]
print("The original list is" ,l)
for i in l:
    if l.count(i)>1:
        l.remove(i)
print("The updated list is ",l)


3.        Write a program to pass a list to a function and display it.

def myfunction(lst):
    print("listvalue in function",lst)
    print("id of list in function",id(lst))
    lst.append(10)
    print("list value after updating in function",lst)
    print("id of list after updating in function",id(lst))
  
lst=[1,2,3,4,5,]
print("list value at calling place",lst)
print("id of list at calling place",id(lst))
myfunction(lst)
print("list value after calling the function",lst)
print("id of list after calling the function",id(lst))

4.     Write a program to demonstrate the use of Positional argument, keyword argument and default arguments.

#positional arguments
def posargf(s1,s2):
    s3=s1+s2
    print(s3)
posargf("abc","def")
posargf("def","abc")
#keyword arguments
def keyargf(rno,name):
     print("Roll no is ",rno, " name is ",name)
keyargf(rno=1,name="def")
keyargf(name="abc",rno=2)

#Default arguments
def defargf(rno,name='***'):
     print("Roll no is ",rno, " name is ",name)

defargf(1,"def")
defargf(2)


5.     Write a program to show variable length argument and its use.

def variargf(farg,*vargs):
     print("Formal argument",farg)
     for i in vargs:
          print("Variable argument",i)

variargf(1)
variargf(1,2,3,4)
variargf(1,"def")



6.       Write a lambda/Anonymous function to find bigger number in two given numbers.

fun=lambda x,y:max(x,y)
ans=fun(5,6)
print("Bigger number is",ans)

  


7.       Create a decorator function to increase the value of a function by 3.


def decor(fun):
     def funinside():
          ans=fun()
          return(ans*3)
     return funinside

def myfunction():
     return(10)

finalans=decor(myfunction)
print(finalans())