Practice Makes Perfect 7. Reverse


#1

May i know why this code won’t run? It keeps saying that end = ‘’ is an invalid syntax.

def reverse(text):
	for i in range(len(text) - 1, -1, -1):
		print (text[i], end = '')

print reverse("python")

#2

It is because you are trying to set the variable end while printing your text. This is not allowed.

What is end = '' used for ?


#3

if i were to print the following :

 def reverse(text):
	for i in range(len(text) - 1, -1, -1):
		print text[i]

print reverse("python") 

the result will be the following :

n
o
h
t
y
p

I’d like to put all the letters on the same line so that i can get nohtyp. And i’ve read from the forums/watched on youtube that the end function will allow me to do so


#4

This can be done by adding only a ‘,’ at the end of the print.
print text[i],

Previous lessons in this course talk about this. You might want to go back a bit to re-read about it.


#5

Oh yes! I remembered about the comma that i was taught in the previous chapter! Thank you so much!

However, when i type the following code, the word none came up. May I know why is that the case?

def reverse(text):
	for i in range(len(text) - 1, -1, -1):
		print text[i] ,

print reverse("python")

n o h t y p None

And also, the reason why end = ’ ’ didn’t work was because the software assumed that it was a new variable?


#6

I expect it to be the forloop. It looks like its trying to print a number that is not filled. I have no clue tho. I almost never go trough a for loop backwards unless its absolutely necessary. My brain has a hard time when i loop backwards.

I am not sure. Unfortunately i am still to new to python to say this for sure. You could assume it is, till the opposite is proven i guess.


#7

No worries ^__^! Thank you very much for your help! I really appreciate it <3


#8
>>> def reverse(text):
	for i in range(len(text) - 1, -1, -1):
	    print (text[i], end='')

		
>>> reverse("Python")
nohtyP
>>> 

#9

doesn’t run. came over from another forum with the same above code u typed


#10

Not sure I follow. That is copied right from the shell. It ran.

https://repl.it/@mtf/reverse-on-range

It won’t pass the exercise, though. That needs a return value which is the reverse of the input string.