Contents

DATA 301

Slide formats:

Projects in DATA 301

  • You will have a choice between doing an individual project vs. a group project

  • Group sizes will be set at 3 (no exceptions)

  • Expectations will be different for individual vs. group projects

  • I will assign groups for those that want to do group projects

    • Time zones, skills/experience will be taken into account

  • The group will be a mix to pair those new to programming, with others

Python Math Expressions

Operation

Syntax

Example

Output

Add

+

5+3

8

Subtract

-

10 - 2

8

Multiply

*

5 * 3

15

Divide

/

8/4

2

Modulus

%

9%4

1

Exponent

**

5 ** 2

25

Expressions - Operator Precedence

Each operator has its own priority similar to their priority in regular math expressions:

  1. Any expression in parentheses is evaluated first starting with the inner most nesting of parentheses.

  2. Exponents

  3. Multiplication and division (*, /, %)

  4. Addition and subtraction (+,-) Recall:BEDMAS Brackets Exponents Division, Multiplication, (modulus), Addition and Subtraction Example: 20 - ((4 + 5) - (3 * (6 - 2))) * 4 = 32

Python Expression Question

 Example 5
What is the value of this expression
                       8∗∗2+12/4∗(3−1)%5
Copy to clipboard

HINT: Modulo is executed after multiplication and division; more on this here.

A) 69 B) 65 C) 36 D) 16 E) 70

Python Expression Question

Answer:
What is the value of this expression
            8∗∗2+12/4∗(3−1)%5
Copy to clipboard

HINT: Modulo is executed after multiplication and division; more on this here.

A) 69 B) 65 C) 36 D) 16 E) 70 I think it’s good practice to be explicit with brackets. I.e., I might have written the above as:

            8**2 + ((12/4)*(3-1))%5
Copy to clipboard

Try it: Python Variables and Expressions

 Example 6
Write a program that prints the result of 35 + 5*10 
Copy to clipboard
Example 7
Write a program that uses at least 3 operators to end up with the value 99.
Copy to clipboard
Example 8
Write a program that has a variable called name with the value of your name and a variable called height storing your height in feet. Print out your name and height using these variables.
Copy to clipboard

Rules for Stings in Python

Strings are sequences of characters that must be surrounded by single or double quotes. Any number of characters is allowed. The minimum number of characters is zero “”, which is called the empty string. Strings can contain most characters except enter, backspace, tab, and backslash. These special characters must be escaped by using the escape character: \

  • Example: new line \n single quote ‘ backslash \ double quote ‘’

Strings

As mentioned previously, we can use triple quotes “”” for a strings that contain single/double quotes and/or line breaks. In addition, double quoted strings can contain single quoted strings and vice versa. Example:

storeName = """Joe's Store
this is anew line

"""


print(storeName)
Copy to clipboard
Joe's Store
this is anew line
Copy to clipboard
name = 'Joseph "Joe" Jones'
storeName = 'Joe\'s Store'
storeName = "Joe's Store" # alternatively height = '''5'9"'''
print("""String that is really long
with multiple lines
     and spaces is perfectly fine""")
     
Copy to clipboard
String that is really long
with multiple lines
     and spaces is perfectly fine
Copy to clipboard

Python String Indexing

Individual characters of a string can be accessed using square brackets ([]); the first character indexed at 0. 􏰀 - Example:

str = "Hello" 
print(str[1]) # e 
print("ABCD"[0]) # A 
print(str[-1]) # o
# Negative values start at end and go backward
    
Copy to clipboard
e
A
o
Copy to clipboard

Read all more about strings here.

 Example 9
How many of the following are valid Python strings?
1. ""
2. ''
3. "a"
4. " "
5. """
6. "Joe\' Smith\""
A) 1 B) 2 C) 4 D) 5 E) 6
Copy to clipboard
    Answer:
How many of the following are valid Python strings?
1. ""
2. ''
3. "a"
4. " "
5. """
6. "Joe\' Smith\""
A) 1 B) 2 C) 4 D) 5 E) 6
Copy to clipboard

Python String Functions and Methods

Suppose: st = “Hello” st2 = “Goodbye”

Operation

Syntax

Example

Output

Length

len()

len(st)

5

Upper case

upper()

st.upper()

HELLO

Lower case

lower()

st.lower()

hello

Convert to a string

str()

str(9)

“9”

Concatenation

+

st1 + st2

HelloGoodbye

Substring

[]

st[0:3] st[1:]

Hel ello

String to int

int()

int(“99”)

99

