Lists, While & For Loops, Dictionaries & String Slicing...

81
Lists, While & For Loops, Dictionaries & String Slicing (plus some miscellaneous) John K. Bennett IWKS 2300 Fall 2019

Transcript of Lists, While & For Loops, Dictionaries & String Slicing...

Page 1: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Lists, While & For Loops,Dictionaries & String Slicing(plus some miscellaneous)

John K. BennettIWKS 2300Fall 2019

Page 2: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

While Loops

A while loop checks its condition before executing its code block.

After execution, the condition is tested again, etc. Code repeats while

the condition is True.

i = 1

while(i <= 10):

print(i,"Hello, World")

i = i + 1

How many time will this snippet of code print "Hello, World"?

Page 3: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

While Loops

A while loop checks its condition before executing its code block.

After execution, the condition is tested again, etc. Code repeats while

the condition is True.

i = 1

while(i <= 10):

print(i,"Hello, World")

i = i + 1

How many time will this snippet of code print "Hello, World"?

10 times

Page 4: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Comparing if and while

The difference between while and if is that

● if executes its code body once if condition is True,

● While repeats its body while the condition is True.

i = 1

if i <= 10:

i = i + 1

# i is now ??

i = 1

while i <= 10:

i = i + 1

# i is now ??

Page 5: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Comparing if and while

The difference between while and if is that

● if executes its code body once if condition is True,

● While repeats its body while the condition is True.

i = 1

if i <= 10:

i = i + 1

# i is now ??

i = 1

while i <= 10:

i = i + 1

# i is now ??

2

Page 6: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Comparing if and while

The difference between while and if is that

● if executes its code body once if condition is True,

● While repeats its body while the condition is True.

i = 1

if i <= 10:

i = i + 1

# i is now ??

i = 1

while i <= 10:

i = i + 1

# i is now ??

2 11

Page 7: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Loop Control: Continue

A continue statement allows you to go to the next iteration.

i = 1

while (i <= 3):

i = i + 1

if (i == 2):

continue # skip to the top of the loop

print("i is not 2, it is", i)

What gets printed?

Page 8: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Loop Control: Continue

A continue statement allows you to go to the next iteration.

i = 1

while (i <= 3):

i = i + 1

if (i == 2):

continue # skip to the top of the loop

print("i is not 2, it is", i)

i is not 2, it is 3

i is not 2, it is 4

Page 9: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Loop Control: BreakA break statement allows you to stop iterating immediately.

i = 1

while(i < 100):

num = int(input("Enter a number, or 0 to exit"))

if (num == 0):

break # stop the loop immediately

i = i + num

print("Okay, bye!")

What gets printed?

Page 10: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Loop Control: BreakA break statement allows you to stop iterating immediately.

i = 1

while(i < 100):

num = int(input("Enter a number, or 0 to exit"))

if (num == 0):

break # stop the loop immediately

i = i + num

print("Okay, bye!")

Enter a number, or 0 to exit: 3

Enter a number, or 0 to exit: 0

Okay, bye!

Page 11: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Loop Control: Pass

A pass statement does nothing. It can be used when you might want a

placeholder (e.g., as you are writing new code). No action results.

i = 1

while(i < 5):

i = i + 1

if (i == 2):

pass # do nothing

print("Number is ", i)

What gets printed?

Page 12: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Loop Control: Pass

A pass statement does nothing. It can be used when you might want a

placeholder (e.g., as you are writing new code). No action results.

i = 1

while(i < 5):

i = i + 1

if (i == 2):

pass # do nothing

print("Number is ", i)

Number is 5

Page 13: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

There is no "Do While" in Python

Unlike some other languages, Python does not have a do while loop. Its

functionality can be obtained with a while True and break.

do(

# loop body

) while condition

i = 1

while True:

# loop body

if not condition:

break

Notes:

1. A while True loop will execute at least once.

2. Make sure the loop stops executing somehow!

Page 14: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

List Indexed Assignment

Lists can change once they’re created. Assign to the list the desired index.

my_list = [5, 6, 7]

My_list[2] = 8

print(my_list) What gets printed from this line?

However, assignments to indices not currently in the list is not allowed. This example will result in an error.

My_list[3] = 9 # This is illegal, 3 is out of range.

