How would loop the word that a user can input like the example below in python.
Enter a word: python (User can input any word)
p
py
pyt
pyth
pytho
python
(Then it loops the word inputted by the user)
How would loop the word that a user can input like the example below in python.
Enter a word: python (User can input any word)
p
py
pyt
pyth
pytho
python
(Then it loops the word inputted by the user)
Here are two more approaches!
Functional:
#!/usr/bin/env python3
in_word = input("Enter a word: ")
print("\n".join(\
map(lambda x:in_word[:x], range(1,len(in_word)+1)) \
))
Using recursion:
#!/usr/bin/env python3
in_word = input("Enter a word: ")
def print_word_recurse(word):
if(not word): return
print_word_recurse(word[:-1])
print(word)
print_word_recurse(in_word)
There may be better ways to do this, but this is the simplest:
string = 'python'
for index in range(1, len(string)):
print(string[:index])
Here's one way to do it, using Python 3 (1):
>>> s = input('Enter string: ')
Enter string: python
>>> for i in range(1,len(s)+1):
... print(s[:i])
...
p
py
pyt
pyth
pytho
python
It uses input()
to prompt for, and get, a string from the user.
It then iterates the i
variable from 1
to the length of the string (inclusive), each time printing out that many characters at the beginning of the string.
Once you become more adept at Python's potential for terseness, you could replace the for
loop with something like:
print(*[s[:i] for i in range(1,len(s)+1)],sep='\n')
or:
print("\n".join([s[:i] for i in range(1,len(s)+1)]))
but you may find that the readable solution is still the best :-)
(1) If you're stuck on Python 2 for some reason, remember to use raw_input()
and remove the parentheses from the print
line.