-2

I am new to programming. I am trying to write a code to print the reverse of any given string. I have written the following code:

import math
string= raw_input ("Enter string")
n= len(string)
ol= n-1
for ol>-1,ol--:
    print string[ol]

but i am getting syntax error. Please help me to figure this out.

Nelson Menezes
  • 109
  • 2
  • 8

3 Answers3

4

Python tries very hard to present code in a readable way. This means you don't get many of the ugly, hard to understand shortcuts that other languages like C offer. Instead, you get other, much easier to understand shortcuts.

The code to loop over a range in python is:

for ol in range(n):

To iterate backwards, use

for ol in range(n-1,-1,-1):

But of course, someone couldn't resist and add an unreadable shortcut to the language:

print string[::-1]

Related:

Community
  • 1
  • 1
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
1

You can use these links for your further work, i know that this answer is out of the topic:

Code Academy

People all over the world are learning with Codecademy.

Python the hard way

Learn Python The Hard Way, 3rd Edition

Python Monk

Free, interactive tutorials to help you discover Python idioms, in your browser!

badc0re
  • 3,333
  • 6
  • 30
  • 46
1

If you want to code the string reverse yourself, try this as well. This will be useful when you reverse a very large string. You just have to traverse only half of it.

Data = list("ABCDEF")
Len  = len(Data)

for i in range(Len//2):
    Data[i], Data[Len - i - 1] = Data[Len - i - 1], Data[i]

Data = ''.join(Data)

print Data

NOTE: This solution is just for learning. For practical purposes, use @Aaron Digulla's third option. It will give far better performance than anything else. Its called slicing. Read about it here http://docs.python.org/2/tutorial/introduction.html#strings

print string[::-1]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497