Dot Notation

  • Like VBA, you will notice that python uses the dot operator to perform methods on objects (read more here).

  • Every constant, variable, or function in Python is actually a object with a type and associated attributes and methods.

  • A method is a function that is attached to an object (read more about this here)

  • Here are some more examples of string methods.

String Operators: Concatenation

The concatenation operator is used to combine two strings into a single string. The notation is a plus sign “+”. 􏰀 - Example:

st1 = "Hello"
st2 = "World!"
num = 5

print(st1 + str(num) + " " + st2)
Copy to clipboard
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-b22669c9e416> in <module>
      3 num = 5
      4 
----> 5 print(st1 + str(num) + " " + st2)

TypeError: 'str' object is not callable
Copy to clipboard
st3 = st1 + st2 # HelloWorld! 
print(st1+st1)
print(st3)
Copy to clipboard
HelloHello
HelloWorld!
Copy to clipboard

String Operators: Concatenation

Note that we must hard code spaces if we want them:

st4 = st1 +" "+ st2 
print(st4)z
Copy to clipboard
Hello World!
Copy to clipboard
Concatenate with numbers and strings
We must convert numbers to strings before concatenation.
Copy to clipboard
num = 5
print(st1+str(num)) 
Copy to clipboard
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-cba2fe5c7a62> in <module>
      1 num = 5
----> 2 print(st1+str(num))

TypeError: 'str' object is not callable
Copy to clipboard

N.B. we can mix types in the print() function, i.e. without concatenation. Notice how print() inserts spaces between inputs:

print(st1,num, 100, "hi there", "byethere")
Copy to clipboard

String Operators: Deleting objects

If you have been following along with me, you will find that the code on the previous slide does not work. This is because str is no longer treated as a function because I assigned “Hello” to this object on slide ??. To delete this object we can type:

del str
Copy to clipboard

Now we are free to use the function str() as desired.

 Example 10
What is the output of this code?
st1 = "Hello"
st2 = "World!"
num = 5
print(st1 + str(num) + " " + st2)
A) Error
B) Hello5World! C) Hello5 World D) Hello 5 World
Copy to clipboard
 Answer:
What is the output of this code?
st1 = "Hello"
st2 = "World!"
num = 5
print(st1 + str(num) + " " + st2)
A) Error
B) Hello5World! C) Hello5 World! D) Hello 5 World!
Copy to clipboard

Substrings (slicing)

The substring function will return a range of characters from a string. The general syntax is st[start:end]

Substring indexing/slicing
􏰀 - The start is inclusive the end is exclusive.
􏰀 - If start is not provided, it defaults to 0.
􏰀 - If end is not provided, it defaults to the end of the string.
 
Copy to clipboard

Example:

st = "Fantastic" 
print(st[1])  # a
print(st[0:6]) # Fantas
print(st[4:]) # astic
print(st[:5]) # Fanta
print(st[-6:-2])# tast
Copy to clipboard
 Example 11
What is the output of this code:
st = "ABCDEFG"
print(st[1] + st[2:4] + st[3:] + st[:4])
A) ABCDCDEFGABCD 
B) ABCDEFGABC
C) BCDDEFGABCDE
D) BCDDEFGABCD 
E) BCDECDEFGABC
Copy to clipboard
 Answer:
What is the output of this code:
st = "ABCDEFG"
print(st[1] + st[2:4] + st[3:] + st[:4])
A) ABCDCDEFGABCD
B) ABCDEFGABC
C) BCDDEFGABCDE 
D) BCDDEFGABCD 
E) BCDECDEFGABC
Copy to clipboard

Split

The split function will divide a string based on a separator. Without any arguments, it splits on whitespace,

st = "Awesome coding! Very good!" 
print(st.split())
Copy to clipboard
otherwise is splits where ever it sees the inputted separator:
Copy to clipboard
print(st.split("!"))
Copy to clipboard

[‘Awesome coding’, ‘ Very good’, ‘’]

Split

This is very useful when we have, for example, comma separated values (csv):

>>> st = 'data,csv,100,50,,25,"use split",99' 
>>> print(st.split(","))
['data', 'csv', '100', '50',
'', '25', '"use split"', '99']
Copy to clipboard

Note that the returned object is a Python list (more on these later).

 Example 12
Assume:
􏰀 - name = "Joe" 
     age = 25
Write a Python program that prints out your name and age stored in variables like this:
Copy to clipboard
Example 13
Assume:
􏰀 - name = "Steve Smith"
Use substring, write a Python program that prints out the first
name and last name of Steve Smith like below. 􏰀
         - First Name: Steve
            Last Name: Smith
Bonus challenge: Recode so that it would work with any name.
Copy to clipboard
stringA = "Use, substring, write, a, Python, program"

