Key Takeaways
- A variable is a named location reserved to store values in the memory. A variable is created or initialized automatically when you assign a value to it for the first time. (2.1.4.1)
- Each variable must have a unique name - an identifier. A legal identifier name must be a non-empty sequence of characters, must begin with the underscore(_), or a letter, and it cannot be a Python keyword. The first character may be followed by underscores, letters, and digits,. Identifiers in Python are case-sensitive. (2.1.4.1)
- Python is a dynamically-typed language, which means you don't need to delcare variables in it. (2.1.4.3) To assign values to variables, you can use a simple assignment operator in the form of the equal (=) sign, i.e., var = 1
- You ca also use compound assignment operators (shortcut operators) to modify values assigned to variables, e.g., var += 1, or var /= 5 * 2. (2.1.4.8.)
- You can assign new values to already existing variables using the assignment operator or one of the compound operators, e.g.: (2.1.4.5)
var = 2
print(var)
var = 3
print(var)
var += 1
print(var)
-
You can combine text and variables using the + operator, and use the print() function to output strings and variables, e.g.: (2.1.4.4)
var = "007"
print("Agent " + var)
Exercise 1
What is the output of the following snippet?
var = 2
var = 3
print(var)
3
Exercise 2
Which of the following variable names are illegal in Python?
my_var
m
101 - incorrect (starts with a digit)
averylongvariablename
m101
m 101 - incorrect (contains a space)
Del
del - Incorrect (is a keyword)
Exercise 3
What is the output of the following snippet?
a = '1'
b = "1"
print(a + b)
11 it prints them next to each other does not add them.
Exercise 4
What is the output of the following snippet?
a = 6
b = 3
a /= 2 * b
print(a)
1.0
2 * b = 6
a = 6 → 6 / 6 = 1.0