Python Forum

Full Version: Problem with for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am doing a homework question where it's asking me to print a word backwards. So far I have the following code:
#My name

word=str(input("Please input a word."))

def backwards_word(word):
  print(word)
  count=0
  backwardsword=""
  for letter in range(len(word), 0, -1)
    backwardsword=backwardsword+word[letter]
backwards_word(word)
I'm trying to make it print the word backwards.
However, I'm getting an error on this line:
for letter in range(len(word), 0, -1)
It's giving me a syntax error. I'm not very familiar with for loops, so I would be glad if you can help.
A for loop should end with :
example
letters = 'letters'
for letter in letters:
    print(letter)

You don't need to use range to go backwards by using the index, you should go backwards directly
numbers = '1234'
for number in numbers[::-1]:
    print(number)
Output:
4 3 2 1

Some problems noted with your code
  1. Indentation should be 4 spaces.
  2. indexing word[letter] with your current method will give an index error.
  3. The function does not return anything.
Thanks for your help, ignore the previous version of the message as I managed to make the code work.

The code is here (albeit it still has some efficiency flaws):
#My name

word=str(input("Please input a word."))

def backwards_word(word):
     print(word)
     count=0
     backwardsword=""
     length=len(word)
     for letter in range(10, 0, -1):
         backwardsword=backwardsword+word[letter]
backwards_word(word)
It does not work, it raises an IndexError: string index out of range, you have hardcoded a the range value of 10, my list of problems above still apply.
Note that input returns a string, so str(input( is redundant.
this is my code, hope it helps
word = input("Please input a word: ")
print(word[::-1])