Learn about Python naming conventions. In this lesson, you’ll see how to choose sensible names for Python objects such as variables, functions, modules and so on. You’ll also see what naming styles are compliant with PEP 8 and which one’s aren’t.
Python Naming Conventions
As you write Python, you need to name quite a few things like variables, functions, and the scripts themselves. It’s important to have a good system to naming so that you can refer to what you want without searching through code all the time. In this video, you’ll learn naming styles that are PEP 8 compliant, as well as some tips on how to choose useful names for things. Right off the bat, you should know to never use an
l or a capital
O or a capital
I as a single-letter name for anything. Here it almost looks like I’m trying to reassign the value of
0 to the value of
00:37 Even though the syntax highlighting in my editor makes this clear that that’s not the case, you can’t assume that somebody else will have the same syntax highlighting or even any syntax highlighting at all. Okay.
Let’s get to some naming styles. For functions, you want to use a lowercase word or words. So something like this is okay. And if you need to use multiple words, go ahead and separate them with an underscore (
_), like so. For variables, follow the same rules, except now you can use single letters if you choose.
02:05 When it comes time to save everything in a module, you’ll go ahead and use your lowercase words separated by an underscore. Make sure you’re using short words to keep things clean in the directory.
Single letter variable names are fine if you’re using them for mathematical functions, because that makes sense. What doesn’t make sense is using them for something like a name, because if I have something like
x = 'John Smith'
03:34 Now if you have to refer to a first name and a last name later on in the script, you’ve got a pretty good idea of where they are. Additionally, you may want to shorten the names of your functions so that you don’t have to type them out all the time. Let’s do something like this.
And all this function is going to do is double. I know that
db() means double, but maybe somebody else doesn’t. So instead of using
db(), maybe you should make this function something like
multiply_by_two(), because that’s what it’s doing. Now if you see later on in the script something that’s like
multiply_by_two(), you’ve got a pretty good idea of what that function is doing.
04:19 The keys when naming things in Python are to follow a style so that you stay organized, and to use meaningful names. Don’t be afraid to type a little more because it may save you quite a few headaches later on. That’s it for now! In the next video, you’ll learn how to lay out your code effectively. Thanks for watching.
Become a Member to join the conversation.