Introduction to Programming

Python has been growing rapidly

Over the last 10 years, it has grown to be one of the most popular programming languages.

It recent outpaced Java and JavaScript in popularity.

What is Python good at?

  • Web and Internet Development
  • Scientific and Numeric
  • Education
  • Desktop GUIs
  • Software Development
  • Business Applications

Web Applications

Google Facebook

Scientific Programming

This Presentation

This presentation was created using tools built in Python.

Where does the name Python come from?

Monty Python's Flying Circus

Overview of Today

  • Motivations and goals for the course
  • Overview of programming
  • Overview for setting up Python
  • Diving into Python

Motivations and Goals

By the end of the course:

  • Start up and use Python
  • Write basic scripts
  • Read documentation and learn more
  • Be able to work through additional material

Install Python

Go to the download link and pick the correct version for your operating system

If you have a "32-bit" operating system, install python-3.6.3.exe

If you have a "64-bit" operating system, install python-3.6.3-amd64.exe

When you install it, make sure to check the option to add Python 3.6 to your PATH.

Add Python Path

Starting Python

  • Code in files and scripts
  • Editor
  • Console
  • Shell

Running the Python console

To start the Python console on Windows, go to Start -> Python 3.6 -> IDLE

Python Terms

This is the Python prompt.

You type the commands you see into it

In [ ]:
 

This is a Python comment. Any line that begins with '#' is a comment.

Comments don't impact your code and are just for reading.

In [1]:
# Comments are notes for yourself about your code

This is an expression which is the basic unit of instruction.

An expression consists of values (like 2) and operators (like +).

Pressing <enter> evaluates the expression.

The result of an expression is a value.

In [2]:
2 + 2
Out[2]:
4

This is an error. If the Python interpreter can't understand

your expressions, or there is another issue, there will be an error.

Python Error

Overview of variables

  • Numbers
  • Strings
  • Boolean
  • None
  • Lists

Variables can be "assigned" with the = operator.

In [3]:
name = "Cass"
occupation = "Programmer"
age = 33

Numbers

  • Integers (... -2, -1, 0, 1, 2, 3 ... 100 ...)
  • Decimal (3.14, 96.6, 0.01)
In [4]:
age = 33
In [5]:
print(age)
33
In [6]:
1 + 1
Out[6]:
2
In [7]:
19 - 8.5
Out[7]:
10.5
In [8]:
12 * 12
Out[8]:
144
In [9]:
# Power operator
2 ** 4
Out[9]:
16
In [10]:
100 / 6
Out[10]:
16.666666666666668
In [11]:
# Fraction discarding the remainder
100 // 6
Out[11]:
16
In [12]:
# "Modulus" or "remainder"
7 % 5
Out[12]:
2
In [13]:
birth_year = 1980

this_year = 2017

age = this_year - birth_year

print(age)
37

Strings

  • Text
  • Names
  • Paragraphs
  • Etc

Construct strings with '' or "".

Strings support operations +, *, and %

In [14]:
name = "Cass"

print("Hello " + name)
Hello Cass

Try with your own name now.

Strings also support "interpolation." You can define a template for your string and then "fill in the pieces."

In [15]:
message = "%s is a %s aged %d"

print(message % (name, occupation, age))
Cass is a Programmer aged 37
In [16]:
message = "{} is a {} age {}"

print(message.format(name, occupation, age))
Cass is a Programmer age 37

You can also multiply a string a number of times.

In [17]:
name * 5
Out[17]:
'CassCassCassCassCass'

Booleans

Conditions of logic. Their values are True and False.

They support operators as well, like or, and, as well as not.

Tricky: Any non-zero variable is treated as True in logical operations.

In [18]:
is_human = True
is_robot = False
In [19]:
is_human or is_robot
Out[19]:
True
In [20]:
is_human and is_robot
Out[20]:
False
In [21]:
not is_robot
Out[21]:
True

None is a special variable, meaning nothing

Typically it means "lack of value"

In [22]:
print(None)
None

Lists hold items in sequence

Lists are useful for holding multiple values where order matters

In [23]:
ages = [33, 13, 49, 65, 1]

Lists have length

In [24]:
len(ages)
Out[24]:
5

List indexing

You can reference items of a list by number, called the index.

