A Python Crash Course

A Python Crash Course

This is a short introduction to python that assumes you are already familiar with another programming language, in particular something that uses a C-like syntax. If you find this is too brief or just want more details, then you might be interested in my post Python Programming: A Self-Learning Guide.

Python is a high-level, object-oriented, interpreted language. We can process python code by either typing commands directly into the interpreter or by using the interpreter to process a file of commands (what I would call an actual program).  Most python tutorials and books will demonstrate python commands by typing them into the interpreter; you will recognize this by the >>> prompt. Much of what I show will be programs that you can copy and then run yourself with the Python interpreter.

Let’s start with some obvious differences between Python and C (or its descendents, like C++ or Java).

  • Python requires that indentation be used for the bodies of functions, conditionals, and loops. In those languages with a C-like syntax, this would be done via curly brackets. This forces the indentation to match the logic.
  • While Python does have object types, you don’t need to declare variable types nor declare variables before their use.
  • Variable names can be re-used with the same or different types; a new object is created.
  • Strings and Booleans are built-in types in Python. The print() function automatically adds a newline. If you don’t want this behavior, then you must suppress it.
  • In Python versions beginning with 3.0, dividing an integer by an integer using a single slash produces a floating-point value. To get an integer result from dividing an integer by an integer you should use two slashes. In C the integer is produced by truncating any part to the right of the decimal value. In Python the result is rounded down to the nearest integer.

Statements

Single line comments begin with #. Multiline comments are wrapped in sets of three single quotes or three double quotes.

C-style format specifiers can be use, although there are newer ways that don’t require that you know the type.

"""
    the type() function allows us to see what type
    Python thinks an object is

    this is particularly helpful when debugging since
    a variable name can be re-used with a new object
    of a different type
"""

a = 14
print( type(a) )  
print("a = %d" % a)
print()   # print a blank line

b = 37
print( type(b) )
print("b = %d" % b, end="")  # suppress the newline
print("\n")                  # print two newlines

c = b/a
print( type(c) )
print( c )
print("%d/%d = %.3f" % (b, a, c) )   # C-style
print("{}/{} = {:.3f}".format(b, a, c))  # one of the new ways
print()   

c = b//a
print( type(c) )
print("{}//{} = {}".format(b, a, c))

print()
d, e = 99, 123
print("d = %d, e = %d" % (d, e))

d, e = e, d
print("d = %d, e = %d" % (d, e))

"""  output
<class 'int'>
a = 14

<class 'int'>
b = 37

<class 'float'>
2.642857142857143
37/14 = 2.643
37/14 = 2.643

<class 'int'>
37//14 = 2

d = 99, e = 123
d = 123, e = 99
"""

Booleans and Logical Operators

a = True
print( type(a) )
print(a)

b = False
print( type(b) )
print(b)

print()
print(not a)

print()
print(a and a)  # only True and True is True
print(a and b)
print(b and b)

print()
print(a or a)   # only need one True among the or'd values
print(a or b)
print(b or b)

"""  output
<class 'bool'>
True
<class 'bool'>
False

False

True
False
False

True
True
False
"""

Conditionals

a = 5
b = 6

if a==5 :
    print("this is true\n")

if a == 100 or b >= 99 :
    print("at least one condition is true\n")
else :
    print("neither condition is true\n")


if a == 1 :
    print("one\n")
elif a == 3 :   # only get here if previous condition false
    print("three\n")
elif a == 5 :   # only get here if previous conditions false
    print("five\n")
else :          # only get here if previous conditions false
    print("something else\n")

if a == 5 :
    print("a is 5", end="")

    if b == 6 :  # only get here is a is 5
        print(" and b is 6")

"""  output
this is true

neither condition is true

five

a is 5 and b is 6
"""

Loops

i = 0

while i < 5 :
    if i%2 == 0 :
        print("%d is even" % i)
    else :
        print("%d is odd" % i)

    i += 1

print()

# the for loop in Python iterates through
#   a set of objects
# it's similar to foreach in some languages
for i in range(0, 10, 3) :
    print("i is {}".format(i) )

"""  output
0 is even
1 is odd
2 is even
3 is odd
4 is even

i is 0
i is 3
i is 6
i is 9
"""

Functions

