Basics

Comments

Text written in a program but not run by the computer is called a comment. Python interprets anything after a # as a comment. Comments can:

  • Help other people reading the code understand it faster:

    # This code will calculate the likelihood that it will rain tomorrow
    complicated_rain_calculation_for_tomorrow()
  • Ignore a line of code and see how a program will run without it:

    # useful_value = old_sloppy_code()
    useful_value = new_clean_code()

Print

The print() function is used to output text, numbers, or other printable information to the console.

# first try
print("Hello World!")

Errors

The Python interpreter will report errors present in your code. For most error cases, the interpreter will display the line of code where the error was detected and place a caret character ^ under the portion of the code where the error was detected.

Python SyntaxError

A SyntaxError is reported by the Python interpreter when some portion of the code is incorrect. This can include misspelled keywords, missing or too many brackets or parenthesis, incorrect operators, missing or too many quotation marks, or other conditions.

age = 7 + 5 = 4

File "<stdin>", line 1
SyntaxError: can't assign to operator

Python NameError

A NameError is reported by the Python interpreter when it detects a variable that is unknown. This can occur when a variable is used before it has been assigned a value or if a variable name is spelled differently than the point at which it was defined. The Python interpreter will display the line of code where the NameError was detected and indicate which name it found that was not defined.

misspelled_variable_name

NameError: name 'misspelled_variable_name' is not defined

ZeroDivisionError

A ZeroDivisionError is reported by the Python interpreter when it detects a division operation is being performed and the denominator (bottom number) is 0. In mathematics, dividing a number by zero has no defined value, so Python treats this as an error condition and will report a ZeroDivisionError and display the line of code where the division occurred. This can also happen if a variable is used as the denominator and its value has been set to or changed to 0.

numerator = 100
denominator = 0
bad_results = numerator / denominator

ZeroDivisionError: division by zero

IndexError

Selecting an element that does not exist produces an IndexError.

employees = ['Michael', 'Dwight', 'Jim', 'Pam', 
                'Ryan', 'Andy', 'Robert']
print(employees[8])
# IndexError: list index out of range

Working Directory

import os

# get the current working path
os.getcwd()

# Return a list containing the names of the entries in the directory given by path. 
# The list is in arbitrary order. 
os.listdir(path)

# change path
os.chdir('my_new_path')

Last updated

Was this helpful?