0 is the first element while len - 1 is the final element.

In [25]:
ages
Out[25]:
[33, 13, 49, 65, 1]
In [26]:
print(ages[0])
33
In [27]:
print(ages[len(ages) - 1])
1
In [28]:
print(ages[-1])
1

Overview of methods of control

  • if / else- decision & logic
  • for - doing something over and over
  • while
  • break - breaking or continuing for loops
  • continue

(Detour) Significance of whitespace in Python

In Python, indentation with whitespace marks a "block" of code.

The convention is to use 4 spaces for this indent.

In IDLE, pressing <TAB> produces spaces rather than a tab.

Four Spaces

if is used for deciding

if <Boolean>:
____<Expression if True>
else:
____<Expression if not True>
In [29]:
if is_human:
    print("{} is a human".format(name))
else:
    print("{} is a robot".format(name))
Cass is a human
In [30]:
if 1:
    print("This 'if' evaluates to 'True'")
This 'if' evaluates to 'True'
In [31]:
if 0:
    print("This 'if' evaluates to 'False'")
In [32]:
if name:
    print("This 'if' evaluates to 'True'")
This 'if' evaluates to 'True'
In [33]:
if None:
    print("This 'if' evaluates to 'False'")

for loops, doing something over and over

Use the for statement to do things a fixed number of times (typically known ahead of time).

for supports iterating over various structures like lists and dictionaries.

To print something 7 times, use:

In [34]:
for i in range(7):
    print("This will appear 7 times")
This will appear 7 times
This will appear 7 times
This will appear 7 times
This will appear 7 times
This will appear 7 times
This will appear 7 times
This will appear 7 times
In [35]:
for i in range(5):
    print("Counting...{}".format(i))
Counting...0
Counting...1
Counting...2
Counting...3
Counting...4

They're also useful for accumulating things.

Below, += means "add and then set equal to."

str means "convert to string." Because numbers is a string, we can only add strings to other strings. We cannot add a number and a string.

In [36]:
numbers = ''

for i in range(10):
    numbers += str(i)
    
numbers
Out[36]:
'0123456789'

while loops

Use while loops to do something multiple times.

Usually used when you don't know the number ahead of time.

In [37]:
# Add numbers until they are more than 100

total = 0
number = 0

while total < 100:
    number += 1
    total += number
    
print("Adding up to {} produced {}".format(number, total))
Adding up to 14 produced 105

break, continue, pass

In [38]:
for i in range(10):
    print("{} before break".format(i))
    if i > 4:
        # `break` brings us out of a `for` loop prematurely
        break
    print("{} after break".format(i))
0 before break
0 after break
1 before break
1 after break
2 before break
2 after break
3 before break
3 after break
4 before break
4 after break
5 before break
In [39]:
sum_of_evens = 0

for i in range(5):
    print("Testing the number {}".format(i))
    
    # If the number is even
    if i % 2 == 0:
        print("{} is an even number".format(i))
        sum_of_evens += i
    else:
        continue
    
    print("The total is now {}".format(sum_of_evens))
Testing the number 0
0 is an even number
The total is now 0
Testing the number 1
Testing the number 2
2 is an even number
The total is now 2
Testing the number 3
Testing the number 4
4 is an even number
The total is now 6

The pass statement does nothing. It's used for when you need an expression but wish to do nothing.

The following code continues forever.

In [40]:
#while True:
#    pass

If you put code above in your prompt, you can press <ctrl> + C or <ctrl> + Z to cancel it.

In [41]:
for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
            break
    else:
        # loop fell through without finding a factor
        print(n, 'is a prime number')
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

Functions

Functions allow you to define behavior to execute later one.

They're useful for abstracting code.

In [42]:
def say_hello(name):
    print("Hello, {}".format(name))
    
say_hello("Cass")
Hello, Cass
In [43]:
print("Hello, {}".format("Cass"))
print("Hello, {}".format("Morris"))
print("Hello, {}".format("Mariatu"))
print("Hello, {}".format("Mohamed"))
print("Hello, {}".format("Bockarie"))
print("Hello, {}".format("James"))
print("Hello, {}".format("Samuel"))
Hello, Cass
Hello, Morris
Hello, Mariatu
Hello, Mohamed
Hello, Bockarie
Hello, James
Hello, Samuel
In [44]:
def say_hello(name):
    print("Hello, {}".format(name))
    
