Uploaded by kemesarosh

CS120 Exam 1 solutions

advertisement
CS120 Exam 1
Name_______________________sect___
1. Write code that will print the concatenation of a string and a number. (2 pts)
print(“age” + str(7))
2. What will be printed for the code in each letter? (5 pts)
name = “John Smith”
a.
b.
c.
d.
e.
print(name[1])
o
print(name[-1])
h
print(name[1:5])
ohn
print(name.index(“o”))
1
print(len(name)) 10
3. Write a list of 4 names and assign it to a variable called names. (2 pts)
names = [“John”, “Jane”, “Tom”, “Sue”]
4. Write code that will print the third item in the list above by index number. (2 pts)
print(names[2])
5. What will names[len(names) – 2] return? (2 pts)
“Tom”
6. Write code that will print the elements of the above list, each on a separate line, using the
range() function. (15 pts)
for i in range(len(names)):
print(names[i])
7. Write code that will print all of the elements of the above list, each on a separate line,
without using the range() function. (15 pts)
for name in names:
print(name])
8. What will be printed for the code in each letter? (5pts)
a. print(10 % 2)
0
b. print(10 ** 2)
100
c. print(10 / 2)
5
d. print(10.0 / 2)
5.0
e. print(5 + 2 * 2)
9
9. What value will the following code print? (5 pts)
num1 = 9
num2 = 7
num3 = 2
1
if num1 > num2 and num2 < num3:
print(num1)
elif num1 > num2 or num2 < num3:
print(num2)
else:
print(num3)
7
10. Write code that gets a course name from a user and assigns it to a variable, then adds it to
an empty list. It should allow multiple inputs from the user until the user enters “q”. (10
pts)
courses = []
run = True
while run:
course = input("Enter course: or q to quit")
if course == "q":
run = False
else:
courses.append(course)
11. Write a function that calculates weekly pay (hours * pay rate per hour). It should have
two parameters and return the result of the calculation as a variable. Write a line that calls
the function. (15 pts)
def get_weekly_pay(hours, rate):
pay = hours * rate
return pay
get_weekly_pay(40, 10.00)
12. Write code for getting the hours worked from user input and assign that value to a
variable named hours. Then get the position of the user from user input and assign that
value to a variable called position. Using if/elif/else, assign the pay rate for each position.
For a manager, pay should be number of hours worked multiplied by 50; for a developer,
pay should be number of hours worked multiplied by 35; for a tester, pay should be
number of hours worked multiplied by 20. (15 pts)
hours = int(input("Hours worked: "))
position = input("Position: ")
if position == "manager":
pay = hours * 50
elif position == "developer":
pay = hours * 35
else:
pay = hours * 20
2
Download