r/pythontips • • Oct 17 '21

Syntax Python Beginner Mistakes

As a Python trainer, I get to work with pynewbies across the spectrum. It doesn't matter whether they are from college or years into the industry when learning Python. The simplest language on the earth is not that intuitive. Things get even more challenging when they are well versed in a Typed-Object-Oriented-Language

I have compiled some of the common mistakes that beginners make.

https://thelearning.dev/python-beginner-mistakes

52 Upvotes

12 comments sorted by

View all comments

3

u/R3D3-1 Oct 18 '21 edited Oct 18 '21

Coming from Javascript, one of my students was surprised to see no Ternary operators in Python.

But it has.

x = -1 if y < 0 else +1 if y > 0 else 0 // vs
x = y < 0 ? -1 : y > 0 ? +1 : 0;

The only unusual thing about Python's ternary expressions is that the expressions, which are not skipped, are not evaluated left-to-right. An aspect I personally dislike; I'd much prefer if python had opted for left-to-right expressions, e.g.

x = if y < 0 then -1 else if y > 0 then +1 else 0
l2 = [for item in l1 INVENTKEYWORDHERE f(item) ]

More verbose, but it would preserve consistency between control flow statements and the corresponding relations. Particularly obnoxious is to remember the order of item produced by

l3 = [(it1, it2) for it1 in l1 for it2 in l2]

partly due to flipping back and forth the ordering.

Write a function called middle that takes a list returns a new list that contains all but the first and last elements

The given examples actually even fail the specification; The first probably has a typo (it should probably be l1 in the argument list), otherwise it would have a name error, but even then both examples modify the existing list by side-effect.

An indexed tuple or list makes the code hard to read. Always unwrap it into proper variable names and use them.

Missed opportunity to write it as

for shape_name, length in shape_with_length:
    area(shape_name,length)