James Y.
James Y.

Reputation: 17

Is there a better way to write my python code

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)

Upvotes: 0

Views: 55

Answers (2)

abarnert
abarnert

Reputation: 365717

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, '')

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117866

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'

Upvotes: 2

Related Questions