Variables and Value Assignments

Computers can not only compute numbers, but they can also remember a lot of information. Variables are the computer's agents to store this information. They act like containers that can hold values including floats, integers, strings, and other types of data.

Simply put, a variable is a name that refers to a value.

To create a variable, type and run the following code:

x = 10
print(x)

Console result:

10

The first line creates a new variable, x, and assigns it to the value 10. x is the variable name and does not require quotation marks because it is not a string. When we input it to print(), the console shows 10.

Assignment

Giving a variable a value is called assigning, which is done in an assignment statement.

You can create a new variable and assign it to any value like this:

variable_name = value

The variable is on the left side of the equal sign, which indicates to the computer that you are creating a variable. On the right is the value you want the variable to be assigned to, such as a number or a string.

Let's assign a string value "Bob" to a variable called name, a number value 88 to variable age:

name = "Bob"
age = 88
print(name, 'is ', age)

Console result:

Bob is 88

About variable names/identifiers

Identifiers are names given to identify a variable, function, class, etc. Variable names follow the rules of identifiers:

  • They can include letters, digits(0-9) and underscore _**
  • Cannot start with a number
  • They are case sensitive
  • Cannot be the same as any Python keywords

Examples of valid identifier names:

cup_of_tea
_funnyStuff
a3

As we continue the lesson, you'll see Python has many other types of data besides strings and numbers. We can assign them to variables in the same way.

CodeCraft Visuals

Let's use CodeCraft to demo some value assignments:

# variable declaration and simple value assignments
a = 10
b = 4

# build columns of height a(dirt:4), height b(cobblestone:2)
column_m(1, -20, a, 2)      # box_blue, height 10
column_m(3, -20, b, 10)     # box_orange, height 4

# use expression to assign values, 
c = 2 + 3
column_m(5, -20, c, 6)      # box_green, height 5

# assign sum of (a+b+c) to variable 'total'
total = a + b + c
column_m(7, -20, total, 13) # box_red, height total=10+4+2+3=19

# multiple assignments
m, n, l = 2, 4, 6
block_m(10, m, -20, 17)     # brick at y=2
block_m(10, n, -20, 18)     # cobblestone at y=4
block_m(10, l, -20, 19)     # diamond at y=6

# a series of assignments
c = 3
d = c
c = 6

# display the results as columns with height of c and d.
column_m(16, -20, c, 78)  # white column height c (3 or 6: correct: 6)

column_m(18, -20, d, 1)   # black column height d (3 or 6: correct: 3)

results matching ""

    No results matching ""