Python Crash Course Part 1

Adapted by Volodymyr Kuleshov and Isaac Caswell from the CS231n Python tutorial by Justin Johnson (http://cs231n.github.io/python-numpy-tutorial/).

Update to Python 3 by Long Nguyen

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

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

PRESS SHIFT-ENTER TO RUN A CELL!

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

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 [20]:
str1 = 'hello'   
str2 = "world"   
str3 = '''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 a bunch of 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