Comments, Variables & Assignment#

Comments#

Comments mark instructions or information in the code that will not run as part of the program. Comments are useful for testing, documenting, and describing what your code is doing.

In Python, single line comments begin with a pound # symbol and multi-line comments are marked by three sets of double quotation marks """.

# This is an example of a single line comment in Python

"""
This is an example of a multi-line comment in Python
"""
'\nThis is an example of a multi-line comment in Python\n'

For more on comments in Python:

Variables & Assignment Operators#

In most programming languages, variables work as “containers for storing data values” (W3Schools, Python Variables)

We create a variable by assigning a value to that variable name using an assignment operator.

“An assignment statement sets and/or re-sets the value stored in the storage location(s) denoted by a variable name; in other words, it copies a value into the variable…The assignment operator has two operands. The one to the left of the operator is usually an identifier name for a variable. The one to the right of the operator is a value” (Kenneth Leroy Busbee and Dave Braunschweig, “Assignment” in Programming Fundamentals)

[identifier] [assignment symbol] [value]

In Python, the equals sign = is the assignment symbol. The underlying syntax for creating a variable in Python using an assignment statement:

# general syntax
identifier = value

# simple variable example
x = 7

# composite variable example
y = 5 + 7

Python has a few restrictions and best practices around variable identifiers or names:

1- They have to start with a letter character or an underscore (no symbols or numeric characters)

# example of a valid identifier
x = 7

# example of an invalid identifier
$x = 7

2: Terms that have other meaning or function in Python can’t be used as variable identifiers. For example the name of a built-in function (type) can’t be used as a variable identifier.

Reserved keywords in Python include: and, except, lambda, with, as, finally, nonlocal, while, assert, fale, None, yield, break, for, not, class, from, or, continue, global, pass, def, if, raise, del, import, return, elif, in, True, else, is, try

3: Best practice is any programming language is to use meaningful variable identifiers. Just calling something x or y won’t be particularly helpful to someone else reading or interacting with your code. That said, overly-complex variable identifiers are prone to user error.

We can show the value for a variable using Python’s print() function.

# assignment statement
x = 7

# show variable value
print(x)

We can also show a variable’s data type using the type() function.

# assignment statement
y = "Hello world!"

# show type
print(type(y))

Application#

Q1: In your own words, explain the difference between the print(hello) and print(“hello”) commands.

Additional Resources#

For more background on variables & assignment operators: