School: University of the People
Moodle ID: C110223808
Class: CS 1101 - Programming Fundamentals
Unit 5: Iteration and Strings
Group: 0036.
Course instructor: Muhammad Anwar Shahid.
Write program to display your name and perform following operations on it:
1. Display n characters from left. (Accept n as input from the user)
2. Count the number of vowels.
3. Reverse it.
Explanation:
1. Display n Characters from the Left:
o The slicing operation name[:n] extracts the first n characters from the string. This
uses Python’s zero-based indexing, where [:n] starts from index 0 and goes up to
(but not including) index n.
2. Count the Number of Vowels:
o We use a loop combined with a generator expression: sum(1 for char in name if
char in vowels).
o Here, each character in the string is checked against a list of vowels
(aeiouAEIOU). If the character is a vowel, it contributes 1 to the sum.
o This ensures both uppercase and lowercase vowels are counted accurately.
3. Reverse the String:
o The slicing operation name [::-1] is a Python way to reverse a string. The third
parameter -1 specifies the step value, indicating that the slice should traverse the
string backward.
Strings in Python are immutable sequences of characters. This allows us to use operations like
slicing ([:]), membership tests (in), and built-in functions (like sum). The slicing operator is
especially versatile, as it can extract substrings or reverse them with appropriate parameters.
The code demonstrates clear use of Python’s strengths in handling strings concisely and
efficiently:
Slicing ([:n] and [::-1]) avoids the need for explicit loops.
The generator expression in the vowel count avoids storing intermediate results, making
it memory-efficient.