Reputation: 13
I am trying to create code that gathers a user's first and last name (input order is last, first) and prints it first, last in a cascading way:
J
o
h
n
S
m
i
t
h
I'm really close, but I don't like the way my code works. I think there's an easier way, and I'm also running into issues where I get IndexError: string index out of range if I put in a name that is longer than how many print statements I put in. Any ideas?
here's my code:
last = raw_input('enter your last name:')
first= raw_input('enter your first name:')
print(first[0])
print('\t' + first[1])
print('\t'*2 + first[2])
print('\t'*3+first[3])
print('\t'*4+first[4])
print('\t'*5+first[5])
print('\t'*6+first[6])
print(last[0])
print('\t' + last[1])
print('\t'*2 + last[2])
print('\t'*3+last[3])
print('\t'*4+last[4])
print('\t'*5+last[5])
Upvotes: 1
Views: 913
Reputation: 4287
You can write a generic function, like the one shown below and reuse for your strings.
def cascade_name(name):
for i, c in enumerate(name):
print '\t'*(i+1), c
output:
>>> cascade_name("foo")
f
o
o
In your case you would do:
last = raw_input('enter your last name:')
first= raw_input('enter your first name:')
cascade_name(last)
cascade_name(first)
Upvotes: 1