0

I am getting used to coding in python by now and am trying to create a code that repeats any input backwards, I don't know how to condense the code or make it so that I don't have to press enter after every word or phrase. Here is my code so far...

a=input()
b=input()
if(b==""):
    print(a)
c=input()
if(c==""):
    print(b,a)
d=input()
if(d==""):
    print(c,b,a)
e=input()
if(e==""):
    print(d,c,b,a)
f=input()
if(f==""):
    print(e,d,c,b,a)
g=input()
if(g==""):
    print(f,e,d,c,b,a)
h=input()
if(h==""):
    print(g,f,e,d,c,b,a)
2
  • 2
    Use a string or list rather than many variables. Commented Sep 15, 2014 at 23:54
  • As a side note, read PEP 8. Even if this structure were the best one, if not b: is clearer than if (b==""):. Commented Sep 16, 2014 at 0:12

2 Answers 2

2

You can use slice notation to reverse a list. This applies to strings too, since they are essentially a list of characters.

>>> a = raw_input('type a word')
type a word
hello

>>> a[::-1]
'olleh'
Sign up to request clarification or add additional context in comments.

2 Comments

I think he's trying to reverse the order of words, not reverse each word. Although I'm not sure…
Also, don't give a 2.x-only answer to someone using 3.x.
2

I don't know how to … make it so that I don't have to press enter after every word or phrase.

So you want to input a bunch of words on a single line, and then print those words in reverse order?

Well, input always reads a whole line. If you want to split that line into separate words, you call the split method. So:

>>> a = input()
Here are some words
>>> words = a.split()
>>> print(words)
['Here', 'are', 'some', 'words']

Now, if you want to print them in reverse order, you can use reversed, or slice notation:

>>> for word in reversed(words):
...     print(word)
words
some
are
Here

If you wanted to reverse each word, you can use reversed again, together with join, or you could use slice notation:

>>> for word in reversed(words):
...     print(''.join(reversed(word)))
sdrow
emos
era
ereH

What if you really did want to read a bunch of lines in, until you got an empty one?

For that, put them in a list, not a bunch of separate variables:

>>> lines = []
>>> while True:
...     line = input()
...     if not line:
...         break
...     lines.append(line)
Here are some words
And some more

>>> lines
['Here are some words', 'And some more']

You can actually simplify that loop, but it might be a little advanced to understand at this point:

>>> lines = iter(input, '')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.