Python Basics
Variables & Comments Math Operators Sequence Data Types Strings Lists & Tuples Logical Operators Conditional Statements Loops Functions
Data Wrangling
Pandas Introduction Importing Data Select, Drop & Rename Joining Data Cleaning Data Add Columns
Coming Soon
Machine Learning
Coming Soon
Other Tutorials & Content
Python Data Science Reference Blog

Python Variables & Comments

Python Variables

Python uses variables to store pieces of information or values in memory. A variable name refers to the block of memory that stores this value. You can think of the block of memory as a box that we store something in and the variable name as the box label. Whenever we call the box label we get the contents of the box. This is how variables work in Python and most other general purpose programming languages.

Variables can contain many data types including:

  • Numbers (integers, floats, complex numbers)
  • Boolean values (True/False)
  • Sequence Types (Strings, Lists & Tuples)
  • Dictionaries

Variables are assigned or updated in the following way with the variable name on the left and the information being stored on the right of the equals sign.

variable_number = 32
variable_string = 'today'
boolean = True

When the variable name is referenced (called) the value stored in the variable will be returned.

print (variable_number)
> 32

We can also use the variable name to pass the stored value into other tasks or manipulate other values.

print ('Variable String: ' + variable_string)
print (variable_number + 10)
> Variable String: today
> 42

Variable names must start with a letter or an underscore but can contain numbers and other characters after the first character. The common convention for naming variables in Python is to use either a single word or multiple words joined together by underscores such as:

  • variable
  • variable_name

Python Comments

In our Python scripts and notebooks we will often want to place comments in our scripts. Comments in code are free text that are ignored when the code is run put provide information to ourselves or others reading the code about the purpose for a particular snippet of code.

There are two ways to add comments within Python code. The first is that we can add a hash # at the start of a line and anything that is written after the hash on the same line will be treated as a comment and therefore ignored at run time.

#Hash Comment

The hash comment is useful for writing just a few brief words on your code, however if you require more scope then you can place your comments in between two sets of three quotation marks. Anything that appears after the first set of quotation marks is treated as a comment and remains the case until a second set of quotation marks is reached. This means we are not restricted to placing comments on a single line but can be over as many lines as required.

"""1st Comment Line
2nd Comment Line"""