0% found this document useful (0 votes)
4 views3 pages

Python Programs for Digit Sum & Fibonacci

Uploaded by

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

Python Programs for Digit Sum & Fibonacci

Uploaded by

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

Program 1: Write a program in python to find the sum of digits in a number.

n=int(input("Enter a number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits is:",tot)

Output:

Enter a number:17

The total sum of digits is: 8

Program 2: Write a program in python to print given number in reverse order


using while loop.

num = 1234
reversed_num = 0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print("Reversed Number: " , reversed_num)
Output:
Reversed Number: 4321
Program 3: Write a program in Python to print the Fibonacci sequence

# Program to display the Fibonacci sequence up to n-th term


nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

Output

How many terms? 5

Fibonacci sequence:

3
Prog.4: Write a program in python to find nth Fibonacci term using recursion.

def fib(n):
if n==1:
return 1
elif n==2:
return 1
else:
return fib(n-1)+fib(n-2)
n=int(input('Enter the number:\t'))
f=fib(n)
print('the nth fib term is', f)

Output:

Enter the number: 8

the nth fib term is 21

Prog. 5 : Write a program in python to find the sum of digits in a number using recursion.

def sum_of_digit(n):
if n<10:
return n
else:
return n%10 + sum_of_digit(n//10)
n=int(input('Enter number'))
print('sum of digit is', sum_of_digit(n))

output:

Enter number148

sum of digit is 13

You might also like