stringA_aslist = stringA.split(', ')

stringA_aslist
Copy to clipboard
['Use', 'substring', 'write', 'a', 'Python', 'program']
Copy to clipboard
stringA_aslist[3]
Copy to clipboard
'a'
Copy to clipboard

Print Formatting

print("Hi", "Amy", ", your age is", 21)
print("Hi {}, your age is {}".format("Amy",21)) 
print("Hi {1}, your age is {0}".format(21,"Amy")) print("Hi {name}, your age is {age}".format(age=21, name="Amy"))
Copy to clipboard
  • We can think of {} as placeholder arguments for the inputs given in format

  • By default, these inputs will be added in the string in order (the input0 will appear in the first place holder, input1 in the second place holder, etc.

  • If we want to read input1 before input0, we need to refer to it by its integer index via {1} or by its name if we have provided one {age}

List Overview

  • A list is a collection of data items that are referenced by index. I Lists in Python are similar to arrays in other programming languages

    • A list allows multiple data items to be referenced by one name and retrieved by index.

  • I Python list: alt text

fruits = ['apple', 'banana', 'grapes']

for fr in fruits:
    print("I like {0} and {1}".format(fr,fr+" dessert"))
Copy to clipboard
I like apple and apple dessert
I like banana and banana dessert
I like grapes and grapes dessert
Copy to clipboard
from datetime import datetime 
Copy to clipboard
datetime.now() - import 
Copy to clipboard
datetime.datetime(2020, 10, 7, 16, 17, 15, 661619)
Copy to clipboard
type(datetime.now())
Copy to clipboard
datetime.datetime
Copy to clipboard
import time

time.time()
Copy to clipboard
1602112708.4995809
Copy to clipboard
n = 3

if n<1:
    print("one")
elif n>2:
    print("two")
elif n == 3:
    print("three")
Copy to clipboard
two
Copy to clipboard

Retrieving Items from a list

  • Items are retrieved by index (starting from 0) using square brackets:

data = [100, 200, 300, 'one', 'two', 600]
print(data[0])# 100
print(data[4])# 'two'
print(data[len(data)-1]) # 600
print(data[-1])# 600
print(data[2:4])# [300, 'one']
print(data[6]) # error ? out of range
Copy to clipboard
  • You can create an empty list using:

emptyList = []
Copy to clipboard

List manipulation

  • We can modify a single value by use of indices and the assignment operator =

data = [1,2,3,5] 
data[2] = 7
print(data)
Copy to clipboard
  • We can also modify multiple values at a time in the following way:

data[0:1] = ["one","two"]  
print(data)
Copy to clipboard

Appending to a list

  • I Notice that when we try to add a value to the end of the list, we get an error:

data[5] = 10
Copy to clipboard
  • To add an item to the end of the list, use append().

Appending to a list

  • Notice how append()doesn’t return a new list; rather it modifies the original list.

data = [1,2,3,5] 
data.append(7) 
print(data)
Copy to clipboard
  • I Alternatively we could have used

data = [1,2,3,5]
data = data + [7]
data
Copy to clipboard

List in loops

  • We can iterate over a list in a for loop.

colours = [‘red’, ‘yellow’, ‘green’, ‘blue’] for colour in colours: print(colour)

  • Thefollowingcodeappendsthevaluesinione-by-onetothe empty list j.

i = [1, 2, 3, 5, 8, 13] 
j = []
for l in i:
    j.append(l)
Copy to clipboard

List append vs extend

  • append() adds its argument as a single element (eg. a number, a string or a another list) to the end of an existing list.

x = [1, 2, 3] # len(x) = 3 
x.append([4,5])
x
Copy to clipboard
len(x)
Copy to clipboard
  • Notice how the length of the list increases by one.

  • If we want to add the elements one-by-one to the end of x we could either use a loop as we did in the previous slide of use the extend() function.

List extend

  • extend() iterates over its argument and adds each element to the list thereby extending the list.

  • The length of the list increases by number of elements in it’s argument.

x = [1, 2, 3] # len(x) = 3 
x.extend([4,5])
x # len(x) = 5
Copy to clipboard
  • Alternatively, we could have used

x = [1, 2, 3] # len(x) = 3
x = x + [4,5]
print(x)
Copy to clipboard

List extend vs append example

  • Read more about the difference between the two here

x = [1, 2, 3]
x.append([4, 5]) 
print (x)
Copy to clipboard
x[3]
Copy to clipboard
  • where x[3] returns [4, 5] and x[4] returns an error.

x = [1, 2, 3]
x.extend([4, 5])
print (x)

x[3]    
Copy to clipboard

List Operations

  • If data = [1, 2, 3, 5] and lst = []

Operation

Syntax

Example

Output

Add item

.append(val)

data.append(1)

[1, 2, 3, 5, 1]

Insert item

.insert(idx,val)

data.insert(3,4)

[1, 2, 3, 4, 5]

Remove item

.remove(val)

data.remove(5)

[1, 2, 3]

Update item

list[idx]=val

data[0]=10

[10, 2, 3, 5]

Length of list

len()

len(data)

4

Slice of list

list[x:y]

data[0:3]

[1, 2, 3]

Find index

.index(val)

data.index(5)

3

Sort list

.sort()

data.sort()

[1, 2,3,5]

Add

lst = []

lst.append(1)

[1]

List details

  • It was mentioned already but its worth repeating…

  • For loops that are used to iterate though items in a list:

data = [5,9,-2,9] 
for v in data:
    print(v)
Copy to clipboard

List details

  • Note that this is not restricted to numbers:

data = ["apples", "bananas","oranges"] 
for v in data:
    print(v)
Copy to clipboard
  • prints apples, bananas, oranges (each on a separate line).

  • We could even iterate through characters in a string:

for v in "bananas": 
    print(v)
Copy to clipboard
  • prints b, a, n, a, n, a, s (each letter on a separate line)

List details

  • If we want to iterate through both index and value, we could use the enumerate() function.

data = ['apple', 'banana', 'grapes', 'pear'] 
for c, value in enumerate(data):
        print(c, value)
Copy to clipboard

If we want our index to start at 1 rather than 0, we could specify that as the second argument: enumerate() function.

data = ['apple', 'banana', 'grapes', 'pear']
for c, value in enumerate(data, 1):
      print(c, value)
Copy to clipboard

Advanced: Python List Comprehensions

evenNums100 = [n for n in range(101) if n%2==0]
Copy to clipboard
  • Equivalent to:

evenNums100 = [] 
for n in range(101):
      if n%2==0: 
        evenNums100.append(n)
Copy to clipboard

Advanced: Python List Slicing

  • List slicing allows for using range notation to retrieve only certain elements in the list by index.

  • Syntax:

  • list[start:end:step]

  • Example:

data = list(range(1,11))
print(data) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(data[1:8:2]) # [2, 4, 6, 8] 
print(data[1::3]) # [2, 5, 8]
Copy to clipboard
 Example 12
At what index is item with value 3?
 data = [1, 2, 3, 4, 5]
 data.remove(3) 
 data.insert(1, 3)
 data.append(2) 
 data.sort()
 data = data[1:4]
A) 0 B) 1 C) 2 D) 3E) not there
Copy to clipboard
 Answer:
