Assignment p
Assignment p
n = int(input("Enter the number of characters to display from the left of your name: "))
if n > len(name):
print(f"Your input exceeds the length of the name. Showing the entire name: {name}")
else:
vowels = "aeiouAEIOU"
Technical Explanation
The program begins by defining a string variable name with a placeholder name ("John Doe"). The user can
The input() function is used to take a number, n, from the user, which specifies how many characters from the
left of the name should be displayed. The input is converted to an integer using int().
The program checks if the value of n is greater than the length of the name using len(name). If n exceeds the
If n is valid, the slice notation name[:n] retrieves the first n characters of the name.
Counting Vowels:
A string vowels containing all vowels (both uppercase and lowercase) is defined.
A generator expression sum(1 for char in name if char in vowels) is used to iterate through the characters in
name. For each character that matches a vowel, 1 is added to the total count. The result is stored in
vowel_count.
The slicing technique name[::-1] is used to reverse the order of characters in the name. The step -1 starts from
Output:
The results of all operations (n characters, vowel count, reversed name) are displayed using print() statements.
Example Output
Sample Input:
Enter the number of characters to display from the left of your name: 4
Sample Output:
Descriptive Analysis
This program showcases three fundamental string operations in Python: slicing, counting, and reversing. The
slicing operation demonstrates how to extract portions of a string using indices. Counting vowels illustrates the
use of iteration to process each character in a string and conditional logic to match specific characters.
These techniques are foundational for text processing tasks such as string manipulation, data cleaning, or
encoding/decoding algorithms. The program is robust, handling edge cases like invalid input (n exceeding the
name length). It provides clear outputs, making it user-friendly and educational for beginners learning Python.
References
Downey, A. (2012). Think Python: How to Think Like a Computer Scientist. Green Tea Press. Retrieved from
https://greenteapress.com/thinkpython2/thinkpython2.pdf