Page 15: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

List Indexed Assignment

Lists can change once they’re created. Assign to the list the desired index.

my_list = [5, 6, 7]

My_list[2] = 8

print(my_list) What gets printed from this line?

[5, 6, 8]

However, assignments to indices not currently in the list is not allowed. This example will result in an error.

My_list[3] = 9 # This is illegal, 3 is out of range.

Page 16: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

List Concatenation

Similar to strings, lists can be concatenated using the + operator:

a = [5, 6, 7]

b = ["eight", "nine", "ten"]

c = a + b

print(a)

print(b)

print(c)

[5, 6, 7]

["eight", "nine", "ten"]

[5, 6, 7, "eight", "nine", "ten"]

Page 17: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Lists in Lists

List can store data of any type; including other lists

print(nested[0][0])

nested[0][0] = nested[1][0]

print(nested)

What gets printed?

Accessing and indexing is done by using another set of brackets

nested = [[1, 2, 3],[4, 5, 6]]

Page 18: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Lists in Lists

List can store data of any type; including other lists

print(nested[0][0])

nested[0][0] = nested[1][0]

print(nested)

1

[[4, 2, 3], [4, 5, 6]]

Accessing and indexing is done by using another set of brackets

nested = [[1, 2, 3],[4, 5, 6]]

Page 19: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

List Methods

● Adding elements to lists○ append(x)○ extend([x])○ insert(i, x)

Python provides several functions to interact with lists (this is more than you need to know now):

● Modifying Elements○ sort()○ reverse()

● Removing Elements from lists○ remove(x)○ pop()○ pop(i)

● Miscellaneous○ index()○ count()

Page 20: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Iterating Over a List using a while

With a while loop, we can iterate over a list using a counter variable.

my_list = [1, 2, "three"]

i = 0

while i < len(my_list):

print(my_list[i]) # print will run 3 times

i = i + 1

1

2

three

Page 21: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

While Loop PracticeFirst, trace the loop by hand and determine the output.

Then, run the loop in Python IDLE to see if you were correct.

x = 1

i = 2

while x < 10:

x = x + i

i = i + 2

print(x, i)

print("Python!")

Page 22: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

While Loop PracticeFirst, trace the loop by hand and determine the output.

Then, run the loop in Python IDLE to see if you were correct.

x = 1

i = 2

while x < 10:

x = x + i

i = i + 2

print(x, i)

print("Python!")

3 4

7 6

13 8

Python!

Page 23: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

While Loop Practice

First, trace the loop by hand and determine the output.

Then, run the loop in Python IDLE to see if you were correct.

i = 0

while i < 2:

i = i + 2

j = 0

while j < 3:

j = j + 1

print(i, j)

print("Okay!")

Page 24: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

While Loop PracticeFirst, trace the loop by hand and determine the output.

Then, run the loop in Python IDLE to see if you were correct.

i = 0

while i < 2:

i = i + 2

j = 0

while j < 3:

j = j + 1

print(i, j)

print("Okay!")

2 1

2 2

2 3

Okay!

Page 25: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

While Loop PracticeFirst, trace the loop by hand and determine the output.

Then, run the loop in Python IDLE to see if you were correct.

i = 0

while i < 20:

if i % 3 == 0:

print(i)

i = i + 1

Page 26: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

While Loop PracticeFirst, trace the loop by hand and determine the output.

Then, run the loop in Python IDLE to see if you were correct.

i = 0

while i < 20:

if i % 3 == 0:

print(i)

i = i + 1

0

3

6

9

12

15

18

Page 27: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Review of Python for Loops:Iterating Over a List

Python provides a range-based construct for iterables called for.

for var_name in iterable:

# do something

for item in my_list:

print(item) # print each item in list

1

2

three

Suppose we have the following list:my_list = [1, 2, "three"]

Page 28: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

The range() function can be used to generate a sequence of numbers. The syntax is

range(start, stop, step)

start is the start number (defaults to 0)stop is the stop number (exclusive)step is the increment value (defaults to 1)

for i in range(0, 3, 1):

print(i) # print each item in list

0

1

2

Review of Python for Loops:Generating Ranges

Page 29: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

If you do not provide a step in the range function, Python assumes one.

Here’s the previous example w/out the step