At what index is item with value 3?
 data = [1, 2, 3, 4, 5] 
 data.remove(3) 
 data.insert(1, 3)
 data.append(2)
 data.sort()
 data = data[1:4]
Copy to clipboard

A) 0 B) 1 C) 2 D) 3E) not there

Try it: Lists

Example 13 (Question 1)
Write a program that puts the numbers from 1 to 10 in a list then prints them by traversing the list.
Copy to clipboard
Example 14 (Question 2)
Write a program that will multiply all elements in a list by 2. Bonus: try doing this using the enumerate() function.
Copy to clipboard
Example 15 (Question 3)
Write a program that reads in a sentence from the user and splits the sentence into words using split(). Print only the words that are more than 3 characters long. At the end print the total num- ber of words.
Copy to clipboard

Lists

  • In the previous example we use the list() function to create our list instead of the square brackets.

  • This constructs a list using the single input. This could be

  • a sequence (eg. string, tuples) or

  • a collection (set, dictionary) or

  • a iterator object (like the objects iterated over in our for loops)

  • If no parameters are passed, it creates an empty list.

Tuples

  • A tuple is a collection which is ordered and unchangeable. To create tuples we use round brackets ().

thistuple = ("apple", "banana", "cherry") 
print(thistuple)
Copy to clipboard
  • Elements in a tuple are referenced the same way as lists:

print(thistuple) 
thistuple[1]
Copy to clipboard
  • Tuples are useful for storing some related information that belong together.

  • Unlike list, once a tuple is created, values can not be changed.

thistuple[1]="pineapple"
Copy to clipboard
  • Notice that tuples are also iterable, meaning we can traverse through all the values. eg,

for i in thistuple:
        print(i)
# The above prints:
Copy to clipboard

Python Sets

  • A set (like a mathematical set) is a collection which is unordered and unindexed.

  • Setsarewrittenwithcurlybrackets{}.

