-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
0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

output = ''
for letter in 'Apple':
    output += letter
    print (output)

2 Comments

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.
Thanks for the comment. I am aware we create a new string, but string slices are just as expensive, and I feel less readable.
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])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.