1) factorial program: expected: Input: n = 6
Output: 720
Explanation: 6! = 6 × 5 × 4 × 3 × 2 × 1 = 720
n = 6
if n < 0:
print("Factorial is not defined for negative numbers")
else:
f = 1
for i in range(1, n+1):
f *= i
print(f)
#720
if n < 0: checks for negative numbers; factorial isn’t defined.
f = 1: initializes the product.
for i in range(1, n+1): f *= i multiplies all numbers from 1 to n iteratively.
2) Python program for counting the digits in a number.
num=int(input("Enter number: "))
count=0
i = num
# count the digits
while(i>0):
count=count+1
i=i//10
print(f"The number of digits in {num}:",count)
#Enter number:8516
The number of digits in 8516: 4
Top comments (0)