# N.B they do not carry duplicates
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
Copy to clipboard
  • Since sets are unordered, the items will appear in a random order and elements cannot be reference by index.

  • Againwecaniteratethougheachitemusingaforloop.

  • Read more about these here.

Python Dictionary

  • A dictionary is a collection which is unordered, changeable and indexed. We create them with curly brackets and specify their keys and values.

thisdict = {
    "key1":"value1",
    "key2":"value2",
    "key3":"value3",
}
print(thisdict)
Copy to clipboard
  • N.B Keys should be unique. If you create different values with the same key, Python will just overwrite the value of the duplicate keys.

nono = {'key1':'this', 'key1':'that'} 
nono
Copy to clipboard

Python Dictionary

  • We can now reference elements by a given name (i.e key) rather than the standard integers index.

thisdict['key1']
Copy to clipboard
  • Referencing by index won’t work (remember these are unordered)

thisdict[0]
Copy to clipboard
  • Don’t get confused at try to do indexing using the values rather than the keys! For instance the following would produce an error:

thisdict['value1']
Copy to clipboard

Python Dictionary

  • If we wanted to, we could always use integers for the keys (in that case we don’t need quotes around them when indexing using square brackets).

dict = {1:'one', 2:'two', 3:'three'}
print(dict[1]) # one
print(dict['one']) # error - key not found
if 2 in dict:# check if key exists 
print(dict[2])# 'two'
Copy to clipboard
  • We can add/delete and view keys/values using the following:

dict[4] = 'four' # Add 4:'four'
del dict[1] # Remove key 1
dict.keys() # Returns keys
dict.values()# Returns values
Copy to clipboard

Python Dictionary

  • Iterating over a dictionary will return the keys

dict = {'Martha':4, 'Janet':17, 'Peter':10}
dict['Anna'] = 20 
for i in dict:
      print(i)
Copy to clipboard
  • To get the values use:

for i in dict: 
      print(dict[i]) # or 
for i in dict.values(): 
      print(i)
Copy to clipboard

Python Dictionary

  • To access both keys and values use:

# option 1:
# i = key, dict[i] = value 
for i in dict:
    print("key = ", i, "value = ", dict[i])
Copy to clipboard
# option 2:
for key, val in dict.items():
    print("key = ", key, "values =", val)
Copy to clipboard

Summary of Python Structures

  • Lists can be altered and hold different data types:

lectures = [1,2,['excelI','excelII'],'CommandLine']
 # can delete individual items
del lectures[3]
# reassign values
lectures[1] = 'Introduction' 
print(type(lectures[0])) # <class 'int'> 
print(type(lectures[1])) # <class 'str'> 
print(type(lectures[2])) # <class 'list'>
Copy to clipboard
<class 'int'>
<class 'str'>
<class 'list'>
Copy to clipboard
  • Tuples are immutable (we can’t change the values):

topics= (1,2,['excel1','excel2'],'CommandLine')
del topics[3]
Copy to clipboard
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-1998bcebb9c7> in <module>
      1 topics= (1,2,['excel1','excel2'],'CommandLine')
----> 2 del topics[3]

TypeError: 'tuple' object doesn't support item deletion
Copy to clipboard
type(topics[2])
Copy to clipboard
  • Sets do not hold duplicate values and are unordered.

myset={3,1,2,3,2}
myset
Copy to clipboard
myset[1]
Copy to clipboard
  • Dictionaries hold key-value pairs (just like real life dictionaries hold word-meaning pairs).

wordoftheday = {'persiflage':'light, bantering talk or writing' , 'foment':'to instigate or foster'}
wordoftheday['foment']
Copy to clipboard
wordoftheday[1] # produces an error
Copy to clipboard
Example 16
What value is printed?
data = {'one':1, 'two':2, 'three':3} data['four'] = 4
sum = 0
for k in data.keys():
if len(k) > 3:
sum = sum + data[k]
print(sum)
A) 7 B) 0 C) 10 D) 6 E) error
Copy to clipboard
Answer:
At what index is item with value 3?
data['four'] = 4
sum = 0
for k in data.keys():
if len(k) > 3:
sum = sum + data[k]
print(sum)
Copy to clipboard

A) 7 B) 0 C) 10 D) 6 E) error

Try it: Dictionary

Example 17
Write a program that will use a dictionary to record the frequency of each letter in a sentence. Read a sentence from the user then print out the number of each letter.
Copy to clipboard
  • Code to create the dictionary of letters:

import string
counts = {}
for letter in string.ascii_uppercase:
      counts[letter] = 0 