def f(a, b, c=5) :
    # if c is not passed in, use c = 5

    val1 = 2*a + b - c
    val2 = 3*a + b**2 + c  # b**2 is b squared

    return val1, val2

#### program starts here
x = 4
y = -2
z = 1

v1, v2 = f(x, y)
print("v1 = {}, v2 = {}".format(v1, v2))

v1, v2 = f(x, y, z)
print("v1 = {}, v2 = {}".format(v1, v2))


"""  output
v1 = 1, v2 = 21
v1 = 5, v2 = 17
"""

Lists and Tuples

Lists in Python are similar to what you would call an array in C-style languages. There are some notable differences, however:

  • while indexing begins with 0 for the first element and counts up from there, we can also apply indexing to the end. That is, the last element has index -1, the next to last element has index -2, and so forth.
  • Python lists can contain multiple types, for example, we could have an int followed by a string followed by another list.
  • we can add and remove elements from the list, with all of the memory management handled for us.

sample program #1

# a list is created with square brackets
d = [1, 2.345, "cat", [7, 8]]

# iterate through elements of list
for x in d :
    print("{} has type {}".format(x, type(x)))

print()


size = len(d)  # get number of elements in list

d[0] = 99  # change the first value

i = 0
while i < size :
    print(d[i])
    i = i + 1

print( d[3][0] )
print( d[3][1] )
print()

print( d[-1] )
print( d[-2] )

# a tuple is created with parenthesis
t = (12.34, "cat")

print( t[0] )

""" tuples are immutable, so this would cause an error
t[0] = 66
"""

"""  output
1 has type <class 'int'>
2.345 has type <class 'float'>
cat has type <class 'str'>
[7, 8] has type <class 'list'>

99
2.345
cat
[7, 8]
7
8

[7, 8]
cat
12.34
"""

sample program #2

# we can slice a list, producing a new list
a = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print("a = {}".format(a))

# start slice at index 1, while less
# than index 6, with step sizes of 2
b = a[1 : 6 : 2]
print("b = {}".format(b))

"""
what if we want to copy an entire list?

writing
  c = a
is legal, but c will be an alias for the
same list that a names
"""
c = a.copy()  # one of several ways to copy
print("c = {}".format(c))

"""  output
a = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
b = [4, 6, 8]
c = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
"""

sample program #3

"""
  lists are objects and have many associated methods
"""
x = [1, 2, 3]
print("1: x = {}".format(x))
x.append(99)      # add to end
print("2: x = {}".format(x))
x.insert(1, 456)  # insert at index 1
print("3: x = {}".format(x))
x.pop()           # remove from end
print("4: x = {}".format(x))
x.pop(2)          # remove at index 2
print("5: x = {}".format(x))
x.sort()
print("6: x = {}".format(x))
x.reverse()
print("7: x = {}".format(x))
print()

print(3 in x)   # check if 3 in list
print(75 in x)  # check if 75 in list

"""  output
1: x = [1, 2, 3]
2: x = [1, 2, 3, 99]
3: x = [1, 456, 2, 3, 99]
4: x = [1, 456, 2, 3]
5: x = [1, 456, 3]
6: x = [1, 3, 456]
7: x = [456, 3, 1]

True
False
"""

sample program #4

"""
what if we want to use one list as a
starting point for making another list?

Python supports list comprehensions
"""
# loop version
d = []
for i in a :
    if i%2 == 1 :
        d.append(i)
print("d = {}".format(d))

# list comprehension version
d = [i for i in a if i%2 == 1]  
print("d = {}".format(d))

"""
d = [3, 5, 7, 9, 11]
d = [3, 5, 7, 9, 11]
"""

Strings

# strings are enclosed by single or double quotes
a = 'single quotes'
b = "double quotes"
c = "it's a mixture of quotes"

print("a = %s" % a)
print("b = %s" % b)
print("c = %s" % c)

d = """this string begins on this line
       but extends to this line"""
print("d = %s" % d)

""" output
a = single quotes
b = double quotes
c = it's a mixture of quotes
d = this string begins on this line
       but extends to this line
"""


# we can use relational operators with strings
a = "cat"
b = "car"

if a > b :
    print("{} comes after {}".format(a, b))
elif a < b :
    print("{} comes before {}".format(a, b))
else :
    print("{} and {} have equal values".format(a, b))

# prints "cat comes after car"