argument.

Review of Python for Loops:Range: step is Optional

for i in range(0, 3):

print(i) # print each item in list

0

1

2

Page 30: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

If you do not provide a start in the range function, Python assumes zero.

Here’s the previous example w/out the step or

start arguments.

Review of Python for Loops:Range: start is Optional

for i in range(3):

print(i) # print each item in list

0

1

2

Page 31: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

You can repeat something n times with a range

based loop:n = 3

for i in range(n):

print("Python is awesome!")

"Python is awesome!"

"Python is awesome!"

"Python is awesome!"

Review of Python for Loops:Repeat n times

Page 32: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

n = 3

for i in range(n):

print("Python is awesome!")

"Python is awesome!"

"Python is awesome!"

"Python is awesome!"

Review of Python for Loops:How Would You Make Range

Inclusive?

Page 33: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

n = 3

for i in range(n+1):

print("Python is awesome!")

"Python is awesome!"

"Python is awesome!"

"Python is awesome!"

"Python is awesome!"

Review of Python for Loops:How Would You Make Range

Inclusive?

Page 34: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Python Range Summary

The range() function can take between 1 – 3 parameters, e.g.:

range (7)

range (0, 7)

range (0, 7, 1)

Besides the number of parameters, what execution differences, if

any, will be observed if these ranges are used?

Page 35: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Other Example Code (note end)

What does the end = " " do?

Page 36: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

For Loop PracticeFirst, trace the loop by hand and determine the output.

Then, run the loop in Python IDLE to see if you were correct.

for i in range(3):

for j in range(2):

print(i, j)

Page 37: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

For Loop PracticeFirst, trace the loop by hand and determine the output.

Then, run the loop in Python IDLE to see if you were correct.

for i in range(3):

for j in range(2):

print(i, j)

0 0

0 1

1 0

1 1

2 0

2 1

Page 38: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

For Loop Practice

First, trace the loop by hand and determine the output.

Then, run the loop in Python IDLE to see if you were correct.

favnums = [4, 3, 1]

stats = ["my new favorite", "okay", "boring"]for num in favnums:

for stat in stats:

print(num, "is", stat)print("Tomorrow . . .")

print("I’m sticking with", favnums[1])

Page 39: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

For Loop Practice

4 is my new favorite

4 is okay

4 is boring

Tomorrow . . .

3 is my new favorite

3 is okay

3 is boring

Tomorrow . . .

1 is my new favorite

1 is okay

1 is boring

Tomorrow . . .

I’m sticking with 3

Page 40: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Dictionaries● A Python dictionary is a collection of key-value pairs.

● Keys must be unique.

● Values can be almost any object.

## Creating an empty dictionary:dict = {}## Creating an initialized dictionary:dict = {

"make": "Ferrari","model": "250 GTO","year": 1963

}

Page 41: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Dictionaries

Dictionary type can be int, float, list, etc., e.g.:dict = {}dict["for loops"] = [43, 48, 50]dict["functions"] = [65, 66]dict["lists"] = [30, 31, 32]dict["while loops"] = [44, 49, 51]print (dict)

Page 42: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

DictionariesWe can look up values using the key, e.g.:

dict = {"make": "Ferrari","model": "250 GTO","year": 1963

}my_car_make = dict["make"]my_car_model = dict["model"]

Page 43: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

DictionariesWe can look up values using the key, e.g.:

dict = {"make": "Ferrari","model": "250 GTO","year": 1963

}my_car_make = dict["make"]my_car_model = dict["model"]## we can also use get, e.g.:my_car_year = dict.get(“year")

Page 44: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

DictionariesWe can change values using the key, e.g.:

dict = {"Bobs": 1,"Carols": 2,"Teds": 0

}dict["Bobs"] += 1dict["Carols"] -= 1dict["Teds"] = 1print(dict)

Page 45: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

DictionariesWe can change values using the key, e.g.:

dict = {"Bobs": 1,"Carols": 2,"Teds": 0

}dict["Bobs"] += 1dict["Carols"] -= 1dict["Teds"] = 1print(dict)-----------------------------------------------------------------------------{'Bobs': 2, 'Carols': 1, 'Teds': 1}

Page 46: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

DictionariesWe can loop through dictionary keys, e.g.:

