Variables¶
definition
Namespace
Variable types
Programming With Python¶
Programming: a way to ask computer to store values (variables), and do things with them (operations).`
# This is a comment. You can write a comment by using a `#`
my_variable = 12
my_other_variable = 13 # Comments can be 'inline', like this one
Defining Variables¶
name = value
.
my_var = 1 # `my_var` is a variable
# This defines another variable
other_var = 'variables are cool'
# once you create a variable it's stored in your namespace
other_var
'variables are cool'
Code Variables != Math Variables¶
In mathematics: =
refers to equality (as a statement of truth).
In coding: =
refers to assignment.
Math: What is x?
\(y = 10x + 2\)
Code: What is x?
x = x + 1
Clicker Question #3¶
After executing the following code, what will be the value of my_var
?
my_var = 2
my_var = my_var + 1
print(my_var)
3
A) 2
B) 3
C) “my_var + 1”
D) This code will fail
Clicker Question #4¶
After executing the following code, what will be the value of diff_var
?
diff_var = my_variabel - my_var
print(diff_var)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-16-bb09d72de1d8> in <module>()
----> 1 diff_var = my_variabel - my_var
2
3 print(diff_var)
NameError: name 'my_variabel' is not defined
A) 4
B) 9
C) “my_variable - my_var”
D) This code will fail
Assignment Notes¶
In programming
=
means assignmentThere can be more than one assignment in a single line
Anything to the right of the
=
is evaluated before assignmentThis process proceeds from right to left
Declaring Variables Cheat Sheet¶
Names are always on the left of the
=
, values are always on the rightNames are case sensitive
Variables must start with letters (or underscores)
After that, they can include numbers
They cannot include special characters (like &, *, #, etc)
Python doesn’t care what you name your variables
Humans do care. Pick names that describe the data / value that they store
Reserved Words¶
There are 33 words that are not allowed to be used for variable assignment in Python 3.6.
False |
None |
True |
and |
as |
assert |
break |
class |
continue |
def |
del |
elif |
else |
except |
finally |
for |
from |
global |
if |
import |
in |
is |
lambda |
nonlocal |
not |
or |
pass |
raise |
return |
try |
while |
with |
yield |
# you will get an error if you try to assign a variable to one of these words
try = 6
File "<ipython-input-17-1c44ba76d8f9>", line 2
try = 6
^
SyntaxError: invalid syntax
Kernels¶
Your kernel also stores your namespace - all the variables and code that you have declared (executed).
It can be useful to clear and re-launch the kernel. You can do this from the ‘kernel’ drop down menu, at the top, optionally also clearing all ouputs. Note that this will erase any variables that are stored in memory.
Namespace¶
whos?
# You can list everything declared in the namespace with '%whos'
%whos
Variable Type Data/Info
-------------------------------------
a str string
diff_var int 9
my_other_variable int 13
my_var int 3
my_variable int 12
other_var str variables are cool
Variable Types¶
# Declare a variable
variable_name = 1
# You can always ask Python 'what type is this variable' using:
type(variable_name)
int
Int¶
my_integer = 1
another_integer = 321
# integers can be signed
yet_another_integer = -4
type(yet_another_integer)
int
Float¶
my_float = 1.0
another_float = -231.45
type(another_float)
float
String¶
my_string = 'words, words, words'
another_string = 'more words'
# Note that strings can be defined with either '' or ""
and_another = "and some more"
print(and_another)
type(and_another)
and some more
str
Quotation Marks¶
About those quotation marks…
my_string = 'This is a single-quoted string.'
my_string
'This is a single-quoted string.'
my_string = "This is a double-quoted string."
my_string
'This is a double-quoted string.'
Note that Python will put single quotes around it, even if you specify double quotes.
A general principle is to pick something and be consistent. In this course, I’ll do my best to only use single quotes.
Aside: What if you want to print a quotation mark?¶
use double quotes outside with apostraphe inside quotes
use an escape
\
(backslash) before charater
# double quotes on outside; single quote inside
my_string = "i wan't to see a quote."
my_string
"i wan't to see a quote."
# backslash to "escape" quotation mark
string_quote = "And she said, \"Please teach me Python!\""
string_quote
'And she said, "Please teach me Python!"'
Boolean¶
my_bool = True
another_bool = False
type(another_bool)
bool
None¶
the_concept_of_nothing = None
type(the_concept_of_nothing)
NoneType
Clicker Question #5¶
After executing the following code, what will the type of var_a
be?
var_a = -17.5
A) String
B) Int
C) Float
D) Boolean
E) None
Clicker Question #6¶
After executing the following code, what will the type of var_b
be?
var_b = '-17.5'
A) String
B) Int
C) Float
D) Boolean
E) None
Clicker Question #7¶
After executing the following code, what will the type of the variable m
be?
n = 1
a = 'm'
m = n
type(m)
int
A) String
B) Int
C) Float
D) Boolean
E) None
Aliases¶
# Make a variable, and an alias
a = 1
b = a
print(b)
1
Here, the value 1 is assigned to the variable a
.
We then make an alias of a
and store that in the variable b
.
Now, the same value (1) is stored in both a
(the original) and b
(the alias).
Reminders¶
Multiple variables can relate to the same value(s)
Mutable vs Immutable¶
The variable types we’ve talked about today are all immutable. This means they cannot be altered after they’re created.
immutable_string = 'COGS18 is the best!'
immutable_string[4]
'1'
# cannot change part of the string after creation
immutable_string[4] = '0'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-41-42af1508f9b7> in <module>()
1 # cannot change part of the string after creation
----> 2 immutable_string[4] = '0'
TypeError: 'str' object does not support item assignment
Python does have mutable types. We’ll talk about these later in the course, and these are where aliasing shines!
Indentation¶
Just a brief word on indentation.
Python does care about whitespace.
You will get an error if Python runs into unanticipated whitespace.
a = 1
b = a
print(b)
File "<ipython-input-43-cf6c464af4da>", line 4
print(b)
^
IndentationError: unexpected indent
There are times when indentation will be required and expected. We’ll discuss these in future lectures.