print(counts)
Copy to clipboard
Example 18
Create the following two variables and write a Python program that prints the following output:
 name = "Joe" age = 25
 
 output
 Name: Joe
 Age: 25
Copy to clipboard
 Example 19
Define the variable:
name = "Steve Smith"
Use substring to write a Python program that prints out the first name and last name of Steve Smith like below.

OUTPUT

First Name: Steve
Last Name: Smith
Copy to clipboard

Python Modules

  • A Python module or library is code written by others for a specific purpose. Whenever coding, make sure to look for modules that are already written for you to make your development faster! Modules are imported using the import command:

                 import <modulename>
Copy to clipboard
  • Useful modules for data analytics:

  • Biopython (bioinformatics),

  • NumPy (scientific computing/linear algebra),

  • scikit-learn (machine learning), pandas (data structures), 􏰀

  • BeautifulSoup (HTML/Web)

Python Date and Time

Python supports date and time data types and functions. To use, import the datetime module using the following:

import datetime
Copy to clipboard

The general syntax to import the module named mymodule is:

import mymodule
Copy to clipboard

You can choose to import only parts from a module, by using the from keyword. For example, if we just want the object person1 from mymodule type:

from mymodule import person1
Copy to clipboard

Read more about this here.

Python Date and Time

We may choose to only import the datetime object from the datetime module (which happens to be the same name) using the following:

from datetime import datetime
Copy to clipboard

The datetime object has a method for formatting date objects into readable strings. Read more here.

Python Date and Time

Methods:

now = datetime.now()
now = datetime.now()
print(now)
Copy to clipboard
current_year = now.year
current_month = now.month
current_day = now.day
print("{}-{}-{} {}:{}:{}".format(now.year, now.month, now.day, now.hour, now.minute, now.second))
print("{}-{}-{} {}:{}:{}".format(now.year, now.month, now.day, now.hour, now.minute, now.second))
Copy to clipboard

Python Clock

  • The time module, is another useful module for handle time-related tasks.

  • The time() function for example, returns the current time in seconds.

  • On Linux machines, this is an integer counting the number of seconds passed since January 1, 1970, 00:00:00 (recall from Lecture 2).

  • This function can be useful when we want to time how long a process takes within our program. See an example on the next slide.

Python Clock

  • Example:

import time
startTime = time.time()
print("Start time:", startTime)
print("How long will this take?")
endTime = time.time()
print("End time:", endTime)
print("Time elapsed:", endTime-startTime) 
Copy to clipboard

Python Input

To read from the keyboard (standard input), use the method input:1 􏰀 - Example: name = input(“What’s your name?”) print(name) age = input(“What’s your age?”) print(age)

Try it: Python Input, Output, and Dates

Example 14
Write a program that reads a name and prints out the name, the length of the name, the first five characters of the name.
Copy to clipboard
Example 15
Print out the current date in YYYY/MM/DD format.
Copy to clipboard

Comparisons

  • A comparison operator compares two values. 􏰀 􏰀

  • Examples:

N=10  
5 < 10
N > 5 # N is a variable. Answer depends on N.
Copy to clipboard

Comparison Operators in Python:

Syntax

Description

>

Greater than

>=

Greater than or equal

<

Less than

<=

Less than or equal

==

Equal (Note: Not “=” which is used for assignment!)

!=

Not equal

The result of a comparison is a Boolean value which is either True or False.

Conditions with and, or, not A condition is an expression that is either True or False and may contain one or more comparisons. Conditions may be combined using: and, or, not. Order of evaluation: not, and, or. May change order with parentheses.

True if:

Syntax

Examples

Outpu

both are true

and

True and True False and True

True False

either or both are T

or

True or True False or True False or False

True True False

false

not

not True not False

False True

Condition Examples

n=5
v=8
print(n > 5) #False
print(n == v) #False
print(n != v) # True
print((n == v) and (n+4>v)) # False
print((n == v) or (n+4>v)) # True
print((n+1) == (v-2) or (not v>4)) # True print((n+1) == (v-2) or not v>4) and (n>5)) # False
Copy to clipboard

Order of Operations

Table: The order of operations for logicals. See complete list here

Syntax

Description

()

brackets

**

exponents

* / % MOD

Multiplication, division, modulo

+ -

Addition and subtraction

< <= > >=

Comparisons: less-than and greater-than

== !=

Comparisons: equal and not equal

and

and

or

or

nots always bind to the condition immediate next to it

### Tip:
I recommend always using brackets to avoid confusion.
Copy to clipboard
 Example 16
