Python 1-2#

Iterations, lists, dictionaries, comprehensions

Iterations#

  • Iterations are code strucures which allow us to repeat sections of code while a condition is true, or a fixed number of time.

  • They allow us to do more with less code!

Definite loops (For Loop)#

  • A Definite loop iterates over a a fixed set of values.

  • Real life iterations: Knocking on every door in your dorm. Calling each person in the contact list on your phone.

  • In Python the for statement is used for definite loops

  • The for loop uses an iterator to select each item from the list or range and take action in the loop body.

  • The range() function is useful for getting an iterator of numbers.

  • The for loop can iterate over any value that is iterable.

1# Example: Using the range() function to iteratre over a sequence
2
3for i in range(5):
4    print(i)
0
1
2
3
4

In the example above:

  • the print() statement repeats as part of the loop body.

  • the variable i is the iterator. It stores the current value of the range(5) for each iteration of the loop

  • range(5) is an example of the iterable - the thing we are looping over.

  • range(5) by definition creates an iterable of sequential numbers from 0 to 4: 0,1,2,3,4

  • Therefore the code repeats 5 times…

1# Example: strings are iterable by their individual characters
2for ch in "testing":
3    if ch == "t":
4        print(ch)
t
t

Questions about the example above:

  • What is the iterator variable?

  • What is the iterable?

  • How many times does this loop “iterate”?

  • Why does it only print two t’s?

The break command#

  • break keyword exits the loop immediately.

  • Commonly used when there is no longer a reason to loop (you achieved your goal).

  • You can add an else to the for loop to execute when break does not happen.

 1# Example: find a letter in a text string
 2
 3text = input("Enter Some Text:")
 4find = input("Enter character to find:")
 5for ch in text:
 6    if ch == find:
 7        print(f"Found {find} in {text}!")
 8        break
 9else:
10    print(f"Unable to find {find} in {text}!")
Enter Some Text: testing
Enter character to find: n
Found n in testing!

Enter Some Text: testing
Enter character to find: x
Unable to find x in testing!

Challenge 1-2-1#

Write a program to accept a password as input. If the password input is “secret” display “access granted” else say “invalid password”

repeat the above up to 5 times. when the correct password is entered, stop looping when 5 loops have exhaused print “you are locked out”

Indefinite loops#

  • Indefinite loops are based on external input and are non-determinsitic.

  • Unlike definite loops we do not know when the loop will stop.

  • Examples: get tutoring when you fail an exam (you may never fail an exam). When the temperature drops below 0 turn on the de-icer.

  • In Python, we use while statement for indefinite loops.

  • The classic indefinite loop is a sentiel controlled loop that repeats until a specific event occurs.

1# Example: Will I ever say the magic word?
2while True:
3    word = input("Say the magic word!")
4    if word == 'please':
5        break
6    print("You didn't say the magic word!")
You didn't say the magic word!
You didn't say the magic word!
You didn't say the magic word!

In the above example the word “please” is the sentinel value

 1# Example: Sentinel loop
 2
 3count = 0
 4while True:
 5    raw = input("Enter a number or type 'stop':")
 6    if raw == 'stop':
 7        break
 8    count = count + 1
 9
10print(f"You entered {count} items.")
You entered 3 items.

Challenge 1-2-2#

Write a program to accept numbers until the user enters: 0

The program should count the number of positive and negative numbers entered, and print those values after the 0 is entered.

Lists#

  • lists are iterable, sequences of values

  • The values in the list are mutable - you can change them.

  • items in the list can be accessed by a zero-based index.

1# Example: Items in the list
2
3items = [ 'milk', 'bread' ,'cheese', 'apples' ]
4
5print("The first item is:", items[0])
6print("The second item is:", items[1])
7print("The last item is:", items[-1])
The first item is: milk
The second item is: bread
The last item is: apples
1# Lists are iterable
2items = [ 'milk', 'bread' ,'cheese', 'apples' ]
3for item in items:
4    print(item)
milk
bread
cheese
apples

Questions about the example above:

  • What is the iterator variable?

  • What is the iterable?

  • How many times does this loop “iterate”?

The in operator#

The in operator checks for existence of an item in a list.

1# Example: whats in the list?
2numbers = [10, 15, 20]
3print(f"5 in {numbers}?", 5 in numbers)
4print(f"20 in {numbers}?", 20 in numbers)
5 in [10, 15, 20]? False
20 in [10, 15, 20]? True

List Methods#

There are numerous list methods which allow you to add remove and find values in the list, etc…

https://docs.python.org/3/library/stdtypes.html?highlight=list#mutable-sequence-types

 1# Example: manipulating a list
 2
 3# An empty list
 4colors = []
 5
 6# Add "blue" to the end
 7colors.append("blue")
 8
 9# add "red" to the beginning
10colors.insert(0, "red")
11
12# add "white" in the 2nd position
13colors.insert(1, "white")
14
15# print ['red', 'white', 'blue']
16print(colors)
17
18# remove the last color
19blue = colors.pop(-1)
20
21# remove "white")
22white = colors.remove("white")
23
24# print ['red']
25print(colors)
['red', 'white', 'blue']
['red']

Challenge 1-2-3#

Write a sentinel controlled loop to input a color until “quit” is entered. add each color to a list only when the color is not already in the list print the list each time in the loop

list comprehensions#

List comprehensions allow us to create lists from operations on existing lists.

Consider the following:

1numbers = [1, 2, 4, 5, 7]
2evens = []
3for num in numbers:
4    if num % 2 ==0: #even
5        evens.append(num)
6print(evens)
[2, 4]
1# Same thing as a list comprehension
2numbers = [1, 2, 4, 5, 7]
3evens = [ num for num in numbers if num % 2 == 0]
4print(evens)
[2, 4]
1# This comprehension makes a list out of the first letter in each work
2words = ["welcome", "other", "rent", "math" ]
3firsts = [ word[0] for word in words ]
4print(firsts)
['w', 'o', 'r', 'm']

Dictionaries#

  • The dict type is designed to store key-value pairs. In Python this is known as a mapping type.
    font={'name':'Arial','size': 8}

  • Python dictionaries are mutable which means you can change the values of the keys after they have been set.

  • Dictionary values are accessed by key not by index.
    font['name'] = 'Courier'

  • the keys are unique in the dictionary

Dictionary Methods#

Complex Data Stuctures#

We can combine lists and dictionaries to create complex data structures in python.

These allow us to represent real-world data in code

1students = [
2    { 'name' : 'abby', 'grades' : [100,80,90] },
3    { 'name' : 'bob', 'grades' : [100,90,90] },
4    { 'name' : 'chris', 'grades' : [90,100,100] }
5]
1# just print each student name
2for student in students:
3    print(student['name'])
abby
bob
chris
1# print each student name and average grade
2for student in students:
3    avg_grade = sum(student['grades'])/len(student['grades'])
4    print(f"{student['name']}  {avg_grade:.2f}")
abby  90.00
bob  93.33
chris  96.67

Challenge 1-2-4#

Write a program to create a shopping list.

loop until “quit” is entered. input a grocery item input a quantity save the item as the key in the dictionary and quantity as the value if the item is in the dictionary already, add the quantity to the existing value