dict = {"Bobs": 1,"Carols": 2,"Teds": 0

}for x in dict:print(x)

-----------------------------------------------------------------------------BobsCarolsTeds

Page 47: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

DictionariesWe can loop through dictionary keys or values, e.g.:

dict = {"Bobs": 1,"Carols": 2,"Teds": 4

}for x in dict.values(): ## this works for dict.keys as wellprint(x)

-----------------------------------------------------------------------------124

Page 48: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

DictionariesWe can loop through both keys and values using the items() function:, e.g.:

dict = {"Bobs": 1, "Carols": 2, "Teds": 4}for x, y in dict.items():print(x, y)

-----------------------------------------------------------------------------Bobs 1Carols 2Teds 4

Page 49: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

DictionariesTo determine if a specified key is present in a dictionary use the in keyword:##dict = {

"make": "Ferrari","model": "250 GTO","year": 1963

}if "model" in dict:

print("Yes, 'model' is one of the keys in the dict dictionary")

Page 50: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

DictionariesTo determine how many items (key-value pairs) a dictionary has, use the len() method.:##dict = {

"make": "Ferrari","model": "250 GTO","year": 1963

}print(len(dict))-----------------------------------------------------------------3

Page 51: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

String SlicingThe Python string data type is a sequence made up of one or more

individual characters that could consist of letters, numbers, whitespace

characters, or symbols. Because a string is a sequence, it can be

accessed in the same ways that other sequence-based data types are,

through indexing and slicing.

Recall how strings are indexed:

P y t h o n R u l e s

0 1 2 3 4 5 6 7 8 9 10 11

-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Page 52: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

String Slicing

s = ‘Python Rules’

slice1 = s [3]

slice2 = s [-4]

print(slice1)

print(slice2)

P y t h o n R u l e s

0 1 2 3 4 5 6 7 8 9 10 11

-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Page 53: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

String Slicing

s = "Python Rules"

slice1 = s [4:6]

slice2 = s [-5:-1]

print(slice1) ## prints "on"

print(slice2) ## prints "Rule"

P y t h o n R u l e s

0 1 2 3 4 5 6 7 8 9 10 11

-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Page 54: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

String Slice Syntax

[start(inclusive) : stop (exclusive) : step]

default: default: def:

0 end 1

Any omitted value is replaced with the

default value.

Page 55: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

String Slicing

s = "Python Rules"

slice1 = s [:6]

slice2 = s [7:]

print(slice1) ## prints "Python"

print(slice2) ## prints "Rules"

P y t h o n R u l e s

0 1 2 3 4 5 6 7 8 9 10 11

-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Page 56: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

String Slicing

s = "Python Rules"

slice1 = s [-12:-6]

slice2 = s [-5:]

print(slice1) ## prints "Python"

print(slice2) ## prints "Rules"

P y t h o n R u l e s

0 1 2 3 4 5 6 7 8 9 10 11

-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Page 57: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

String Slicing

s = "Python Rules"

slice1 = s [::4]

slice2 = s [::-1]

print(slice1) ## prints "Pou"

print(slice2) ## prints "seluR nohtyP"

P y t h o n R u l e s

0 1 2 3 4 5 6 7 8 9 10 11

-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Page 58: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

String Slicing

s = "Python Rules"

slice1 = s [::-2]

slice2 = s [::-4]

print(slice1) ## prints "slRnhy"

print(slice2) ## prints "sRh"

P y t h o n R u l e s

0 1 2 3 4 5 6 7 8 9 10 11

-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Page 59: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

A Few Miscellaneous Thoughts

● Assignment Shorthand

● Debugging Python Programs

Page 60: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Shorthand Assignment and Op

Normally, to increment i by 1, we write:

i = i + 1

We can use shorthand notation instead:

i += 1

To increment i by 3, we write:

i += 3

i += a is equivalent to i = i + a

Page 61: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Shorthand Notation and Other Operators

i += a is equivalent to i = i + a

i –= a is equivalent to i = i – a

i *= a is equivalent to i = i * a

i /= a is equivalent to i = i / a

i **= a is equivalent to i = i ** a

Page 62: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Shorthand Notation : Common Use

Page 63: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Practice: What is the final value of i?