How many of the following conditions are TRUE? 
1. True and False
2. not True or not False
3. 3 + 2 == 5 or 5 > 3 and 4 != 4
4. (1 < 2 or 3 > 5) and (2 == 2 and 4 != 5)
5. not (True or False) or True and (not False)

A) 1 B) 2 C) 3 D) 4 E) 5
Copy to clipboard

Python Flow Control

Decisions

  • Decisions are used in programming to specify one or more conditions to be tested, along with statement(s) to execute if the condition is true.

  • Acondit ion is an expression that is either True or False.

  • These conditions control the flow of you program and different statements will be carried out depending on the outcome of these conditions.

  • To build conditional statements we need to be able to write Boolean expressions.

Boolean Expressions

  • A Boolean expression is an expression that evaluates to a Boolean value 1 .

  • A Boolean value is either True or False. Boolean values Boolean values are not strings. The Python type for storing True and False values is called bool.

print(type(True)) 
Copy to clipboard
print(type("True"))
Copy to clipboard
  1. The name comes from George Boole, who first defined an algebraic system of logic in the mid 19th century

Boolean Expressions

We can create Boolean expressions using: Relational operators/Comparisons: used to compare two values

  • Examples:

5 < 10 # returns True 
Copy to clipboard
N > 5  # N is a variable. Answer depends on N.
Copy to clipboard

Logical operators: the logical operators and, or and not are used to combine relational operators.

  • Example:

n=1
(n>5)and(v!=n)
Copy to clipboard
  • The result these expressions are a Boolean value which is either True or False

Comparisons

A condition is a Boolean expression that is either True or False and may contain one or more comparisons.

The comparison operators in Python are summarized below:

Syntax

Description

>

Greater than

>=

Greater than or equal

<

Less than

<=

Less than or equal

==

Equal (Note: Not “=” which is used for assignment!)

!=

Not equal

Conditions with and, or, not

Conditions may be combined using the relational operators and, or, not.

Syntax

Description

Examples

Output

both are true

and

True and True
False and True

True
False

either or both are T

or

True or True
False or True
False or False

True <brTrue
FLase

false

not

not True
not False

False
True

Condition Examples

n=5
v=8
print(n > 5) #False
print(n == v) #False
print(n != v) # True
print((n == v) and (n+4>v)) # False
print((n == v) or (n+4>v)) # True
print((n+1) == (v-2) or (not v>4)) # True print((n+1) == (v-2) or not v>4) and (n>5)) # False
Copy to clipboard

Order of Operations

Table: The order of operations; see complete list here.

()
**
* / % MOD
+ -
< <= > >=
== !=
and
or

brackets
exponents Multiplication, division, modulo
Addition and subtraction
Comparisons: less-than and greater-than
Comparisons: equal and not equal
and
or

Tip:
I recommend always using brackets to avoid confusion.
Copy to clipboard
Example 16
How many of the following conditions are TRUE?
1. True and False
2. not True or not False
3. 3+2==5or5>3and4!=4
4. (1<2or3>5)and(2==2and4!=5)
5. not (True or False) or True and (not False)
A) 1 B) 2 C) 3 D) 4 E) 5
Copy to clipboard
Answer:
How many of the following conditions are TRUE?
1. True and False = True or False
2. not True or not False = (not True) or (not False)
3. 3+2==5or5>3and4!=4
= (5 == 5) or (5 > 3) and (4 != 4) =(5==5)or((5>3)and(4!=4))# and first
4. (1<2or3>5)and(2==2and4!=5) (1 < 2 or 3 > 5) and (2 == 2 and 4 != 5) (1 < 2 or 3 > 5) and (2 == 2 and 4 != 5)
5. not (True or False) or True and (not False) not (True or False) or True and (not False) not (True or False) or True and (not False)
Copy to clipboard

A) 1 B) 2 C) 3 D) 4 E) 5

Decisions

In Python decision syntax:

put an image here

  • Thestatement(s)aftertheifconditionisonlyperformedif the condition (i.e. Boolean expression) returns True.

  • Anystatement(s)followingthe(optional)else:conditionis only performed if the condition is False.

Python syntax
Remember that the indentation and colons are not optional!
Copy to clipboard

Decision Block Syntax

  • Statementslistedafteranif/elif/esleclausearenotonly indented for readability.

  • These indentation is also how Python knows which statements are part of the group of statements to be executed.

  • Statements with the same indentation belong to the same group called a suite.

  • Be consistent with either using tabs or spaces (no mixing)

Tip: one-line if clause
If the suite of an if clause consists of a single line, it may go on the same line as the header statement.
Copy to clipboard
if (n > 100): 
    print("n is large")
Copy to clipboard

Decisions if/elif Syntax

