Install Python and related tools
Install one of these distributions of Python, pick only one:- Just pick ONE of these. Installing multiple will create different versions of Python on your computer and that will cause conflicts later.
- Anaconda
- If drive space isn't an issue (you'll need 5-6 GB), get this. It is the most common distribution used by beginners and advanced users.
- Comes with a common packages for life sciences pre-installed (e.g. pandas, numpy, matplotlib)
- Makes creating different Python environments easy
- Pick this if you are attending an Intro to Python workshop
- Miniconda
- Lighter version of Anaconda. It comes with less pre-installed programs. I like it.
- Won't have "Anaconda Navigator" window, so you will need to control Python environments through the terminal (might be frustrating for beginners)
- Pick this if you already know how to program, have other programming software on your computer, and don't want the full Anaconda installation to create duplicates of Jupyter Lab and other tools.
- Python.org
- If drive space is very limited, download this basic version
- Any additional packages will need to be installed separately. Beware, this requires more steps and is less beginner friendly.
- During installation, select click the box to add whichever Python version to your PATH environment variable. You want this! It allows you to run Python scripts from the terminal later.
- The default text application (e.g. Notepad.exe for Windows) will work because programs are just text files with special file extensions, but text editors specifically for programmers will make your life easier by color-coding the programming language syntax. This helps you notice when you forget a closing parenthesis or add an extra apostrophe.
- Notepad++ (Windows)
- Sublime Text (Windows, Linux, macOS)
- Geany (Linux)
- Jupyter Lab is popular and great for multi-script projects.
- From Windows terminal (cmd.exe):
python -m pip install jupyterlab - From Python terminal:
pip install jupyterlab - Spyder comes bundled with Anaconda and is my favorite IDE for Python. It is less complicated the Jupyter Lab.
- RStudio Desktop now supports Python but I don't recommend it if you are learning Python for the first time. It is useful if you plan to use both R and Python languages together in the future.
- Anaconda and Miniconda will pre-install pip (so skip this step)
- Otherwise: Instructions for Windows/Linux/macOS (Python.org)
Open Jupyter Lab and start writing basic Python code
- Click "Launch" on the box for "Jypyter Lab" or "Jupyter Notebook".
- Type into the terminal and press [ENTER] button:
jupyter lab
File: New: Notebook
x = 5y = 10x + y
15
z = x*x
zprint(z)
print(x+y)print("Hello world")z = "Beautiful"print("Hello",z)
print(x, type(x))print(y, type(y))print(z, type(z))
'str' = string (the programming name for "text" data)
y = y+0.01print(y, type(y))
2 + 1 # addition2 - 1 # subtraction2*3 # multiplication18 / 2 # division2**3 # exponent
Adding comments is very helpful to take notes on your code. Write #comments regularly.
Conditional statements, if else code blocks, and loops
Relational operators:
x = 100
y = 2
x < y # less than
x > y # greater than
x <= y # less than or equal to
x >= y # greater than or equal to
x == y # double equal sign evaluates for equivalency (is x equal to y?)
x != y # is x NOT EQUAL to y?
Create ifelse statements.
x = 15
y = 10
if x > y: #Note the use of the colon to indicate the end of the if statement to be evaluated
print(str(x)+ " is greater than " +str(y)) #Code to run if statement is true
else: #What to run if the conditional statement is not true
print(str(x)+ "is " +str(y)+ "or less")
Note that Python requires correct indentation of lines for ifelse statements. Not all programming languages enforce this, but Python is strict about it.
The colons after the if conditional statement and after else are important to tell Python what to do. Python will evaluate if the conditional statement is true or not, then decide which code block to run.
Create a while loop. It repeatedly runs a loop until the conditional statement is no longer true.
iteration=0
while iteration < 5:
print("Iteration:", iteration)
iteration += 1 #increases variable 'iteration' by 1 each time the while loop is run
Be careful with while loops. If you don't create a way for it to be interrupted, you can manually stop the code with the square stop icon.
Combine conditional statements and decide if either needs to be true, or if both need to be true.
x=2
y=15
a=5
b=6
is_true = x>y or a<b
print(is_true)
is_true = x>y and a<b
print(is_true)
Copying and aliasing comparisons:
a=[2,3,4]b=a #tell computer to use the same value from a for b
print(a is b)
b=[2,3,4] #write object b with values [2,3,4], same values as a but it's a different object
print(a is b)
a==b #compare values of the variables
True
False
True
Lists, dictionaries
Ranges:
for i in range(5):
print(i)
0
1
2
3
4
for i in range(25,30):print(i)
25
26
27
28
29
Pre-defined lists and using list indexes to pull out values:
my_list = [1, True, 3, 'Vegas', 5]
print(my_list[3])
Vegas
Because Python is zero-indexed (lists begin with zero), the list item 3 is actually the 4th item because Python counts 0,1,2,3,4.
Strings can also be lists of characters:
word = "Python"
for letter in word:
print(letter)
p
y
t
h
o
n
Use loops to add values to lists:
Long way:
squares = []
for i in range(5):
squares.append(i**2)
print(squares)
[0, 1, 4, 9, 16]
Concise way:
squares = [i**2 for i in range(5)]
print(squares)
Slice lists (get list subsets):
fruits = ["apple", "banana", "kiwi", "guava", "cherry"]
for fruit in fruits[1:-1]:
print(fruit)
banana
kiwi
guava
The code was told where to start (at index 1, which is the second value since Python starts with 0), and where to end (at index -1, which is the second-to-last spot because Python can go backwards).
Dictionaries store key-value pairs:
student = {
"name": "Jose Soandso",
"age": 20,
"major": "Math"
}
## see the dictionary
print(student)
## pull a specific value
student["age"]
## print in loop
for key, value in student.items():
print(f"{key}: {value}") #f-string formatting
Functions
- Python functions defined
- Python function variables, and setting default values
- Allowing functions to accept unknown number of arguments
- Combining functions with function decorators
How to write a simple Python program inside a text file, then run it on the Windows terminal
- Make a new folder at C:\Python
- Open the program Notepad++
- Type the following and pay attention to parentheses, spaces, and quotation marks:
print("Hello! Good morning!") - Save into C:\Python with the following file name: hello.py
- Keep Notepad++ open. We will use it later.
- Open the "Run" Windows application by either searching for it or simply using [WindowsKey]+R. The Windows key looks like four squiggly boxes arranged as a square. It is usually two keys left of the spacebar.
- In the Run box, Open: cmd, then click OK. This opens a black command box which we will be using to run our Python script.
- To navigate to the folder where our Python script is stored, type the following and press [Enter]:
cd C:\Python - That changed the directory which the command window is using to access and write files (cd = change directory). It is a very useful MS-DOS command.
- Type the following and press [Enter]:
python hello.py - That command runs our simple Python script. You should see a message that says:
Hello! Good morning! - Congratulations, you have run your first Python program!
- Go back to Notepad++ and change the message in between the quotation marks. Save.
- Go back to the cmd window and re-run your program by either re-typing python hello.py or using the up arrow key to search the cmd window memory for what you typed last. Press [Enter].
- Congratulations! You have now edited a program in Python!
Know the differences: Python 2 vs Python 3
print "Hello World!"
print("Hello World!")
python --version
python3 --version
How to make a Windows shortcut to run a Python script (easiest way) - optional!
cd C:\Users\YourName\Dropbox\coding\python\test1\blah\blahpython hello.py
- Open Notepad (or Notepad++ or any simple text editor). Type this:
cd C:\Users\YourName\Dropbox\coding\python\test1\blah\blah
python hello.py
pause - Save that text file as run_hello.bat (or any name you want, just replace the .txt extension with .bat to create a batch file). It doesn't matter where you save this file. You can save it to the desktop.
- Double-click run_hello.bat and you will see a Windows command window open and run those three lines of code in your batch file. Windows will navigate to the directory you selected, run your Python program, and then leave the window open (with pause) so you can see any print output.
- Note: if you make the batch file in the same folder as the Python script, you can skip the change directory (cd) line entirely. You only need two lines in run_hello.bat:
python hello.py
pause
Install Python on Windows Subsystem for Linux (Ubuntu Distribution) - optional
Install prerequisites by typing this into the Ubuntu terminal:
sudo apt-get update
sudo apt-get install libgl1-mesa-glx libegl1-mesasudo apt-get install libxrandr2 libxrandr2 libxss1sudo apt-get install libxcursor1 libxcomposite1 libasound2sudo apt-get install libxi6 libxtst6
cd /mnt/c/Users/YourName/Dropbox
sha256sum Anaconda3-2020.02-Linux-x86_64.sh
Result:
2b9f088b2022edb474915d9f69a803d6449d5fdb4c303041f60ac4aefcc208bb Anaconda3-2020.02-Linux-x86_64.sh
bash Anaconda3-2020.02-Linux-x86_64.sh
source anaconda3/bin/activate
conda info #information about anaconda
conda config --add channels defaults
conda config --add channels bioconda
conda config --add channels conda-forge
How to do basic stuff on the Python console
- Work directory
- import os
- print(os.getcwd()) #get current work directory
- os.chdir('/Documents/User/example') #change directory
- os.listdir() #list files in the current directory
- Find out where Python is installed so you can set the Python interpreter for Spyder (if you're having issues installing packages for Spyder)
- Windows console: py --sys