Prac 5
Prac 5
PRACTICAL NO: 5
XI. Exercise
1.Print the following patterns using loop:
a)
Code:
n=4
for i in range(1, n + 1):
print('*' * i)
Output:
b)
Code:
rows = 3
for i in range(1, rows + 1):
print(" " * (rows - i) + "*" * (2 * i - 1))
c)
Code:
n=7
for i in range(0, n // 2 + 1):
for j in range(n - 2 * i):
if j % 2 == 0:
print('1', end='')
else:
print('0', end='')
print()
Output:
2. Write a Python program to print all even numbers between 1 to 100 using while loop.
Code:
num = 2
while num <= 100:
print(num, end=" ")
num += 2
Output:
3. Write a Python program to find the sum of first 10 natural numbers using for loop.
Code:
total = 0
for num in range(1, 11):
total += num
Output:
Code:
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b # Update to the next terms
Output:
if num < 0:
print("Factorial is not defined for negative numbers.")
elif num == 0:
print("The factorial of 0 is 1.")
else:
dd
reversed_num = 0
7. Write a Python program takes in a number and finds the sum of digits in a number.
Code:
def sum_of_digits(number):
total = 0
while number > 0:
total += number % 10
number //= 10
return total
dd
result = sum_of_digits(num)
print(f"The sum of digits in {num} is {result}.")
Output:
8. Write a Python program that takes a number and checks whether it is a palindrome or
not.
Code:
def is_palindrome(number):
num_str = str(number)
return num_str == num_str[::-1]
if is_palindrome(num):
print(f"{num} is a palindrome.")
else:
print(f"{num} is not a palindrome.")
Output: