In this article, we discuss six tips for beginners just getting started with Python, including list comprehension, *args and **kwargs, lambda …
Python is one of the easiest programming languages to learn. The syntax is close to English. Beginners generally encounter only a few surprises, such as forced indentation and the use of self
in methods.
At some point, everyone starts reading, copying, and editing other people’s code. That’s where the confusion starts.
I’ll explain five Python concepts that will help beginners to modify code written by other authors. These tips were compiled by observing problems novice Python developers encountered in workshop-style training as well as analyzing online discussions that took place in a free and open development communityfocused on the usage of APIs, image processing, and metadata (text) processing for the RICOH THETA camera. The typical person has intermediate programming experience with Java, C, JavaScript, or bash, but is still a Python novice.
They can write their own Python code to get a job done, but have problems reading the code contributed by other people.
Here are five things that helped some of these people better understand Python.
If you look at Python modules or even documentation for the module, you’re likely to see *args
and **kwargs
. They look and act vaguely like a pointer in C. They are not. *args
is simply a list of arguments sent to a function.
**kwargs
is a dictionary of keyword arguments.
<strong>*args</strong>
** example:**
def add_it(*args):
for num in args:
print(num)
add_it(3, 4, 5, 6)
Output:
$ python dzone.py
3
4
5
6
<strong>**kwargs</strong>
** example:**
def fish_counter(**kwargs):
print(kwargs)
fish_counter(salmon=10, trout=30, smelt=10, bluegill=52)
Output:
$ python dzone.py
{'bluegill': 52, 'smelt': 10, 'salmon': 10, 'trout': 30}
list compressions are a short way to return a list. In the snippet, the for loop is for number in args
.
The expression that is normally inside the loop is num **2
, which returns the square of the arguments.
def square_it(*args):
return [num **2 for num in args]
print(square_it(3, 4, 5, 6))
Output:
$ python dzone.py
[9, 16, 25, 36]
You can tack on a filter to the end of the list comprehension to filter out inputs. For example, to only square the even numbers, filter it with this:
def square_it(*args):
return [num **2 for num in args if num %2 == 0]
print(square_it(3, 4, 5, 6))
Output:
$ python dzone.py
[16, 36]
The list comprehension does not add any special feature over the for
loop. People use list comprehensions because they are shorter and can make code easier to read once you get accustomed to the syntax. Some people may overuse list comprehensions and make code more difficult to read. Be careful of this, as convoluted a list comprehension with multiple nesting is not best practice.
If you’re just getting started with Python and see a for
loop all in one line, you can search on the Internet for list comprehension and review the syntax of the three components:
Python is wonderful for string manipulation. You’ll probably see at least three techniques to insert variables into strings. Two are clunky. One is cool.
Long ago, you may have inserted variables into a string with code similar to this:
animal = "dogs"
population = 3
city = "Palo Alto"
print("There are " + str(population) + " " + animal + " in " + city + ".")
Output:
$ python dzone.py
There are 3 dogs in Palo Alto.
This is difficult to read and easy to make errors. Even with syntax highlighting, it’s easy to miss a space.
A better method is to use .format()
and make strings like this:
animal = "dogs"
population = 3
city = "Palo Alto"
print("There are {} {} in {}".format(population, animal, city))
$ python dzone.py
There are 3 dogs in Palo Alto
Although .format
is a big improvement over string concatenation, it is still a bit clunky.
First, upgrade to Python 3.6 or 3.7. Now, you can use f strings.
print(f"There are {population} {animal} in {city}")
Output:
$ python3 dzone.py
There are 3 dogs in Palo Alto
Python lambda functions are shortcuts. Although they can be assigned to a variable, similar to a normal function, they are commonly used as an anonymous function using the syntax below.
print((lambda num1, num2: num1 + num2)(4,6))
Output:
$ python3 dzone.py
10
Like most of these Python shortcuts, the lambda function doesn’t usually add new functionality. Though, it can reduce the code complexity once you get used to the syntax.
You’ll likely see a decorator function used with an @decorator_name
above a function.
@time_decorator
def cool_function:
print("doing cool things")
The name of the decorator can be anything. For example, it would work with @panda
. You don’t have to understand how to create your own decorator in order to use it. For example, let’s look at the Django documentation for http decorators.
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET", "POST"])
def my_view(request):
# I can assume now that only GET or POST requests make it this far
# ...
pass
The import
line allows you to use pre-built decorators. In this case, you just need to understand that the @require_http_methods
adds additional features to the function you created called, my_view()
.
As I primarily discuss Python programming with a group of people focused on a specific class of problems, I would love to get additional tips suitable for novice programmers that can help them interact with a wider developer community.
===================================================================
Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter
☞ Complete Python Bootcamp: Go from zero to hero in Python 3
☞ Python and Django Full Stack Web Developer Bootcamp
☞ Python for Time Series Data Analysis
☞ Python Programming For Beginners From Scratch
☞ Beginner’s guide on Python: Learn python from scratch! (New)
☞ Python for Beginners: Complete Python Programming
☞ Django 2.1 & Python | The Ultimate Web Development Bootcamp
☞ Python eCommerce | Build a Django eCommerce Web Application
☞ Python Django Dev To Deployment
#python #web-development