Misadventures in Learning Python

I’ve been trying to teach myself some Python lately. Knowing a fair bit of Java and C# have definitely left me with a good basis, but I can definitely see the difference in design philosophy even without having much understanding of not-strictly-OOP programming.

Here’s a simple example. To get the second-to-last item in an array in Python, you can use the index -2, like so:

>>>>arr=[5,4,3,2,1]
>>>>print (arr[-2])
2

But to do something like that in say, C#, you have to explicitly subtract 2 from the count of elements in the array:

int[] array = new int[] { 1, 3, 5, 7, 9 };
int item = array[items.Count-2];

This is a very simple example, but from my short time with it I can see that Python has a lot of “shortcuts” like this. I say “shortcuts” but it’s probably only a shortcut to me because I’m used to those other languages. How I (initially) would go about this in Python is in the same way you would go about this in C#, but with the “shortcut” you can make your code a lot shorter and possibly more readable.

Would it be accurate to say that this is an example of imperative and declarative programming? In Python, you can declare that you want the element of the array that’s second to last, while in C#, you have to describe how you want to get there.

Through learning Python, I have also realized that I may have gotten in the habit of overthinking problems in general. I guess recognizing problems is just the kind of thing that comes with having lots of programming experience.

Here’s an example of that. This is a simple problem from check.io. All I want is a function that checks if every letter in a string is uppercase. This is how I went about that initially:

def is_all_upper(text: str) -> bool:
    for c in text:
        if c.islower():
            return False
        else:
            continue
    return True

This iterates through the string and returns False if it finds a lowercase letter. However, there’s a much simpler way to do this. check.io is nice because it lets you see others’ solutions once you’ve completed the problem, and I feel like I’ve been learning some new things this way.

def is_all_upper(text: str) -> bool:
    return text.upper() == text 

Of course! Just compare a capitalized version of the string to the string… if nothing changed it’ll return True. That makes a lot more sense than iterating through the string. This solution is definitely doable in C#, too.

Although, I guess whether it’s faster or not depends how text.upper() is implemented, as that may be iterating through the string and looking for lowercase letters as well, to capitalize them.

I dunno. I feel like I have a lot to learn (and possibly un-learn), but I’m happy to expand my skills.