Python Lab2
Python Lab2
def count_characters(string):
count = 0
for char in string:
count += 1
return count
Output
def count_vowels(string):
count = 0
for char in string:
if char == 'a' or char == 'e' or char == 'i' or char == 'o' or char == 'u' or \
char == 'A' or char == 'E' or char == 'I' or char == 'O' or char == 'U':
count += 1
return count
Output
3. Given two numbers, write a Python code to find the Maximum of two numbers (taken from user).
Input: a = 2, b = 4
Output: 4
Output
4. Write a program to find factorial of a number using Iteration.
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
Output
def factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers."
elif n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
Output
6. Write a program to print the ASCI value of all the characters in a string.
def print_ascii_values(string):
for char in string:
print(f"Character: {char} => ASCII Value: {ord(char)}")
Output
Hint: ord() is used to find the ASCI value of a character
7. Write a python program for Simple Calculator having following:
Select operation.
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
def calculator():
while True:
print("\nSelect operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
if choice == '5':
print("Exiting the calculator. Goodbye!")
break
if choice == '1':
result = num1 + num2
print(f"The result of {num1} + {num2} = {result}")
calculator()
Output
8. Create a function with TWO arguments (one of them is the default argument), and call the function.
Output
9. Write a Python program that calculates the sum of even and odd numbers separately within a given range. Implement a function
that takes the range as input and returns the sum of even and odd numbers within that range.
Output
10. Write a Python program to generate the multiplication table for a given number. Implement a function that takes the number as
input and prints its multiplication table up to a certain range (e.g., up to 10).
Output