# we can concatenate strings using +
s = "this"
s = s + "string"
s = s + "is" + "getting" + "longer"
print(s)  # prints "thisstringisgettinglonger"


a = "bookend"
b = a[ :4]  # when slicing lists or strings, if going all
c = a[4: ]  #   the way to an end can leave out that index

print("a {} without the {} is just a {}".format(a, c, b))
# prints "a bookend without the end is just a book"


# there are many string methods
a = "123,abc,XYZ"
b = a.lower()
c = a.upper()
d = a.split(',')           # tokenize with comma as delimiter
print("a = {}".format(a))  
print("b = {}".format(b))  
print("c = {}".format(c))  
print("d = {}".format(d))  # a list of tokens

""" output
a = 123,abc,XYZ
b = 123,abc,xyz
c = 123,ABC,XYZ
d = ['123', 'abc', 'XYZ']
"""

File Input/Output

""" code below reads  sample.txt
one
two
three
"""

fp = open("sample.txt", "r")

for line in fp :
    print(line)   #  print lines from file

fp.close()

"""  output
# each line ends in a newline and print() also adds a newline
one

two

three
"""


fp = open("sample.txt", "r")
data = fp.readlines()  # store lines from file in a list as strings
fp.close()

fp = open("output.txt", "w")
for line in data :
    fp.write("out: %s" % line)
fp.close()

"""  output.txt
out: one
out: two
out: three
"""

Dictionaries

A dictionary is a built-in data structure in Python that stores information using key/value pairs. They are hash tables, so finding values by key is quick.

#  dictionaries are created using curly braces
#  the syntax is key : value
#  keys must be unique and immutable
d = {"cat" : "Felix",
     123 : "dog",
     "aList" : [1, 2, 3]}

print(d)
print(d[123])
print(d["aList"])

""" output
{'cat': 'Felix', 123: 'dog', 'aList': [1, 2, 3]}
dog
[1, 2, 3]
"""


d["aList"].append(4)
d["aList"].append(5)
d["aList"].append(6)
d["newKey"] = "newValue"   # add key/value pair
d[123] = "elephant"        # change value
del d["cat"]               # delete key/value pair
print(d)

""" output
{123: 'elephant', 'aList': [1, 2, 3, 4, 5, 6], 'newKey': 'newValue'}
"""


print("the keys are {}".format(d.keys()))
print("the values are {}".format(d.values()))

""" output
the keys are dict_keys([123, 'aList', 'newKey'])
the values are dict_values(['elephant', [1, 2, 3, 4, 5, 6], 'newValue'])
"""


for k in d :
    print("key: {}, value: {}".format(k, d[k]))

""" output
key: 123, value: elephant
key: aList, value: [1, 2, 3, 4, 5, 6]
key: newKey, value: newValue
"""

Modules (aka, libraries)

One of the reasons that Python is so popular is that there are a huge number of libraries (modules in Python terminology) available, many of which come with the standard Python installation. Here is a sample of some libraries I have found useful.

import math

print("e^1 = {}".format(math.exp(1)) )
print("log base 2 of {} is {}".format(2048, math.log2(2048)) )
print("sqrt(2) = {}".format(math.sqrt(2)) )
print("sin(pi/4) = {}".format(math.sin(math.pi/4)) )

"""  output
e^1 = 2.718281828459045
log base 2 of 2048 is 11.0
sqrt(2) = 1.4142135623730951
sin(pi/4) = 0.7071067811865475
"""

import csv

fp = open("csvFile.csv", "r")
reader = csv.reader(fp)
    
for line in reader :
    print(line)   # each line is a list of tokens
    
fp.close()

"""  csvFile.csv
1,2,3
4,5,6,7

     program prints
['1', '2', '3']
['4', '5', '6', '7']
"""


import datetime

today = datetime.date.today()
future = datetime.timedelta(days=14)
futureString = "%s" % (today + future)
f = datetime.datetime.strptime(futureString, '%Y-%m-%d')
future = f.strftime('%m/%d/%Y')

d = today.strftime("%m/%d/%y")
print("today is {} or {}".format(today,d) )
print("in 14 days it will be {}".format(future) )

"""  output
today is 2020-08-24 or 08/24/20
in 14 days it will be 09/07/2020
"""


Comments are closed.