Variables

CS 65: Introduction to Computer Science I

Variables

variable: a named unit of computer memory that can store a value

They're kind of like cells in a spreadsheet

Cell with name B4 has the value 42, and we can use that value in other computations by referring to its name.

In Python, we can do something similar.

In [1]:
B4 = 42
B5 = B4+10
In [2]:
print(B4)
print(B5)
42
52

Variable Names

We can give variables any name we want

In [3]:
foo = 42
bar = foo + 10
print(bar)
52

But... you should give them descriptive names for the sake of humans reading the code

In [4]:
num_students = 42
num_adults = 10
total_field_trip_lunches = num_students + num_adults
print(total_field_trip_lunches) 
52

Rules for variable names

Allowed: upper and lowercase letters, numbers, underscores _

Not Allowed: other special characters, spaces

In [5]:
total$ = 42.0
  File "<ipython-input-5-a9f41a7586c7>", line 1
    total$ = 42.0
         ^
SyntaxError: invalid syntax

Can't start with a number

In [6]:
5th_grade_students = 42
  File "<ipython-input-6-36a4d5abbb0c>", line 1
    5th_grade_students = 42
     ^
SyntaxError: invalid syntax

Names a case-sensitive (lower/uppercase matters)

In [7]:
students = 42
print(Students) 
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-18c3e7a0187f> in <module>
      1 students = 42
----> 2 print(Students)

NameError: name 'Students' is not defined

Assignment Statements

Code with a = is called an assignment statement

In [8]:
students = 42

Whatever is on the right side of = will be evaluated and saved to the variable named on the left side.

You can't write it the other way around.

In [10]:
42 = students
  File "<ipython-input-10-e94c5307290e>", line 1
    42 = students
    ^
SyntaxError: cannot assign to literal

Printing text and variables

We've seen printing out text by itself and variables by themselves. What if I want both in the same print statement?

You can pass multiple things to print() using commas between them.

In [11]:
students = 42
print("There are",students,"students who need to eat lunch.")
There are 42 students who need to eat lunch.