Python Crash Course Part 1

Python Crash Course Tutorial for anyone with some experience in programming.

Adapted from Justin's Johnson CS231n's notes.

This Python tutorial is minimal, covering only the absolute basics necessary for the Introduction to Neural Networks course. For an excellent and more comprehensive introduction to Python, especially as it relates to data science, see Ryan Soklaski's Python Like You Mean It.

Introduction

Python is a great general-purpose programming language on its own, but with the help of a few popular libraries (numpy, scipy, matplotlib) it becomes a powerful environment for scientific computing.

This tutorial will serve as a quick crash course both on the Python programming language. We will be using the latest verion of Python, 3.6.

Part I will cover:

  • Basic data types: Numbers, Booleans, Strings
  • Conditionals and Loops

This notebook tutorial will teach Python through examples. You are encouraged to change the code and rerun. Experiment!

Some shortcuts when using Jupyter Notebook:

If a cell is selected, Press ENTER to enter Edit Mode(Green Border Cell)

  • PRESS SHIFT-ENTER TO RUN A CELL!

If a cell is selected, Press ESC to enter Command Mode(Blue Border Cell)

  • create a new cell above the current cell: a
  • create a new cell below the current cell: b
  • delete the current cell: dd
  • change the current cell’s type to “Code”: y
  • change the current cell’s type to “Markdown”: m

Basics of Python

Python is a high-level, dynamically typed programming language. Python has an expressive and readable syntax.

Basic data types

Numbers

There are only three number types in Python: integers, floats and complex numbers.

In [11]:
x = 3
y = 2.5
z = 2 + 4j
print(type(x))
print(type(y))
print(type(z))
<class 'int'>
<class 'float'>
<class 'complex'>
In [12]:
print(4 + 1)   
print(10 - 5)   
print(4 * 2)   
print(3 ** 2)  # exponentiation
print(3 / 2)   # division
print(3 // 2)  # floor division
5
5
8
9
1.5
1
In [14]:
a = 4
b = 5
a += 1
b *= 3
print(a, b)  
  
5 15

Python does not have unary increment (x++) or decrement (x--) operators.

Booleans

Python uses English words for Boolean logic.

In [24]:
t = True
f = False
print(type(t)) 
print(f)
<class 'bool'>
False

Here are the basic logical operations.

In [16]:
print(t and f) 
print(t or f)  
print(not t)   
False
True
False
In [17]:
x = 5

if x % 2 == 0 or x > 0:
    print('x is even or positive')
    print("still in this block")
print("different block")    
x is even or positive
still in this block
different block

Strings

String literals can use single, double or triple quotes.

In [6]:
str1 = 'hello'   
str2 = "world"   
str3 = '''hello, world'''  # or """hello, world!"""
print(str1, len(str2))
print(str3)
hello 5
hello, world
In [23]:
s = str1 + ', ' + str2  
print(s)  
hello, world
In [4]:
formatter = 'Hello {}, did you get the {} tests?'.format('Mike',7)
print(formatter)
Hello Mike, did you get the 7 tests?

String objects have many useful methods; for example:

In [13]:
s = "hello"
print(s.capitalize())  # Capitalize a string; prints "Hello"
print(s.upper())       # Convert a string to uppercase; prints "HELLO"
print(s.replace('l', '(ell)'))  # Replace all instances of one substring with another;
                               # prints "he(ell)(ell)o"
Hello
HELLO
he(ell)(ell)o
In [99]:
print('I am ' + str(16) + ' years old')  # must cast numbers to string(str) 
I am 16 years old
In [14]:
x = "hello, world"
print(x[0]) 
print(x[2]) # With slicing(see below), we can extract substrings. 
h
l

Slicing Strings

A substring can be extracted by creating a slice of the original string.

In [16]:
greeting = "Hi! How are you?"  
greeting
Out[16]:
'Hi! How are you?'
In [17]:
# strings can be indexed [start, stop) 
greeting[0:2]  # notice index starts with 0
Out[17]:
'Hi'
In [9]:
#  +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---
#  | H | i | ! |   | H | o | w |   | a | r | e |   | y | o | u | ? 
#  +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---
#  0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15
# -16 -15 -14 -13 -12 -11 -10 -9  -8  -7  -6  -5  -4  -3  -2  -1
In [18]:
greeting[12:-1] 
Out[18]:
'you'
In [19]:
x = "string"
print(x[1:4]) # substring beginning from 1 to 4(not including)
print(x[:]) # the entire string
print(x[2:]) # from 2 to end

y = 'programming'
print(y[1:7:2]) # from 1 to 7(not including) every other character(by 2)
tri
string
ring
rga

You can find a list of all string methods in the documentation.

Conditionals

In [5]:
var = 100
if var == 100:  
   print("var is 100")
   print(var)
elif var == 150:
   print("var is 150")
   print(var)
elif var == 200:
   print("var is 200")
   print(var)
else:
   print("None of the above.")
   print(var)
var is 100
100
In [3]:
x = 5

if x % 2 == 0 or x >= 0:
    print('x is even or nonnegative')
else:
    print('x is odd and negative')
x is even or positive

Loops

Range

range(stop): from 0 up to but not including stop

range(start, stop): from start up to but not including stop

range(start, stop, step): from start up to but not including stop with stepsize = step.

In [101]:
for i in range(6):
    print(i)
0
1
2
3
4
5
In [29]:
for i in range(2, 5):
    print(i, end=",") # separated by commas
2,3,4,
In [28]:
for i in range(1, 9, 2):
    print(i, end=" ") # separated by spaces. 
1 3 5 7 
In [104]:
count = 0
while count < 5:
    print(count)
    count += 1  # This is the same as count = count + 1
0
1
2
3
4
In [105]:
count = 0
while True:
    print(count)
    count += 1
    if count >= 5:
        break   #break is used to exit a loop
        
0
1
2
3
4

break is used to exit a for loop or a while loop, whereas continue is used to skip the current block, and return to the "for" or "while" statement.

In [20]:
# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
    if x % 2 == 0:
        continue  #continue is used to skip the current block, 
                    #and return to the "for" or "while" statement.
    print(x)
    
1
3
5
7
9

Homework

Do the following problems.

Mike's total on five tests is 384. What is the average of his tests?

Use the quadratic formula to solve $x^2+4x-3=0$. The quadratic formula is

\begin{equation} \frac{-b\pm\sqrt{b^2-4ac}}{2a}. \end{equation}

Your answers should be 0.6457513110645907 and -4.645751311064591.

In [2]:
import math # use math.sqrt()
root1 =
root2 =
print(root1, root2)
0.6457513110645907 -4.645751311064591

Write a for loop that prints out all even numbers between 1 and 24 separated by spaces. Use python's modulo (%) operator

Write a while loop to print out all multiples of 3 between 3 and 30 separated by spaces. Use +=3 for the counter.

Create two string variables and concatenate them. Store the result in a new variable.

In [2]:
# you can use single, double or triple quotes.

Create a string variable and store your favorite funny quote. Print the quote.

Consider the string below. Use string slicing to extract "LOve".

In [3]:
x = "I LOve Python!"

Extract all even-indexed characters from x above. Use slicing. Your answer should be 'ILv yhn'.

Using the variable x above, extract every 3rd character starting with the letter 'L' to the end of the string. Use slicing. Your answer should be: 'Leyo'

Consider the string below. 1) Change all characters to lower case. 2) Remove all spaces.

In [4]:
x = "I LOVE ProGRAMming "

Use string slicing to print the variable x above backwards. No loops!