Being new to python, I'm starting to ask more and more questions. A lot of the time is understanding trying to understand 'complicated' lines of code that seem to do a lot in a single line. This has given me an better appreciations for Python as I build my own knowledge in the subject.
Background:
I've come across of a function that reverses/manipulates numbers but its difficult to understand what's happening in the IF/Else Statement. I use a few tools to better understand these statements including PythonTutor that gives me a step by step visual of what's happening in code. I've added the code right below this and the screen shots below that are from Python Tutor.
def reverse(x):
a = str(x)
if a[0] == '-':
return int('-'+a[:0:-1])
else:
return int(a[::-1])
print(reverse(-387))
print(reverse(712))
Context:
In this screen shot below, I'm having a hard time understanding what's happening in [:0:-1]
. I understand that if there's a negative in the integer, then continue w/ this statement but why would it be starting at the :0
in this statement? Aren't we trying to take the last int which is -1
and put it to the beginning?
My question is shouldn't it be [:-1:0]
since we want to capture the last int and place it first?
I have the same type of question, which is confusing me, related the Else
portion of the IF statement (below). The portion [::-1]
shows that there's no need to capture the 0
in it, Why is this? Don't we still need the 0
index because we still need to reverse a positive integer, correct?
I guess this can be a 2-part question. Would love to understand this better and if there's a version of this that may not been a IF/Else Statement, that may also help me understand this better.