CS 22A: Introduction to Python
Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit
CS 22A: Introduction to Python Fall 2021
Hands-On Twelve: Practice
Problems 1 to 6:
For problems 1 and 2, write the code first, and then trace through the for-loop on a separate paper.
1. Write a program that goes through each element in my_list, and if the element starts with the letter ‘p’ and ends with the letter ‘e’, print that element.
my_list = [‘book’, ‘binder’, ‘pencil’, ‘phone’]
2. Write a program that goes through each element in my_list, and if the element starts with the letter ‘b’, print out “starts with the letter b”. If the element does not start with the letter ‘b’, prints out “does not start with the letter b”. Also create a trace chart for your code.
my_list = [‘bt23’, ‘ns31’, ‘by44’, ‘jr71’]
CS 22A: Introduction to Python Fall 2021
For problem 3, fill out the trace chart.
3. For the code below, trace the for-loop using the tracing scheme given below.
grades = ‘A,D,B,B,F,C,F’
grade_list = grades.split(“,”)
good = []
poor = []
for grade in grade_list:
if grade == ‘A’ or grade == ‘B’ or grade == ‘C’:
good.append(grade)
else :
poor.append(grade)
print(good)
print(poor)
grade |
grade == ‘A’ |
grade == ‘B’ |
grade == ‘C’ |
good |
poor |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
CS 22A: Introduction to Python Fall 2021
For problem 4, read the text and understand the given function.
4. We want to write a Python program that tells us whether a given number is odd or even. How do we code this?
In Python, the % (called the “modulo operator”) returns the remainder when dividing two numbers. For example, 4%2 = 0 because when you divide 4 by 2, there is no remainder left. However, 3%2 = 1 because 2 only goes into 3 one time and thus, we get a remainder of 1. Notice that any even number divided by 2 will give you 0 as your remainder. Using this logic, any number%2 will give you either 0 or 1. If the remainder is 0, we know that the number is even. If it is 1, we know that the number is odd.
def even_odd(num):
if num%2 == 0:
return ‘even’
else:
return ‘odd’
print(even_odd(4))
For problem 5, 6, and 7, fill out the given trace chart.
5. my_list = [5,3,1]
for i in range(3):
my_list.append(i+i)
print(my_list)
i |
my_list.append(i+i) |
print(my_list) |
|
|
|
|
|
|
|
|
|
|
|
|
CS 22A: Introduction to Python Fall 2021
6. amino_acids = ‘P,L,A,Y’
amino_list = amino_acids.split(“,”)
aa_list_1 = []
aa_list_2 = []
for amino in amino_list:
if amino == ‘P’ or amino == ‘A’:
aa_list_1.append(amino)
elif not amino == ‘Y’:
aa_list_2.append(amino)
print(aa_list_1)
print(aa_list_2)
amino |
amino == ‘P’ |
amino == ‘A’ |
not amino == ‘Y’ |
aa_list_1 |
aa_list_2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Note: Double check your work.
2021-12-06