A flexible approach to getting user input is to use a while-true loop, breaking
when conditions are met. The structure is easy to remember and allows you to
handle user mistakes without awkward setup or code repetition:
while True:
x = input('...')
if x is OK:
break
I realize the variable names are coming from your teacher's instructions, but
both of you should strive for better variable names. Better does not always
mean longer (brevity and clarity are both worthy goals and they are at odds
sometimes); but it does mean using variable names that are meaningful
in context. For example, letters
is a better name for a string of letters
than n
, which is a purely abstract name (even worse, it adds confusion
because n
is often/conventionally used for numeric values).
There is no need to build T
character by character. Python strings are
iterable and therefore directly convertible to lists.
Python strings, lists, and tuples are directly iterable: just iterate over the
values and don't bother with the soul-crushing tedium imposed by many less-cool
programming languages where you must iterate over indexes. And for cases when
you need both values and indexes, use enumerate()
.
Use simple comments as sign-posts and organizational devices to make
your code more readable. This habit will serve you well as you try
to write bigger, more complex programs.
# Get user input.
while True:
prompt = 'Enter 5 to 10 letters, without spaces or punctuation: '
letters = input(prompt)
if len(letters) in range(5, 11) and letters.isalpha():
break
# List of the original letters.
T = list(letters)
# List of letters with case flipped.
V = []
for c in letters:
c2 = c.lower() if c.isupper() else c.upper()
V.append(c2)
# Same thing, in one shot.
V = [
c.lower() if c.isupper() else c.upper()
for c in letters
]
# Check.
print(T)
print(V)
N
in your code snippet, and it is unclear what "between 5 and 10" means. \$\endgroup\$