Python Programs With Output
Python Programs With Output
# Creating strings
str1 = "Hello"
str2 = "World"
# Concatenating strings
str3 = str1 + " " + str2
print("Concatenated String:", str3)
# Accessing sub-string
print("Sub-string (0 to 4):", str3[0:5])
Expected Output:
Concatenated String: Hello World
Sub-string (0 to 4): Hello
Expected Output:
Sample Input:
Enter first number: 25
Enter second number: 17
Enter third number: 40
Output:
The largest number is: 40
Expected Output:
Prime numbers less than 20:
2 3 5 7 11 13 17 19
Expected Output:
Enter a number: 5
Factorial of 5 is 120
# Creating a list
my_list = [1, 2, 3]
print("Initial List:", my_list)
# Appending an element
my_list.append(4)
print("After Appending:", my_list)
# Removing an element
my_list.remove(2)
print("After Removing 2:", my_list)
Expected Output:
Initial List: [1, 2, 3]
After Appending: [1, 2, 3, 4]
After Removing 2: [1, 3, 4]
6. Tuple Demonstration
# Creating a tuple
my_tuple = (10, 20, 30, 40)
Expected Output:
First element: 10
Sliced tuple: (20, 30)
7. Dictionary Demonstration
# Creating a dictionary
student = {'name': 'Alice', 'age': 22, 'course': 'Python'}
# Accessing and modifying dictionary
print("Name:", student['name'])
student['grade'] = 'A'
print("Updated Dictionary:", student)
del student['age']
print("After Removing Age:", student)
Expected Output:
Name: Alice
Updated Dictionary: {'name': 'Alice', 'age': 22, 'course': 'Python', 'grade': 'A'}
After Removing Age: {'name': 'Alice', 'course': 'Python', 'grade': 'A'}
# fib_module.py
def fibonacci(n):
fib_series = []
a, b = 0, 1
while len(fib_series) < n:
fib_series.append(a)
a, b = b, a + b
return fib_series
# main.py
import fib_module
n = int(input("Enter the number of Fibonacci terms: "))
print("Fibonacci Series:", fib_module.fibonacci(n))
Expected Output:
Enter the number of Fibonacci terms: 6
Fibonacci Series: [0, 1, 1, 2, 3, 5]
def display(self):
print("Name:", self.name)
print("Age:", self.age)
Expected Output:
Name: John
Age: 21
10. Inheritance
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(self.name, "makes a sound")
# Derived class
class Dog(Animal):
def speak(self):
print(self.name, "barks")
Expected Output:
Buddy barks