Check out the difference for age = 20:

age = 20
if age > 19:
    print("Not a teenager")
    print("Sorry") 
else:
    print("You're young") 
    print("ID checked")
Copy to clipboard
age = 20
if age > 19:
    print("Not a teenager")
    print("Sorry") 
else:
    print("You're young") 
print("ID checked")
Copy to clipboard

Generic code:

    if (cond1):
          Process 1
          
Copy to clipboard

Example 1:

n=5
if (n < 10):
    n = 10
Copy to clipboard

n is now 10

Example 2:

   n=5
if (n > 10):
     n = 10
Copy to clipboard
  • Generic code:

 if (cond1):
     Process 1
 else:
     Process 2
Copy to clipboard
  • Example 3:

n=5
if (n > 10):
    n = 10 
else:
    n=3 
 ### n is now 3
Copy to clipboard

Decisions if/elif Syntax

If there are more than two choices, use if/elif/else statements.
N.B. once a condition is met, no subsequent conditions are checked

if condition1:
     Process 1
 elif condition2:
     Process 2
 elif condition3:
     Process 3
 else:
     Process 4
Copy to clipboard
if n == 1: 
    print("one")
elif n == 2: 
    print("two")
elif n == 3: 
    print("three")
else:
    print("Too big!")
print("Done!")
Copy to clipboard
else
Again, the else statement is an optional. There could be at most one else statement following an if
Copy to clipboard

if, elif, else

need a flow chart

Decisions if/elif Syntax

n=1 
if n==1:
    print("one")
elif n>0: # this condition is never checked since the
# condition on line 2 has already been satisfied
    print("positive number")
elif n==3:
    print("three")
else:
      print("Too big!")
print("and Done!") # not part of the if statement
Copy to clipboard

The above returns:

one <br>
and Done!
Copy to clipboard

Decisions if/elif Syntax

n=3 
if n==1:
    print("one") 
elif n>0:
   print("positive number")
elif n == 3: # this condition is never checked since
     # condition on line 4 has already been satisfied
     print("three")
else:
     print("Too big!")
print("and Done!") # not part of the if statement
Copy to clipboard

The above returns:

positive number<br>
 and Done!
Copy to clipboard

Decisions Multiple if statements

I As mentioned previously, once a condition is met in an if/elif statement, no subsequent conditions are checked. I If we want all conditions to be checked we could use multiple if statements:

if condition1:
    Process 1
if condition2:
    Process 2
if condition3:
    Process 3
if condition4:
    Process 4
Copy to clipboard

n=3 if n>0: print(“positive number”) if n==3: print(“three”) if n<10: print(“single digit”)

Example 17

What is the output of the following code?
n=3
if n < 1:
  print("one") 
elif n > 2:
  print("two") 
elif n == 3:
  print("three")
A) nothing
B) one
C) two
D) three
E) error
Copy to clipboard
Answer:
What is the output of the following code?
n=3
if n < 1:
print("one") elif n > 2:
print("two") elif n == 3:
print("three")
A) nothing
B) one
**C) two**
D) three
E) error
Copy to clipboard
Example 18

What is the output of the following code?
n=3
if n < 1:
  print("one") 
elif n > 2
  print("two")
else:
  print("three")
A) nothing
B) one
C) two
D) three
E) error
Copy to clipboard
Answer:

What is the output of the following code?
n=3
if n < 1:
print("one") elif n > 2
print("two") else:
print("three")
Copy to clipboard
  1. nothing

  2. one

  3. two

  4. three
    5. error (missing colon)

Example 19
What is the output of the following code?
n=1
if n < 1:
  print("one") 
elif n > 2:
  print("two")
else:
  print("three") 
print("four")
A)nothing
B) one  four
C) three
D) three four
E) error
Copy to clipboard
Answer:
What is the output of the following code?
n=1
if n < 1:
  print("one") 
elif n > 2:
  print("two")
else:
  print("three") 
print("four")
Copy to clipboard

A)nothing B) one four C) three D) three four E) error

 Example 20
What is the output of the following code?
n=0
if n < 1:
   print("one")
   print("five") 
elif n == 0:
   print("zero")
else:
   print("three") 
print("four")

A)nothing 
B) one 
   four
C) one 
   four
   five
D) one 
  five
  zero 
  four
E) error
  
Copy to clipboard

 Example 20
What is the output of the following code?
n=0
if n < 1:
   print("one")
   print("five") 
elif n == 0:
   print("zero")
else:
   print("three") 
print("four")

A)nothing 
B) one 
   four
C) one 
   four
   five
D) one 
  five
  zero 
  four
E) error