TERM WORK-2
1. Write a python program to demonstrate various ways of accessing the string.
i) By using indexing (both positive and negative)
ii) By using slice operator
# String for demonstration
text = "Hello, Python!"
# Accessing string by using Indexing
print("Accessing string using indexing:\n")
# Positive indexing
print(f"First character (positive indexing): {text[0]}")
print(f"Fifth character (positive indexing): {text[4]}\n")
Output
First character (positive indexing): H
Fifth character (positive indexing): o
# Negative indexing
print(f"Last character (negative indexing): {text[-1]}")
print(f"Second to last character (negative indexing): {text[-2]}\n")
Output
Last character (negative indexing): !
Second to last character (negative indexing): n
# Accessing string by using slice operator
print("\nAccessing string using slice operator:\n")
# Slicing with positive indices
#Syntax text[start:end], by defaults start is set to 0
#text[:5] is the same as text[0:5]
print(f"First five characters: {text[:5]}")
print(f"Characters from index 7 to end: {text[7:]}\n")
Output
First five characters: Hello
Characters from index 7 to end: Python!
# Slicing with negative indices
print(f"Last five characters: {text[-5:]}")
#text[-5:] means "start from index -5 and go to the end of the string."
print(f"Characters from -7 to -2: {text[-7:-2]}\n")
Output
Last five characters: thon!
Characters from -7 to -2: Pytho
# Slicing with a step
#text[start:stop:step]
print(f"Every second character: {text[::2]}")# step = 2
print(f"Reversed string: {text[::-1]}\n")# -1 as the step means reverse the string
Output
Every second character: Hlo yhn
Reversed string: !nohtyP ,olleH
2. Demonstrate following functions or methods which operate on strings with suitable examples.
# Define a sample string for demonstration
text = "Hello, Python!"
# len(): Returns the length of the string (including spaces).
print("\nlength of string: ", len(text)) #Includes spaces
# Output: length of string: 14
# strip(): Removes leading and trailing spaces.
text = " Hello, Python! " # String with spaces at the beginning and end
print("\nString after strip():", [Link]())
# Output: String after strip(): Hello, Python!
# rstrip(): Removes spaces from the right end of the string.
text = " Hello, Python! " # String with spaces at the beginning and end
print("\nString after rstrip():", [Link]())
# Output: String after rstrip(): Hello, Python!
# lstrip(): Removes spaces from the left end of the string.
print("\nString after lstrip():", [Link]()) # removes leading spaces
# Output: String after lstrip(): Hello, Python!
# find(): Returns the index of the first occurrence of the substring.
text = "Hello, Python!"
print("\nIndex of first 'Python' using find():", [Link]("Python")) # 7
# Output: Index of first 'Python' using find(): 7
# rfind(): Returns the index of the last occurrence of the substring.
text = "Python is fun. Python is powerful."
print("\nIndex of last 'Python' using rfind():", [Link]("Python"))
# Output: Index of last 'Python' using rfind(): 15
# index(): Similar to find().
text = "Hello, Python!"
print([Link]("Python")) # Output: 7
# rindex():Finds the last occurrence of a substring.
text = "Python is fun. Python is powerful."
print([Link]("Python")) # Output: 15
# count(): Counts how many times the substring occurs in the string.
text = "Hello, Python Python!"
print("\nCount of 'Python': ", [Link]("Python"))
# Output: Count of 'Python': 2
# replace(): Replaces occurrences of a substring with another substring.
text = "Hello, Python!"
print("\nReplacing 'Python' with 'Java':", [Link]("Python", "Java"))
# Output: Replacing 'Python' with 'Java': Hello, Java!
# split(): Splits the string by whitespace and returns a list of words.
text = "Python is awesome"
print([Link]())
# Output: ['Python', 'is', 'awesome']
# join(): Joins a list of strings with a separator.
words = ["Python", "is", "awesome"]
print(" - ".join(words))
# Output: Python - is – awesome
# upper(): Converts all characters in the string to uppercase.
text = "Hello, Python!"
print([Link]())
# Output: HELLO, PYTHON!
# lower(): Converts all characters in the string to lowercase.
print([Link]())
# Output: hello, python!
# swapcase(): Swaps the case of all characters in the string.
print([Link]())
# Output: hELLO, pYTHON!
#title(): Capitalizes the first letter of each word.
text = "python is fun"
print([Link]())
# Output: Python Is Fun
# capitalize(): Capitalizes the first letter of the string.
text = "python IS Fun"
print([Link]())
# Output: Python is fun
# startswith(): Checks if the string starts with a specified substring.
text = "Hello, Python!"
print([Link]("Hello"))
# Output: True
# endswith(): Checks if the string ends with a specified substring.
text = "Hello, Python!"
print([Link]("!"))
# Output: True
# Write a program to find factorial of a given number
def factorial(n):
if n == 0 or n == 1: # Base case: factorial of 0 and 1 is 1
return 1
else: # Recursive case: multiply n by the factorial of n-1
return n * factorial(n - 1)
# Input from the user
num = int(input("Enter a number: ")) # Get user input as an integer
# Call the factorial function and display the result
print(f"The factorial of {num} is {factorial(num)}") # Output the result
Output
Enter a number: 0
The factorial of 0 is 1
Enter a number: 1
The factorial of 1 is 1
Enter a number: 2
The factorial of 2 is 2
Enter a number: 3
The factorial of 3 is 6
Enter a number: 4
The factorial of 4 is 24
Enter a number: 5
The factorial of 5 is 120 # and so on..
Journal Programs
2 a. Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
# Step 1: Read input from user
N = int(input("Enter the length of the Fibonacci sequence: "))
# Step 2: Initialize the first two numbers in the Fibonacci sequence
a, b = 0, 1
# Step 3: Loop N times to generate the sequence
for _ in range(N): # _ is a placeholder Runs the loop N times.
print(a, end=" ") # Step 4: Prints current Fibonacci number value on same line.
a, b = b, a + b # Step 5: Update values of a and b for the next iteration
Output
Enter the length of the Fibonacci sequence: 6
011235
2 b. Write a function to calculate factorial of a number. Develop a program to compute
binomial coefficient (Given N and R).
Example:
# Function to calculate the factorial of a number
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Function to calculate the binomial coefficient (N choose R)
def binomial_coefficient(N, R):
if R > N:
return 0 # Binomial coefficient is 0 if R > N
# Using the formula C(N, R) = N! / (R! * (N - R)!)
return factorial(N) // (factorial(R) * factorial(N - R))
# Input from the user
N = int(input("Enter value for N: "))
R = int(input("Enter value for R: "))
# Call the binomial coefficient function and display the result
print(f"The binomial coefficient C({N}, {R}) is {binomial_coefficient(N, R)}")
Output
Enter value for N: 5
Enter value for R: 2
The binomial coefficient C(5, 2) is 10