-2

My code below is not generalized; it handles each line of output as a special case. How I could get the same output using a while or for statement?

string = "Apple"
i = 0

one = string[0:i+1]
two = string[0:i+2]
three = string[0:i+3]
four = string[0:i+4]
five = string[0:i+5]

print(one)
print(two)
print(three)
print(four)
print(five)

I have the following result:

A
Ap
App
Appl
Apple
Prune
  • 76,765
  • 14
  • 60
  • 81
Mr. J
  • 87
  • 1
  • 7

3 Answers3

1

In Python we can iterate through a string to get the individual characters.

output = ''
for letter in 'Apple':
    output += letter
    print (output)
Edd Saunders
  • 138
  • 7
  • 1
    you do not need the semicolon at the end of each statement, and though you produce the correct output you are constantly creating a string at every iteration. – lmiguelvargasf Feb 24 '17 at 23:35
  • Thanks for the comment. I am aware we create a new string, but string slices are just as expensive, and I feel less readable. – Edd Saunders Feb 25 '17 at 00:53
1

Note that your variable i is useless: you set it to 0 and then use it only to add to things. Dump it.

This is a simple usage of the loop index:

for i in range(len(string)):
    print string[0:i+1]

Note that you can drop the 0 from the print statement.

Prune
  • 76,765
  • 14
  • 60
  • 81
0

With a for loop:

for i in range(len(string)):
    print(string[0:i+1])

With a while loop:

j = 0
while j < len(string):
    j += 1
    print(string[0:j])
Orphamiel
  • 874
  • 13
  • 22