Python Assignment Answers Simple
Python Assignment Answers Simple
Q3. Write a program to generate and print the first n Fibonacci numbers using a loop.
n = int(input("Enter n: "))
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
Q5. Write a Python program to find the Least Common Multiple (LCM) of two numbers.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
gcd = 1
for i in range(1, min(a, b) + 1):
if a % i == 0 and b % i == 0:
gcd = i
lcm = (a * b) // gcd
print("LCM:", lcm)
Q6. Write a recursive function to compute the sum of the first n natural numbers.
def sum_n(n):
if n == 1:
return 1
return n + sum_n(n - 1)
n = int(input("Enter n: "))
print("Sum:", sum_n(n))
Q8. Write a recursive function to count the number of digits in a given number.
def count_digits(n):
if n < 10:
return 1
return 1 + count_digits(n // 10)
n = int(input("Enter number: "))
print("Number of digits:", count_digits(n))
Q10. Write a recursive function to generate the binary representation of a given decimal
number.
def to_binary(n):
if n <= 1:
return str(n)
return to_binary(n // 2) + str(n % 2)
n = int(input("Enter a number: "))
print("Binary:", to_binary(n))