Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS...

29
Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett

Transcript of Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS...

Page 1: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Python Day 3: Lists & Branching

IWKS 2300

Fall 2019

John K. Bennett

Page 2: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Lists Basics

A list is a built-in data structure for storing and accessing objects that belong in a specific sequence.

Two ways to create an empty list in python:

list_one = list()

list_two = []

Page 3: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Lists Basics (Continued …)

A list can contain all sorts of objects, including: integers, strings, booleans, floats, and even other lists.

Python allows you to have multiple data types in the same list.

example = [112, "Apple", True, 1.75, [57, False]]

Page 4: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

More on Lists

Add element to the list:

4

List can be concatenated:

numbers = [1, 2, 3]

letters = ['a', 'b', 'c']

print(numbers + letters)

[1, 2, 3, 'a', 'b', 'c']

list_two.append(7)

Page 5: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

More on Lists (Continued …)

What gets printed when we change the order?

print(letters + numbers)

['a', 'b', 'c', 1, 2, 3] Order is important!

What about now?

letters.append('d')

print(letters + numbers)

['a', 'b', 'c', 'd', 1, 2, 3] Console Output

Page 6: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

List IndexingLists in python are indexed from 0.

Python also wraps around to the end of the list. The last item is index -1.

my_list = ['a', 'b', 'c', 1, 2, 3]

0 1 2 -3 -2 -1

Note: You can only wrap around once. my_list[-7] will cause an error!

>>> my_list[5]

3

>>> my_list[-1]

3

3 4 5

Page 7: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Another Kind of Equals

We’re used to the = operator for assignments. In Python, the == operator is for equality testing.

>>> year = 2019

>>> year == 2018

False

>>> year == 2019

True

An expression a == b will be True iff a has the same value as b, False otherwise.

>>> month = "January"

>>> month == "january"

False

>>> month == "January"

True

Page 8: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Comparisons Operators== Equals to

!= Not Equals to

< Less than

> Greater than

<= Less than or Equals to

>= Greater than or Equals to

Page 9: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Branching

Start ExitTrue

If

Body

Statement just

below if

False

If Condition

if condition:

# do something

elif other_condition:

# do something else

else:

# do something else

Page 10: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Branching (Continued …)

< Less than <= Less than or equals == Equals

> Greater than >= Greater than or equals != Not Equals

name = input("What is your name? ")

if name == "John":

print(f"Your name is {name}")

elif len(name) == 4:

print("Your name has four letters but is

not 'John'")

else:

print("Pleased to meet you", name)

Recall the comparison operators:

Page 11: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Branching (Continued …)

age = int(input("How old are you? "))

if age < 0:

print("That’s not possible!")

elif age <= 12:

print("You are a pre-teen!")

elif age <= 19:

print("You are a teenager!")

elif age == 20:

print("You are not allowed to (legally)

order alcohol.")

else:

print("You can legally order alcohol")

Page 12: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Indentation Denotes ScopeIn Python, indentation not only provides style to help yourself and others read your code, but also provides functionality by denoting the scope of the operation. Consider the following example:

n = int(input("Input a number: "))

if n > 0:

print(n, "is positive.")

if n % 2 == 0:

print(n, "is even.")

print("n is odd.")

print("Goodbye!")

Page 13: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Indentation Denotes Scopen = int(input("Input a number: "))

if n > 0:

print(n, "is positive.")

if n % 2 == 0:

print(n, "is even.")

print("n is odd.")

print("Goodbye!")

1. What will be printed if n is 3?

2. What will be printed if n is -2?

3. What will be printed if n is 4?

Page 14: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Indentation Denotes Scopen = int(input("Input a number: "))

if n > 0:

print(n, "is positive.")

if n % 2 == 0:

print(n, "is even.")

print("n is odd.")

print("Goodbye!")

1. What will be printed if n is 3?

2. What will be printed if n is -2?

3. What will be printed if n is 4?

3 is positive.

n is odd.

Goodbye!

Page 15: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Indentation Denotes Scopen = int(input("Input a number: "))

if n > 0:

print(n, "is positive.")

if n % 2 == 0:

print(n, "is even.")

print("n is odd.")

print("Goodbye!")

1. What will be printed if n is 3?

2. What will be printed if n is -2?

3. What will be printed if n is 4?

Goodbye!

Page 16: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Indentation Denotes Scopen = int(input("Input a number: "))

if n > 0:

print(n, "is positive.")

if n % 2 == 0:

print(n, "is even.")

print("n is odd.")

print("Goodbye!")

1. What will be printed if n is 3?

2. What will be printed if n is -2?

3. What will be printed if n is 4?4 is positive.

4 is even.

n is odd

Goodbye!

???

Page 17: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

What’s Wrong With This Code?How to Fix It?

n = int(input("Input a number: "))

if n > 0:

print(n, "is positive.")

if n % 2 == 0:

print(n, "is even.")

print("n is odd.")

print("Goodbye!")

Page 18: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

How to Fix this Code?

n = int(input("Input a number: "))

if n >= 0:

print(n, "is positive.")

else:

print(n, "is negative.")

if n % 2 == 0:

print(n, "is even.")

else:

print(n, "is odd.")

print("Goodbye!")

n = int(input("Input a number: "))

if n > 0:

print(n, "is positive.")

if n % 2 == 0:

print(n, "is even.")

print("n is odd.")

print("Goodbye!")

Page 19: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Introduction to 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 20: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

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

Introduction to Python for Loops:Generating Ranges

Page 21: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Introduction to Python for Loops:

Ranges work a lot like substrings

Page 22: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

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

Here’s the previous example w/out the step

argument.

Introduction to Python for Loops:Range: step is Optional

for i in range(0, 3):

print(i) # print each item in list

0

1

2

Page 23: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

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.

Introduction to Python for Loops:Range: start is Optional

for i in range(3):

print(i) # print each item in list

0

1

2

Page 24: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

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!"

Introduction to Python for Loops:Repeat n times

Page 25: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

n = 3

for i in range(n):

print("Python is awesome!")

"Python is awesome!"

"Python is awesome!"

"Python is awesome!"

Introduction to Python for Loops:How Would You Make Range

Inclusive?

Page 26: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

n = 3

for i in range(n+1):

print("Python is awesome!")

"Python is awesome!"

"Python is awesome!"

"Python is awesome!“

"Python is awesome!"

Introduction to Python for Loops:How Would You Make Range

Inclusive?

Page 27: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Python Village ini4:## Problem

##

## Given: Two positive integers a and b (a<b<10000).

##

## Return: The sum of all odd integers from a through b inclusively.

##

## Sample Dataset

##

## 100 200

##

## Sample Output

##

## 7500

How do we solve this problem?

Page 28: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Bioinformatics Stronghold rna:# Transcribing DNA into RNA

"""

Problem

An RNA string is a string formed from the alphabet containing 'A', 'C', 'G', and 'U'.

Given a DNA string t corresponding to a coding strand, its transcribed RNA

string u is formed by replacing all occurrences of 'T' in t with 'U' in u.

Given: A DNA string t having length at most 1000 nt.

Return: The transcribed RNA string of t.

Sample Dataset

GATGGAACTTGACTACGTAAATT

Sample Output

GAUGGAACUUGACUACGUAAAUU

"""

How do we solve this problem?

Page 29: Python Day 3: Lists & Branching - University of Colorado ...Python Day 3: Lists & Branching IWKS 2300 Fall 2019 John K. Bennett . Lists Basics A list is a built-in data structure for

Bioinformatics Stronghold rna:1) Remember how we enumerate

over a string:

for ch in mystring:

if ch == 'T':

print("Found a 'T'")

2) Remember how concatenate strings

by adding them:

outstr = ""

for ch in mystring:

if ch == 'Q':

outstr += 'W'