My random thoughts about various programming languages.
The fact that Python is often considered an easy language makes it appealing to beginners. However, there are some "traps" in the language that may confuse beginners.
def do_something(v):
print('doing something with', v)
def do_something_else(v):
print('doing something else with', v)
# assuming my_list is a list
for item in my_list:
do_something(item)
do_something_else(item)
In this case, do_something_else(item)
should be inside the for loop.
This is an easy mistake to make by simply not indenting a new line enough
times. And, while it's obvious in this example, in an very long for loop
it can be easy to miss.
So what happens here? I asked this once and the general consensus is that
an error will be thrown after the for loop because item
is not defined.
Which is only partially true. item
will not be defined only if there
are no elements in my_list
. When my_list
contains at least one element
then item
will be equal to the last element. Because of this, an error
will not be thrown, an a beginner may not realize they've made this
mistake until much later.
lambdas = [lambda: n for n in range(5)]
for l in lambdas:
print(l())
What happens here? If you write the same logic in most other popular programming languages, you'll get a count from 0 to 4. In Python, it will just print 4
repeatedly.
def append_one(l=[]):
l.append(1)
return l
print(append_one())
print(append_one())
print(append_one())
What does this do? It prints [1]
, [1, 1]
, and [1, 1, 1]
. This is different from JavaScript or Ruby, which re-initializes the default argument each time.