dimanche 10 octobre 2021

Understanding the manipulation of integers in the given function

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. Screen shots below are from Python Tutor.

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?

enter image description here

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?

enter image description here

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.

Aucun commentaire:

Enregistrer un commentaire