Python Variables, Constants, Style & Comments

Photo by Andrew Neel on Unsplash

Python Variables, Constants, Style & Comments

Table of contents

No heading

No headings in the article.

Hey there, friends! Today, we're going to talk about one of the building blocks of Python: variables. Variables and constants are like little containers that store information. Let's dive in and demystify Python variables together!

What are Variables?

Picture this: you have a box, and you want to put something in it. That box is your variable, and what you put inside is your data. It could be a name, a number, or even a whole paragraph of text!

Python has various data types: strings, integers, floats, and booleans.

What are Constants?

Constant is a data item whose value cannot change during the program’s execution. Thus, as its name implies – the value is constant. It should be UPPERCASE, eg. PI = 3.14159.

Declaring Variables & Constants:

To declare a variable, you simply give it a name and assign a value. Let's see this in action:


name = "James"
age = 25
SPECIES = "Human"

PI = 3.14159 # Constant

In this example, we've created two variables and two constants. name is a string, age is an integer, while SPECIESand PI are constants. You have to keep track of constants though, as you can overwrite them, the best way to track them is to make sre they are uppercase.

Ned Batchelder - Facts and Myths about Python names and values - PyCon 2015

Watch this video above on names and values!

My favorite quotes:

  1. Assignment never copies data.

  2. Python is neither "Call By value" nor "Call By Reference", it's "Call by Assignment"!

  3. There is no way in python where a name can refer to another name. A name can only refer to values.

Dynamic Typing:

In Python, you don't have to declare the data type. Python figures it out for you. This is called dynamic typing, and it makes your life as a programmer easier! Use the type() function to see what the data type was inferred. One last thing you need to worry about, but you do need to keep track of them as Python won’t.

first_name = "Spock" # str = string
type(name)
# <class 'str'>

my_var = 42    # int = integer
type(my_var)   
# <class 'int'>
  • Integer: temp = int(101.2)

  • Float: temp = float(100)

  • Boolean: raining = bool(’True’)

  • String: temp = str(97.2)

Variable Naming Rules:

  • Start with a letter or underscore.

  • Can contain letters, numbers, and underscores.

  • Case-sensitive (e.g., age and Age are different, so be careful).

  • Constants use screaming snake case 🗣️ 🐍, e.g MY_COOL_CONSTANT

  • For more details, see Python’s style rules found in Pep 8 and watch the Pep 8 talk from PyCon 2015:

PEP 8 – Style Guide for Python Code |peps.python.org

Raymond Hettinger - Beyond PEP 8 -- Best practices for beautiful intelligible code - PyCon 2015

Reassigning Variables:

Variables can change their value. It's like giving your box something to store in it.

first_name = "Jim"
print(first_name)  # Output: Jim

first_name = "Spock"
print(first_name)  # Output: Spock

first_name started with "Jim" and then became "Spock." But be careful, as you don’t want to change the data type (if it is set up as a string, DO NOT change it to a different data type or you will give yourself a massive headache 😵‍💫 further along in your program.)

Printing Variables:

To see what's inside your variable, use the print function:

age = 30
print("My age is: ", age)
print(f"My age is: {age}")
print("My age is {}".format(age))

# My age is 30

This will display: My age is: 30

Formatted string literal f is a print() function argument, which is just a shortened form of format() function.

Concatenating & Replicating Variables:

You can also combine variables that contain text by using the + operator and you can replicate it using the * operator:

first_name = "James"
middle_name = "Tiberius"
last_name = "Kirk"
full_name = first_name + " " + middle_name + " " +last_name  # concatenation
print("Full Name:", full_name)
# James Tiberius Kirk

alien = "Tribble"
alien_fed = TRUE
alien_count = alien * 10  # replication
print(alien_count if alien_fed else alien)
# TribbleTribbleTribbleTribbleTribbleTribbleTribbleTribbleTribbleTribble

Type Casting:

You can change the type by using functions like int(), float(), and str() to change the data type. If you try to add the string 2 to an integer 2 you will get an error, but if you temporarily change its type, you can add it to the number successfully.

num_two = "2"
type(num_two)
# <class 'str'>

num_two + 3
# Traceback (most recent call last):
#  File "<stdin>", line 1, in <module>
# TypeError: can only concatenate str (not "int") to str

int(num_two) + 2
# 4

Try the same thing with the float(), and str() functions.

Comments & Docstrings

Use hashtag #.

# This is a comment

""" This is a 
docstring
"""

def least_difference(a, b, c):
    """Return the smallest difference between any two numbers
    among a, b and c.

    >>> least_difference(1, 5, -5)
    4
    """
    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(a - c)
    return min(diff1, diff2, diff3)

help(least_difference)  # call the help() function from Python on the method you created, and it will output the docstring

Help on function least_difference in module __main__:

least_difference(a, b, c)
    Return the smallest difference between any two numbers
    among a, b and c.

    >>> least_difference(1, 5, -5)
    4

You can use a docstring, but technically this is used to provide documentation of functions, classes and modules. The content they contain will show up as a preview when you hover on the function, class or module you add them.

They begin and end with three quotes """ .

# Factoring an expression involves taking out the greatest common factor/ rewriting a sum of terms as a product. Can use this to solve quadratic equations, it will give you the 2 parts of the equation and you solve for x by setting the equations is equal to 0 separately
def factor_equation(symbo_list, expr):
    """
    factor_equation(symbol_list, expr)

    Returns equation factored. 
    >> factor_equation('x, y', 'x**2 + 2*x*y + y**2') 
    (x + y)**2
    """  

    if len(symbol_list) == 2:
        x, y = symbols(symbol_list)
    elif len(symbol_list) == 3:
        x, y, z = symbols(symbol_list)
    else:
        x = symbols(symbol_list)

    return factor(expr)

It’s best to stick with hashtag for real comments.

There are some important things to remember about comments and docstrings:

  1. Docstrings are string literals, so the interpreter can “see” them, while comments are completely ignored by it.

  2. Docstrings are used for automatic documentation generation.

  3. Docstrings are generally only docstrings when they appear at the top of the module, function, class or method they define, whereas comments can live anywhere.

Conclusion:

And there you have it! Variables and constants are like the Lego blocks of Python. They hold your data, and you can play around with them however you like. Practice, experiment, and most importantly, make up some examples for your own notes. 🚀🐍

Buy Me A Coffee