Sorry for the noobish question, but I'm trying to write a function that accepts strings as inputs. Here's what I've got:

def backwards(x):
word = "x"
index = 1
while index < len(word)+1:
letter = word[-index]
print letter
index = index + 1

Whenever I call the function, such as backwards(word), it gives me a name undefined error. How do I get it to accept the input?

Thanks for the help!

In python variable types are not important. You should just assign x to your string and strike the line word = "x". This assigns word to the string x not to the string of the value stored in the variable x as you were probably intending. You also want to start with index zero since python starts iterable objects at position zero (this would also cause you to remove the +1 in your loop statement).

Thank you for the quick response. I modified the function and removed word but I'm getting the same error. Now the function looks like this:

def backwards(x):
index = 0
while index < len(x):
letter = x[-index]
print letter
index = index + 1


I'm getting the same error:

Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
backwards(something)
NameError: name 'something' is not defined

When you enter the word something without quotation marks or apostrophes python thinks that you are referencing a variable. This is why you are getting the error. In order to pass the function the string something you need to call the function as follows:

backwards('something')

I think NineTrails solved the error. You should use code tags. Your code would be easier to read.

Are you trying to print a string backwards?

>>> x = 'something'
>>> x[::-1]
'gnihtemos'
>>>

Putting the input in quotes worked! Thank you guys so much! Yes, I'm trying to write a function that prints words backwards (Working through "How to Think Like a Computer Scientist" by myself). I knew the problem had to do with the input and now I know what it is! This is one lesson I won't soon forget; I've been trying to figure it out all week.

also for the last line of your code

index = index + 1

#you could simplify this to

index += 1

this does the exact same thing and is simpler to write...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.