Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

March 21, 2017

Python: Starting Python for the First Time (Windows & Linux)

Python is a programming language that is popular as a first programming language. This "getting started" tutorial is aimed at Windows users, with suggestions for Linux users.

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. 
Install a text editor for programmers (lightweight software), pick one or more: 
  • 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) 
Install more complex IDE software (highly recommended for beginners), pick one or more: 
  • 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. 
Install pip and use it to install Python packages

Open Jupyter Lab and start writing basic Python code

On Windows with Anaconda, open "Anaconda Navigator" 
  • Click "Launch" on the box for "Jypyter Lab" or "Jupyter Notebook".

On Windows with Miniconda, open software "Anaconda Powershell Prompt"
  • Type into the terminal and press [ENTER] button:
    jupyter lab

Jupyter Lab will launch
Whichever method used, the computer will launch Jupyter Lab on a web browser.

Create a new Jupyter notebook file with...
File: New: Notebook

Navigate to the new notebook tab (Untitled.ipynb) and type code into the gray text book. For example:
x = 5
y = 10
x + y 
 
To run the cell (the block of code), either press the play triangle icon or use keyboard shortcut [SHIFT] + [ENTER]

You should see the output of your code and a new cell (gray text box for code):
15

Type and press [SHIFT] + [ENTER]:
z = x*x

Your code will run and you will get a new cell. However, it doesn't look like it ran (no output). Your code assigned a value to variable z, but it did not instruct Python to print the output.

To print the output, try one of these:
z
print(z)

Either of these will print the output (the value) of variable z to your window.

Note that function print() cannot have a space between print and the open parenthesis. The function needs to be attached to the input inside the parentheses.

Try this and output:
print(x+y)
print("Hello world")
z = "Beautiful"
print("Hello",z)


Note that you just replaced the value of variable z so now it has a string value ("Beautiful") instead of a numerical value (x*x or 25). Variable values can be replaced. When writing code, keep track of what assigns values to your variables and when you are rewriting them.

You can also see the data types of your variables, for example:
print(x, type(x))
print(y, type(y))
print(z, type(z))
 
Remember to close every parenthesis that you open, or you will get an error.
'int' = integer
'str' = string (the programming name for "text" data)

There are different type of number datatypes. For example, change y to a number with decimals:
y = y+0.01
print(y, type(y))

'float' = number with decimals

Math expressions with comments after the hashtag (#):
2 + 1 # addition
2 - 1 # subtraction
2*3  # multiplication
18 / 2 # division
2**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


How to write a simple Python program inside a text file, then run it on the Windows terminal

R programming lesson #2: merging pdf files

Use R package "pdftools" to merge separate pdf into one pdf file. You will never need to use sketchy websites or pay for software ...