pfatagaga
pfatagaga

Reputation: 15

What is wrong with the following Python Script?

Can someone explain me what's wrong with the following script?

I have started learning programming in Python very recently so this might be very trivial for the experienced out here but please look into it and let me know what's wrong with it. The idea is to write a script that reverses a given string. I understand there is a simpler way of doing this using s[::-1] but I would like to do it in my own way. Does the error have anything to do with z not being defined in a proper way? If so, please do let me know how to fix it. Thanks!

def reverse(x):
    y = len(x)
    for i in range(y-1):
        z[i] == x[y - 1 - i]    
    return z

Upvotes: 0

Views: 160

Answers (3)

Lauritz V. Thaulow
Lauritz V. Thaulow

Reputation: 50995

First, from you recent comment I deduce that your python program is executed as a bash script. To have it execute properly, add this line to the top:

#!/usr/bin/env python

Then there's the reverse function. The others have all pointed out that you need to use the assignment operator (=) and not the equality operator (==). But that doesn't solve the problem, because z is undefined. But how should we define it? It can't be a string, because strings are immutable, so you can't change single characters in a string like you're attempting to do.

The pythonic solution, if you're determined to use an algorithm exactly like this, is to let z be a list, and use the join method of string to concatenate the characters in the list z to a single string at the end. But we're not out of the woods yet either. The range(y - 1) is a list from 0 to y - 2, but you want to have y - 1 in that list as well. So we need to use range(y) instead.

All together this gives us the following code:

def reverse(x):
    y = len(x)
    z = list(x) # Using the characters of x will give it the correct length
    for i in range(y):
        z[i] = x[y - 1 - i]
    return "".join(z)

Upvotes: 1

misterjinx
misterjinx

Reputation: 2616

One error that I see is that you are using the comparison operator (==) on line 5 where you perhaps wanted to use the assign operator (=)

Upvotes: 0

Or Duan
Or Duan

Reputation: 13810

You used double "=" which return True or False for comparison. you should use "=".

i highly recommend you to read about the operators because it will save you a lot of time when coding:

http://www.tutorialspoint.com/python/python_basic_operators.htm

Upvotes: 4

Related Questions