Variables, Operations and Types
What are Variables?
At the heart of every computer program lies variables. They are tools to store data for future use. For example, say you want to store the number of Apple shares you own to perform operations based on this number. Declaring a variable in Python is simple, as shown in the following example:
apple_stock_number = 5
A variable consists of three elements: a name, a value, and a type. In this case, the name is apple_stock_number
, the value is 5, and the type is a number (we will look into types later).
In Python, the convention for naming variables is to use descriptive English words, in all lowercase letters, with underscores substituting any spaces. Adhering to this standard will contribute to maintaining clear and readable code by you and others. If you want to know more about conventions for writing Python, you can have a look at the PEP 8 (https://peps.python.org/pep-0008/), this is the most widely adopted standard.
You can now retrieve the number of APPLE shares you own at any time, for instance:
print(apple_stock_number) # Displays 5
You should see the number 5 displayed, which is indeed the value we assigned earlier. The print() is a function that allows us to display the value of what is inside the parentheses. You have tested this function in the previous session with print("Hello World"), which in this case displayed the text "Hello World".
You should also note that the character # is used to add comments. Anything after the # will not be considered in the program. This can be useful to provide notes to explain what the code does, for example.
A variableâs value is not set in stone, you can change it:
apple_stock_number = 7
Now, the value of apple_stock_count
is 7. You can use print()
to observe the change:
apple_stock_number = 5
print(apple_stock_number) # Displays 5
apple_stock_number = 7
print(apple_stock_number) # Displays 7
In this case, you should see 5 followed by 7 displayed.
However, beware:
print(microsoft_stock_number) # Displays and error
This will cause an error, since the variable microsoft_stock_count
has not been defined.
What are the Different Types?
Earlier, we mentioned that variables have types. In Python, the four primary types are:
- int for integers (e.g., 5 or -5)
- float for floating-point numbers (e.g., 5.91)
- str for strings (e.g., âHello Worldâ)
- bool for Booleans (e.g., True or False)
Here's an example that demonstrates the types:
int_var = -5
float_var = 5.7
str_var = "Hello World"
bool_var = True
print(type(int_var)) # Displays <class 'int'>
print(type(float_var)) # Displays <class 'float'>
print(type(str_var)) # Displays <class 'str'>
print(type(bool_var)) # Displays <class 'bool'>
Here, we have defined four new variables, each of a different type. Indeed, you should see a message displayed for each variable <class ââ>
with the type inside the quotes.
type()
is like print()
, a function that allows you to find out the type of the object that you put inside the parentheses.
We will not go into details here, but know that you can also change the type of a variable in certain cases, for example:
int_var = -5
str_var = str(-5)
print(str_var) # Displays "-5" instead of -5, and str_var will now behave as a string
print(type(str_var)) # Displays <class 'str'>
Having a good understanding of the types of variables that one uses is important. A significant number of errors that occur when building code in Python, and in most programming languages in general, arise because the user tries to perform operations between variable types that are not compatible with each other.
Using Operations in Python
Having explored variables and their types, it is time to put them into action with Pythonâs fundamental arithmetic operations:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
- Modulo (%)
Modulo is slightly less common but invaluable. It returns the remainder after division.
Here are some examples demonstrating these operations:
# Addition
result = 2 + 3
print(result) # displays 5
# Subtraction
result = 10 - 5
print(result) # displays 5
# Multiplication
result = 2 * 3
print(result) # displays 6
# Division
result = 10 / 5
print(result) # displays 2.0 (result of division is a float)
# Modulo
result = 7 % 3
print(result) # displays 1 (7 is 3*2 + 1)
Also, you can use operations with str
variables, but this will yield different behaviours:
word1 = "Hello"
word2 = "World"
result = word1 + word2
print(result) # displays "HelloWorld"
result = word1 + " " + word2
print(result) # displays "Hello World"
print(word1 * 2) # displays "HelloHello"
Understanding operations and variables in Python enables you to perform calculations which can be utilized for various practical applications such as calculating profits, losses, or rates of return.
Practical Exercise
To reinforce what you have learned, let us engage in a practical exercise. It is often more insightful to practice by applying the concepts to realistic scenarios.
Scenario:
John is an investor with Apple stocks. Each Apple stock is currently valued at $135. He bought 20 stocks at $60 each, then acquired an additional 10 at $145 each. He sold 8 stocks at $120 each. Now, John is evaluating the financial merits of selling his remaining stocks and is curious about the potential tax implications.
Tasks:
- Calculate and display the total value of the current Apple stocks in Johnâs portfolio.
- Calculate and display the average purchase price of Johnâs Apple stocks.
- Calculate and display the potential total capital gain if John sells all his Apple stocks now.
- John holds dual citizenship in France and Belgium. In France, the tax rate on capital gains is 30%. In Belgium, capital gains are tax-exempt up to $500, and a 40% tax rate applies beyond this threshold. Calculate and display the taxes John would incur on his capital gains in France and Belgium.
A correction example can be found here: https://github.com/RobotTraders/Python_For_Finance/blob/main/exercise_correction_chapter_1.ipynb