Mission 1.4 - Variables
Introduction
Variables are a good way to reference and manipulate data in a computer program. They provide a useful way to label primitives so that our programs can be more easily understood by the reader and the programmer. Typically, we name variables in ways that we can easily understand why they are useful. Variables in Python have a specific naming convention. Variables names start with a lowercase letter. If we need to name a variable a name that uses multiple words, we use an underscore to separate the words
​
The following are some examples:
x = 5 which is an example of a variable that holds an integer
y = “Detective” which is an example of a variable that holds a string
Changing variables
To change the value of a variable (what the variable is holding), you can re-assign the variable to a different value.
The following is an example:
num1 = 5
num1 = 500
So we changed x to make it equal to 500 instead of 5. Furthermore, we can also change x to a string if we want to. Here’s how:
message = “Mission accomplished!”
​
Assigning a variable to None
If you are unsure what a variable should be at time of creation, you can set the value of a variable to None. Here’s how:
x = None
Once you know what you want the value to be, you can reassign it.
Swapping Variable Values
A variable can only hold one value at a time. So if you want to switch the values of two variables, you need another variable to temporarily hold one of the values. For example, if we have a variable x = 10 and y = 5, when we try to set x = y, x takes the value of y and becomes x = 5. However we can no longer set y = x, because the previous value of x has been lost. In order to avoid this, you must create a value that temporarily holds the value of x. Here’s an example:
x = 10
y = 5
temp = x
x = y
y = temp
If we print x and y, we will see that x now equals 5 and y now equals 10.
Reserved Keywords
In Python, there are reserved words that a variable cannot be named. These words include False, class, return, None , try, True, break, elif, if, or, and, import. May attention to whether or not the word is capitalized because it makes a difference.
Concatenation
As previously stated, strings can be concatenated by using the addition operator. This can be done with variables storing string values as well. Here’s how:
first = “Hello"
second = “world!”
combined_str = first + second
The value stored in combined_str is “Hello world!”