-3

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)

3 Answers3

3

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)
user156213
  • 736
  • 4
  • 12
2

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])
Cyphase
  • 11,502
  • 2
  • 31
  • 32
1

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953