# This is a comment (it is ignored by python)
print('Hello world!') # This is also a comment
L02: Variables, types, operators
Lecture overview
This lecture gives you a quick preview of some fundamental concepts in any programming language: “variables”, “types”, and “operations”.
We’ll write some python code in each notebook cell below, and then we’ll “run” or “execute” that code by hiting “CTL+ENTER” (or “CMD+ENTER” on Mac). You can also use “SHIFT+ENTER”, which will execute the cell and move the cursor to the cell below.
We finish by looking at several other ways in which you can get your computer to execute Python code (this is optional material).
Let’s start with some very simple python code:
Here’s a more complicated example. We’ll spend the next few lectures learning all the fundamentals needed to understand what this code is doing and how it works:
import yfinance
'TSLA','META'], interval='1mo')[['Adj Close']].dropna().plot() yfinance.download([
Variables (and the print function)
In programming, a variable is just a name for something. The “something” is usually referred to as data, and the variable is the name we give to that data. For example, in the code below, we create a new variable called myName, which is just a name for the piece of data “Mihai Ion”:
= "Mihai Ion" myName
Now, every time I use myName in a price of Python code, Python will know that I actually mean “Mihai Ion”. Below, I use the Python “print” function to display the data that myName refers to:
print(myName)
Note that the print function does not display “myName”. If I wanted to do that, I would write:
print("myName")
With the quotation marks, Python does not try to interpret what I mean by “myName”. It just assumes that I want to print that piece of text on the screen. However, without the quotation marks, Python searches in the code that I have previously run, to see if at any point, I created a variable called myName. Since I had already run the myName = “Mihai Ion” line of code, it knows that, any time I use myName in a piece of code, I really mean “Mihai Ion”.
Note that a variable name can not start with a digit:
1myName = "Mihai Ion"
Types
Note that the print function can also print numbers, with or without quotation marks:
print(123)
print("123")
Above, it looks like 123 is the same thing as “123”, but internally, Python treats these as very different types of data. 123 is a number (an integer to be more exact) and “123” is a piece of text (a string to be more exact). Formally, we say that 123 and “123” are of different type. I can check the type of a particular piece of data using the “type” function as below:
print(type(123))
The int above stands for “integer” (whole number)
print(type("123"))
The str above stands for “string” (a sequence of characters).
We can use the same function to see the type of a given variable we have created in a prior piece of code:
print(type(myName))
Two other very important data types are:
- float (floating point number i.e. not whole number)
print(type(12.4))
- bool (boolean value i.e. True or False)
print(type(False))
Note that Python has several other data types that we will introduce later on, as we need them.
Operators
Understanding the difference between data types is important because what we can do with any particular piece of data depends critically on its type.
For example, we can not add a number to a variable of type “str”:
= "1"
a print(a + 23)
But we can add a number to a variable of type “int” (or “float”):
= 1
a print(a + 23)
And we can not append a piece of text at the end of a variable of type “int”:
print(a + "23")
In the above line, python looks for the last time we declared what we mean by a, which is in the line above it (i.e. a = 1).
But we can append a piece of text at the end of a variable of type “str”:
= "1"
a print(a + "23")
Operators are special symbols which tell Python to perform particular tasks.
In the examples above, + is an operator and the variables on which it operates are called operands (e.g. a and “23” in the last example are operands).
The examples show you that the + operator performs different tasks depending on the types of its operands: - addition, when the operands are numeric (e.g. int or float type) - concatenation (joining), when the operands are strings (str type)
The examples also show us that Python gives us an error if we try to supply operands of incompatible types to the + operator (e.g. and int and a str).
In the following three subsections, we cover some of the most commonly used operators in Python. The examples are pretty self explanatory so we only show the code. This is not an exhaustive list of all operators found in Python. We will introduce others as needed.
Mathematical operators
print(1 + 2.3)
print(1 - 2.3)
print(10*2)
print(10/2)
#Exponentiation
print(2**3)
Comparison operators
Checking for equality
We use the == (double equal) operator to check if two values are equal. Note that this is different from the = (i.e. “assignment”) operator, which is used to create variables (see examples above.
print(1==1)
print(1==2)
Checking for inequality
# not equal
print(1 != 2)
# strictly smaller than
print(1 < 2)
# strictly larger than
print(1 > 2)
# smaller or equal
print(1 <= 1)
# larger or equal
print(1 >= 1)
All these operators work on any variables of numeric type you have previously declared.
= 10
a = 20
b print(a != b)
But be careful what you are comparing because these operators also work on variables that are not of numeric type (and the results may surprise you):
= "A"
a = "1"
b print(a > b)
The result of a comparison can be assigned a variable name:
= 10
a = 20
b = a > b
c print(c)
Logical operators
Python interprets 1 as True and 0 as False. We’ll talk more about this when we introduce conditional statements. If you want to read ahead on this topic, take a look here: https://docs.python.org/3/library/stdtypes.html
= True
a = False
b = 1
c = 0 d
#Logical "and"
print(a and b)
print(a and c)
print(c and a)
#Logical "or"
print(a or b)
#Logical "not"
print(not a)
String operators
In Python, a string is represented as a sequence of characters.
# Concatenation (joining)
= 'fin'
a = "525" #note that both single quotes and double quotes can be used
b = a + b
c print(c)
print('fin'+'525')
# Repetition (with the * operator)
= a * 3
d print(d)
# Slicing a single character (with the [] operator)
= a[1] #PYTHON STARTS COUNTING FROM 0 (0 means first, 1 means second, etc)
e print(e)
print('abcd'[-2]) #the - sign means "starting from the back"
# Slicing a range of characters (with the [:] operator)
print('Mihai Ion'[0:5]) #print from the first to the fifth characters of 'Mihai Ion'
print('Mihai Ion'[:5]) #same thing
print('Mihai Ion'[:-2]) #print all but the last 2 characters
# Membership (with "in" operator)
print('s' in 'Mihai')
# Membership (with "not in" operator)
print('s' not in 'Mihai')
String formatting with f-Strings
f-Strings are a relatively new addition to the Python language. They allow you insert the result of an expression inside another string.
#Inserting the value of a variable inside another string
= 'Mihai'
name = 104
age = f'My name is {name}, and I am {age} years old' #the f at the beginning makes this an f-string. Note the {} inside.
s print(s)
#Insert the result of a computation inside another string
print(f"Two plus two equals {2*2}")
We can also specify how the value that we want to insert inside the f-string needs to be formatted:
= 104.123
age print(f'My name is {name}, and I am {age: .2f} years old')
The “.2f” in the code above, tells Python we want “age” to be formatted as a float (hence the f in .2f) with only 2 digits after the decimal point (hence the .2 in .2f).
WARNING
f-strings may execute any piece of Python code you supply inside curly brackets. Never include in an f-string a piece of input you obtain from a third party (say a response someone puts into a form somewhere on your website). If they provide malicious code as their input, you may end up inadvertently running that code on your computer.
For example:
f"{__import__('os').remove('./TEST.txt')}"
Alternative Methods of Running Python code (OPTIONAL)
Using Jupyter Notebook
This is the method used in this course. You have to make sure that the code you want to run is in a “code cell” rather than a “Markdown cell”. If you are not sure, you can convert a cell to a code cell by clicking on it, then pressing “esc” and then “Y” (or using the menu option, usually right below Navigate or Widgets).
How to run it: - Press “Shift + Enter” (at the same time) or “Ctrl + Enter” to run the code in that cell.
Using a REPL
Not very useful when your program is large. It allows you to run code one instruction at a time, which is useful if you have some simple tasks that you want to quickly try out. However, if you want to execute hundreds of commands, executing them one at a time will not only be tedious, but also has the inconvenience that you can not save those commands so you can execute them at a later time.
How to run it: - Open a Anacond Prompt (or a terminal like PowerShell in Windows or Terminal in macOS and Bash in Linux) - Type “python” - Start typying your commands (you execute a command by pressing “Enter” after you type it)
Running scripts in the terminal
Involves writing your code in a text file (script) or multiple text files (saved with a “.py” extension) and then running them from a terminal (e.g. PowerShell in Windows and Bash in Linux or macOS). Many programmers use a text editor like Virtual Studio Code or Sublime Text (or an IDE. see below) to help organize their project, get syntax highlighting and completion, etc.
How to do it: - Write your code in a text file (using a text editor of your choice e.g. Notepad, TextEdit, gedit, SublimeText, VS Code) - Save the file with a “.py” extension (let’s call it “XXX.py” for this example). Note that, if you are using Notepad, when you save the file, you have to select “All Files” under the “Save as type” tab. - Open a Anaconda Prompt or any other terminal - Change directory to the folder where you saved your script, by typing “cd” followed by the path to that folder - Type “python XXX.py” and press “Enter”
Using an IDE
Free, third-party software that integrates all the different parts of the Python programming process: code writing, code execution, data/results visualization, project organization etc. The Spyder IDE is most similar to the interfaces used by SAS, Stata, and Matlab but most of its funtionality is available in VS Code too.
How to do it: - Every IDE will be different, but most of them have a “Run” button that will just run the current script for you (so you’ll have to navigate to your script first). - Some IDEs will have a terminal embedded in them, in which case you can run your script in that terminal (using the python command followed by your script’s path and filename). - Other IDEs, like Spyder, will have something called an “IPython” console embedded in them. In these cases, you can use that console to run scripts as well. Just type %run followed by your script’s path and filename.