0

I am just getting started on functions in Python. My goal is to loop a list with fruits and for each fruit, print it's letters backwards. When it hits a special character, it will stop and move on to the next fruit. I tried doing this with a loop and adding to the index each time but it would only print the first fruit correctly. If I just put the code for each fruit five times, it works perfectly. Please help me fix the index. Code is below.

def reverse(li):
    c = 1
    while c == 1:
        index = 0
        for c in reversed(li[index]):
            if c.isalpha():
                print(c, end="")
                index += 1
            else:
                print()
                index += 1
                break

fruits = ['ap!ple','bana@na','ma%ngo','#orange','pine*apple']
reverse(fruits)
2
  • Are you trying to reverse the first part of the word or the second part? ie, if you have 'ap!ple' are you expecting 'pa' or 'elp'? Commented Sep 1, 2018 at 17:11
  • Use a for-loop to loop over the strings in the list. No need for a while loop with indexes Commented Sep 1, 2018 at 18:59

2 Answers 2

2

You are looping through the first element of the list only (reversed(li[index])).

def reverse(li):
    for word in li:
        for rev_word in reversed(word):
            if rev_word.isalpha():
                print(rev_word, end="")
            else:
                print()
                break

fruits = ['ap!ple','bana@na','ma%ngo','#orange','pine*apple']
reverse(fruits)

Output:

elp
an
ogn
egnaro
elppa
Sign up to request clarification or add additional context in comments.

1 Comment

Good. I would also suggest to rename the variables: a better name for li would be words. A better name for ii would be word. Then for word in words would be much easier to read and understand.
2

You set index to 0, so only the first entry is used. Also, c is after the first iteration never equal to 1, so the while-loop is run only once.

Better create a new string, e.g. with takewhile and print it inside a for loop over all words:

from itertools import takewhile

def reverse(words):
    for word in words:
        print(''.join(takewhile(str.isalpha, reversed(word))))

fruits = ['ap!ple','bana@na','ma%ngo','#orange','pine*apple']
reverse(fruits)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.