Social Media

2/06/2019

Examples on functions

Script1: Write a function in python which can calculate the factorial of a number entered by the user.
def calfact(n):
    x=1
    while n!=1:
        x*=n
        n-=1
    return x

a=int(input("Enter the number "))

f=calfact(a)
print("The factorial is {}".format(f))

Script2: Write a function in python which can print the fibonacci series up to n numbers, value of n is entered by the user.
def printfibo(n):
    x=1
    y=2
    if n==1:
        print(x)
        return
    print(x,end=" ")
    print(y,end=" ")
    while n!=2:
        print(x+y,end=" ")
        x,y=y,x+y
        n-=1

n=int(input("Enter the number "))

printfibo(n)



Script3. Write a function which can decide whether the entered number by the user is prime or not.
def checkprime(n):
    i=2
    if n==1 or n==2:
        print("Number is prime")
        return
    while i!=n-1:
        if n%i==0:
            print("Number is not prime")
            break
        i+=1
    else:
        print("Number is prime")

x=int(input("Enter the number "))

checkprime(x)

Script4: Write a function which check whether the number entered by the user is armstrong or not.
def checkarmstrong(n):
    sum=0
    temp=n
    while n!=0:
        sum+=(n%10)**3
        n//=10
    if sum==temp:
        print("Number is armstrong")
    else:
        print("Number is not armstrong")

print("Enter the number ")

x=int(input())
checkarmstrong(x)

Script5: Write a function which check whether the entered string is palindrome or not.
def checkpalindrome(s):

    m=s[::-1]
    if m==s:
        print("String is palindrome")
    else:
        print("String is not palindrome")

print("Enter the string you want to check ")

x=input()
checkpalindrome(x)



Be First to Post Comment !
Post a Comment