Home Articles Categories Series
Pythonise Just now

Python variables | Learning Python Pt. 3

Assigning, naming and working with variables in Python along with some best practices and naming conventions


Article Posted on by in Python
Julian Nash · 9 months ago in Python

In this part of the "Learning Python" series, we're going to be exploring and learning about variables.

Let's quickly define what a variable is and then move onto some examples.

What is a Python variable

Variables are used to store values and can almost be thought of as a placeholder or reference to another value.

We assign values to variables using the = operator.

You'll often see a variable in Python defined like the following:

language = "Python"

Where language is the variable name and "Python" is the value.

Let's create some variables and assign them different types of values:

Variable assignment

A variable can be assigned with different types of values.

Strings:

my_string = "Python is awesome"

Whole numbers (Integers):

my_age = 30

Floating point values (Floats):

pi = 3.14159265359

Lists:

names = ["Foo", "Bar", "Baz"]

Dictionaries:

user = {"username": "Julian", "password": "sausages22"}

Booleans:

awesome = True

And much more.

We're going to be covering integers, floats, list, dictionaries, booleans & more in future parts of this series.

Reusing variables

Once a variable has been created, we can reuse it throughout our code, for example, let's create a variable with a string value and reuse it 5 times using the print function:

kick_drum = "Boom!"

print(kick_drum)
print(kick_drum)
print(kick_drum)
print(kick_drum)
print(kick_drum)

If we run this code from the terminal, we get the following output:

Boom!
Boom!
Boom!
Boom!
Boom!

Multiple assignment

We can create and assign multiple variables with values all on the same line:

name, gender, age = "Julian", "Male", 30

If we then passed these 3 variables to the print function:

print(name, gender, age)

We get the following output:

Julian Male 30

Variable reassignment

In Python, you can reassign an existing variable with a new value, just as if you were creating a new variable:

quantity = 100
print(quantity)  # prints 100

quantity = 500
print(quantity)  # prints 500

quantity = "One million"
print(quantity)  # prints "One million"

You can also assign a variable with the value of another variable:

name = "Guido"
guido = name

print(guido)  # Prints "Guido"

We can also swicth variable values in place!

foo = "foo"
bar = "bar"

foo, bar = bar, foo

print(foo)  # Prints "bar"
print(bar)  # Prints "foo"

Value unpacking

Although we're yet to cover lists, tuples or sets in this series (3 types of Python data containers), we can unpack values from containers into variables:

awesome = ("Foo", "Bar", "Baz")

foo, bar, baz = awesome

print(foo, bar, baz)  # Prints "Foo Bar Baz"

Variable naming

You can name a variable anything you like as long as you follow these rules.

Variable names must begin with a letter or underscore:

5weets = "Yum"  # Not allowed
sweet5 = "Yum"  # Allowed

Variable names must only contain alpha-numeric characters and underscores (No spaces):

I.e ! " £ $ % ^ & * ( ) _ + = etc.. are not allowed.

music style = "House"  # Not allowed. Contains a space
music-style = "House"  # Not allowed. Contains a -
mucic_$tyle = "House"  # Not allowed. Contains a $

music_style = "House"  # Allowed

Variable names are case sensitive:

language = "Python"
Language = "Python"
LANGUAGE = "Python"

# All 3 are separate variables

Variable names must not use Python reserved keywords (Special reserved Python words like print list, class, def, in, not etc). You'll learn more of these special names as you progress through the series:

class = "Classy!"
del = "Delete!"
print = "Printy!"
not = "No chance!"

# All of these use special reserved keywords and will cause an error

Naming best practices

Use the following bext practices when it comes to naming variables.

Separate words with underscores (AKA Snake case):

somekindofvariable = 5  # Unreadable
some_kind_of_variable = 5  # Readable

Be descriptive (Explicit is better than implicit!):

x = "17ueV0nZfbvIS40-cxqgKw"  # Not descriptive
secret_key = "17ueV0nZfbvIS40-cxqgKw"  # Descriptive

Use all uppercase for constants (Values that should't be changed or reassigned) again with words separated with underscores:

DATABASE_ACCESS_KEY = "o8743yt82yrhrd832"

Naming conventions

Snake case is widely accepted as the "de facto" way to name variables and I'd recommend you make a habit of it!

Having said that, there will be times when you come across the following naming conventions:

Camel case (Uppercase words apart from the first) - often found in older Python code.

thisIsSomeCamelCase

Studly Caps / Pascal Case (Uppercase words) - Used for naming Python classes.

ThisIsSomePascalCase

Studly Caps is the formal convention for naming Python classes (Which we'll cover soon), so be sure to stick to it when we get to creating classes.

A few more variable naming conventions include

Naming a variable with a single leading underscore - Used to hint that the variable is private:

_something_private = 242

Single underscore variables are typically found in Python classes so we won't go into detail on it now.

Naming a variable with a trailing underscore:

class_ = "Class of 99"

Typically used when one of Python's reserved keywords (described above) is the only suitable name for your variable or you have a second variable which needs a very similar name to one already defined.

And finally, a couple of things you should avoid

Capitalizing & underscores combined:

This_Is_Ugly_And_Time_Consuming = "Agreed!"

Using double underscores around variable names (Used for "Dunder" or "Magic" methods which you'll learn about soon):

__something__ = "huh?"

Deleting variables

Variables can be deleted using the del keyword, followed by the variable:

short_lived = 1

del short_lived  # Deletes the short_lived variable

print(short_lived)  # Will cause an error, the variable is gone forever!

You probably won't be deleting variables very often, but it's there if you need it.

Wrapping up

Variables play a key part in Python and almost every other programming language.

Be sure to stick to the naming conventions and follow the best practices, you'll appreciate it later down the line!

As a challange, go ahead and create some variables of your own and use the print function to print the output to your terminal!

Last modified · 14 Mar 2019
Did you find this article useful?
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License
Contents
Loading...