Sure! Here's a program that displays a name and performs the given operations on it:
Python:
name = input("Enter your name: ") # Takes the name as input from the user
# 1. Display n characters from left
n = int(input("Enter the number of characters to display from left: "))
left_characters = name[:n]
print("Characters from left:", left_characters)
# 2. Count the number of vowels
vowels = ['a', 'e', 'i', 'o', 'u'] # List of vowels
count = 0
for char in name:
if char.lower() in vowels: # Convert character to lowercase and check if it's a vowel
count += 1
print("Number of vowels:", count)
# 3. Reverse the name
reversed_name = name[::-1]
print("Reversed name:", reversed_name)
Explanation:
1. The program starts by taking the name as input from the user using the
input()
function and stores it in the variable
name
.
2. The program then prompts the user to enter the number of characters they want to display from the left, using the
input()
function again. The input is converted to an integer using
int()
and stored in the variable
n
.
3. To display the n characters from the left, we use string slicing. The variable
left_characters
stores the characters sliced from the left of the
name
string using the syntax
name[:n]
. The characters are then printed using the
print()
function.
4. To count the number of vowels in the name, we initialize a count variable to 0. Then, we iterate through each character in the
name
string using a
for
loop. Inside the loop, we convert the character to lowercase using the
lower()
method and check if it is a vowel by comparing it with the
vowels
list using the
in
operator. If it is a vowel, we increment the
count
variable by 1. Finally, the count is printed using the
print()
function.
5. To reverse the name, we use string slicing again. The variable
reversed_name
stores the reversed name by slicing the
name
string with a step value of -1 (
name[::-1]
). The reversed name is then printed using the
print()
function.
By following the above steps, the program displays the name, the specified number of characters from the left, counts the number of vowels, and reverses the name.