i = 4

i += 2

i -= 3

i *= 3

i **= 2

print(i)

Page 64: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Practice: What is the final value of i?

i = 4

i += 2

i -= 3

i *= 3

i **= 2

print(i)

-------------------------------------------------------------81

Page 65: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Practice: What is the final value of x?

x = 2

x /= 2

x += 1

x **= 2

x **= 2

print(x)

-------------------------------------------------------------

Page 66: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Practice: What is the final value of x?

x = 2

x /= 2

x += 1

x **= 2

x **= 2

print(x)

-------------------------------------------------------------16.0

Page 67: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Debugging Python ProgramsDebugging is a mileage sport. The more code you write and make work, the better you will be at debugging code. Here are a few suggestions:

While writing your code

● Use comments extensively. Use multiline comments at the beginning of your program (or in each file of your program) to explain the overall rationale of that section of code. Use in-line comments to clarify what your code is actually doing.

● Avoid being clever for the sake of cleverness. If there is a performance win, ok, be clever, but explain what you are doing in comments. The more clever (obtuse) your code, the more time you need to spend explaining things.

● Develop and use a consistent style for variable names, comments, etc. Write code as if your personal reputation depends upon its quality. It might.

Page 68: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Debugging Python ProgramsRunning your code

● Use lots of print statements to see what is happening. You can remove them later, or wrap them in a “if debug:”, where debug is a Boolean flag you set at the top of your code.

● Program incrementally. Write a little bit of code and test it, then add a little bit more code and test that. Repeat, continuing to build out from a working foundation.

● Use the built in IDLE debugger to set breakpoints and inspect program operation while it is running. Here is a good IDLE debugger tutorial: https://www.cs.uky.edu/~keen/help/debug-tutorial/debug.html

Page 69: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Use Multi-line comments

# We are accustomed to one line comments.

# But, for longer comments that span multiple lines, this can

# be very inefficient, which is why multi-line comments exist.

"""

Multi-line comments are used when a comment spans multiple lines.

They make it easier for other people to read and use your code.

Nice to use to give a descriptive explanation about a large

chunk of code."""

Page 70: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Validating Credit Card Numbers (Luhn)• Since the 1970’s, credit cards have become a ubiquitous method for

paying for purchases and discharging debts.

• All such cards have a numerical sequence of digits that uniquely identify

the card and it owner. In most cases, having a credit or debit card is as

good as having cash.

• This exercise explores how credit/debit card numbers are generated and

validated.

• Validation, (testing for being a valid credit card number), is distinct from

authentication and authorization, (ensuring that the user of the card is its

rightful owner, and that they are allowed to make a specific purchase).

• We will not consider authentication or authorization in this exercise.

Page 71: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Validating Credit Card Numbers (Luhn)

Different card companies use different length numbers:

• American Express - fifteen digits

• Visa and MasterCard - sixteen digits

Credit card companies also use unique identifying

prefixes in their numbers, e.g.:

• American Express - start with 34 or 37

• MasterCard - start with 51, 52, 53, 54, or 55

• Visa - start with a 4

Page 72: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Validating Credit Card Numbers (Luhn)

• Most credit card numbers use a built-in “checksum.”

• The checksum algorithm used by most credit card companies (and by several

governments and many non-financial industries) is called the “Luhn Algorithm,”

named for its inventor, an IBM scientist named Hans Peter Luhn.

• Luhn patented this algorithm (or rather, an invention that implemented this

algorithm in a handheld mechanical device intended to be used by merchants)

in 1960 (U.S. Patent No. 2,950,048, Computer for Verifying Numbers; filed in

1954), but the patent has since lapsed into the public domain.

• The Luhn algorithm is intended only to protect against accidental errors, i.e.,

mistyped numbers; it offers little protection from malicious cryptographic

attack.

Page 73: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Luhn’s CC# Validation Algorithm

1. Starting with the second to last digit (from the right) of the

number, multiply every other digit by 2, recording each answer

separately.

2. Sum all of the individual digits of all the products (not the

products themselves) from Step 1.

3. To the sum obtained in Step 2, add all of the digits that were not

multiplied by 2 in Step 1.

4. If the last digit of the resulting sum is zero, (i.e., the total modulo

10 is equal to 0), the number is valid.

