python day 3: lists & branching - university of colorado ...python day 3: lists & branching...

Post on 17-Apr-2021

3 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Python Day 3: Lists & Branching

IWKS 2300

Fall 2019

John K. Bennett

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 = []

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]]

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)

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

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

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

Comparisons Operators== Equals to

!= Not Equals to

< Less than

> Greater than

<= Less than or Equals to

>= Greater than or Equals to

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

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:

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

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

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?

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!

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!

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!

???

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

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

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

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

Introduction to Python for Loops:

Ranges work a lot like substrings

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

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

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

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?

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?

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?

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?

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'

top related