Variables & Assignment Operators

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

Example#

# simple variable example
x = 7

# composite variable example
y = 5 + 7

Variable Restrictions#

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.

Examples#

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

# assignment statement
x = 7

# show variable value
print(x)
7

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

# assignment statement
y = "Hello world!"

# show type
type(y)
str

Comprehension Check#

Clipboard icon Variables & Assignment Operators Comprehension Check

Application#

Q1: Create a named variable for each of the following data types.

  • Integer

  • Float

  • String

  • Boolean

Show the value of each variable using print() and check the type of each variable using type().

Answer to this question includes program + comments that document process and explain your code.