Page 74: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Luhn Example (part 1)

Let’s try an example using a possible number that we created for this purpose:

4735672384163216

First, if valid, we know this is a Visa card because it starts with a “4”.

To make things easier, let’s underline every other digit, starting with the

number’s second-to-last digit (the other digits are highlighted in yellow):

4935672384163216

Now multiply each of the underlined digits by 2, as shown here:

1•2 ; 3•2 ; 1•2 ; 8•2 ; 2•2 ; 6•2 ; 3•2 ; 4•2

That gives us:

2 ; 6 ; 2 ; 16 ; 4 ; 12 ; 6 ; 8

Page 75: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Luhn Example (part 2)

Now add those products’ digits (not the products

themselves) together (the braces show how we have

separated the digits of the two-digit numbers):

2 + 6 + 2 + [1 + 6] + 4 + [1 + 2] + 6 + 8 = 38

Now add this sum (38) to the sum of the digits that were

not multiplied by 2 (the ones highlighted in yellow), starting

from the right and working left:

38 + 6 + 2 + 6 + 4 + 3 + 7 + 5 + 9 = 80

The last digit in the resulting sum (80) is a zero, so this card

number is valid (please do not try to use it)!

Page 76: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Your Task (Option a.)

a. (If you are less comfortable with this assignment) Write a Python program that asks for a credit

card number (input as a string without hyphens or spaces, not as a number), and reports the card

type (American Express, MasterCard, or Visa), and whether the card is valid. So, for the example

above (4735672384163216), your program should output “4735672384163216--------VISA: VALID”,

i.e., the number as a string, 8 hyphens, and “VISA: VALID.” If the entered number is anything other

than a valid CC number, your program should output the number as a string, eight hyphens, and

“INVALID NUMBER.” In addition to your working code, you should submit a plain text file with one

answer per line, for each of the following twenty CC numbers (which include valid and invalid credit

card numbers of each type):

4735672384163216

You may manually enter these numbers one at a time, or (better) read them from a file that you

create.

Page 77: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Your Task (Option b.)

b. (If you are more comfortable with this assignment)

Write a Python program that reads a text file of

candidate CC numbers, one number (as a string) per line,

and outputs a file with the results described above for

each CC number, one per line. The CC numbers the file

(of about 700 numbers) may be of any type in any order.

Test your program on the file testCCNums.txt, and

submit the results with your working code.

Page 78: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Luhn IsValid Function (1)

def isValidCC(num):length = len(num)## list of digits to be multiplied by 2list1 = []str1 = ""for i in range(length-2, -1, -2):

list1.append(str(2 * int(num[i])))for number in list1:

str1 += numbersum1 = 0str1 = str1.strip()for ch in str1:

sum1 += int(ch)

## the other digits…

Page 79: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Luhn IsValid Function (2)

## the other digitslist2 = []str2 = ""for i in range(length-1, 0, -2):

list2.append(num[i])for number in list2:

str2 += numbersum2 = 0str2 = str2.strip()for ch in str2:

sum2 += int(ch)## do the sum…

Page 80: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Luhn IsValid Function (3)

## do the sumccsum = str(sum1 + sum2)lastdig = int(ccsum[len(ccsum)-1])if lastdig == 0:

return (True) ## valid cardelse:

return (False)

Page 81: Lists, While & For Loops, Dictionaries & String Slicing ...inworks.ucdenver.edu/jkb/iwks2300/lectures/Python-Day5.pdfThere is no "Do While" in Python Unlike some other languages, Python

Luhn Main Program## Main Programf = open('Luhn_Part_a.txt', 'r')g = open('Luhn_a_out.txt', 'w')for num in f:

num = num.strip();typeDig = num[0]if typeDig == '4':

ccType = 'VISA'elif ((typeDig == '3') and ((num[1] == '4') or (num[1] == '7'))):

ccType = 'MASTERCARD'elif ((typeDig == '5') and ((int(num[1]) >= 1) and (int(num[1]) <=5))):

ccType = 'AMEX'else:

ccType = 'BOGUS'

if isValidCC(num): outstr = num + "--------" + ccType + ":VALID\n"

else:outstr = "INVALID NUMBER\n"

g.write(outstr)

f.close()g.close()