say_hello("Cass")
say_hello("Morris")
say_hello("Mariatu")
say_hello("Mohamed")
say_hello("Bockarie")
say_hello("James")
say_hello("Samuel")
Hello, Cass
Hello, Morris
Hello, Mariatu
Hello, Mohamed
Hello, Bockarie
Hello, James
Hello, Samuel
In [45]:
def say_hello(name):
    print("Kushe-o, {}".format(name))
    
say_hello("Cass")
say_hello("Morris")
say_hello("Mariatu")
say_hello("Mohamed")
say_hello("Bockarie")
say_hello("James")
say_hello("Samuel")
Kushe-o, Cass
Kushe-o, Morris
Kushe-o, Mariatu
Kushe-o, Mohamed
Kushe-o, Bockarie
Kushe-o, James
Kushe-o, Samuel

Overview of data structures

  • Lists
  • Dictionaries
  • Tuples
  • Sets

Lists

Lists contain sequences of items.

In [46]:
names = ["Morris", "Bockarie", "Mariatu", "Fodi"]

You can add lists.

In [47]:
places = ["Sensi", "NP", "Total", "Raza"]
In [48]:
names + places
Out[48]:
['Morris', 'Bockarie', 'Mariatu', 'Fodi', 'Sensi', 'NP', 'Total', 'Raza']
In [49]:
len(names)
Out[49]:
4
In [50]:
names.append("Cass")
names
Out[50]:
['Morris', 'Bockarie', 'Mariatu', 'Fodi', 'Cass']
In [51]:
languages = ["Python", "Java"]

languages.extend(["Javascript", "HTML"])
languages
Out[51]:
['Python', 'Java', 'Javascript', 'HTML']
In [52]:
for l in languages:
    print("I want to learn {}".format(l))
I want to learn Python
I want to learn Java
I want to learn Javascript
I want to learn HTML

They support "list comprehensions"

In [53]:
numbers = range(10)

[i + 10 for i in numbers]
Out[53]:
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Lists (and other structures) support the in operator.

In [54]:
names
Out[54]:
['Morris', 'Bockarie', 'Mariatu', 'Fodi', 'Cass']
In [55]:
"Morris" in names
Out[55]:
True
In [56]:
if "Morris" in names:
    say_hello("Morris")
Kushe-o, Morris

Dictionaries

Dictionaries allow you to put multiple pieces of information into a single structure.

In [57]:
{"name": "Cass", "age": 33, "occupation": "programmer"}
Out[57]:
{'age': 33, 'name': 'Cass', 'occupation': 'programmer'}
In [58]:
person = _
In [59]:
person['name']
Out[59]:
'Cass'
In [60]:
person['occupation']
Out[60]:
'programmer'

Tuples

Tuples are like "lists of fixed size." You cannot add to them or extend them.

In [61]:
point = (1, 2)
In [62]:
print(point)
(1, 2)

Sets

Sets are groups of items. A set contains no duplicates.

In [65]:
numbers = {1, 2}
In [71]:
numbers.update({10})
numbers
Out[71]:
{1, 2, 10}
In [73]:
numbers.update({10})
numbers.update({1})
numbers
Out[73]:
{1, 2, 10}

Job Interview Exercise

This is an actual job interview exercise, usually the first one in a round of interviews.

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

For printing, use print.

For multiples, use n % m == 0. For instance, since 10 is an even number, then

10 % 2 == 0 evaluates to true.

Caesar Cipher Exercise

Create a version of the "Caesar Cipher".

Caesar Cipher

The code would be a correspondence between plain letters and encoded letters:

Plain:    ABCDEFGHIJKLMNOPQRSTUVWXYZ
Cipher:   XYZABCDEFGHIJKLMNOPQRSTUVW

so that a message encoding would be:

Plaintext:  THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Ciphertext: QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD

The follow cells change the code block prompts so that they look like the standard IDLE prompt.

They need to be slide type "Notes" to work.

In [63]:
%%HTML
<style>
.code_cell  .input_prompt:after {
    content: '>>> ';
}
</style>
In [64]:
%%javascript

$('.code_cell .input_prompt').html("");
$('.output_area .prompt').html("");