Python Forum
Problem with for loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with for loop
#1
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.
Yoriz write May-19-2021, 08:58 PM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
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.
Reply
#3
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)
Yoriz write May-20-2021, 06:05 AM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#4
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.
Reply
#5
Note that input returns a string, so str(input( is redundant.
Reply
#6
this is my code, hope it helps
word = input("Please input a word: ")
print(word[::-1])
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trivia2 Loop problem? milll929 3 3,913 Jun-07-2017, 12:46 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020