Uploaded by kemesarosh

CS120 MidTerm Exam Review -ANSWERS

advertisement
CS120 Midterm Exam Review
Name_______________________
Due Thursday 10/11 for 20 points extra credit.
Write code for each of the following:
1. Assign a string to a variable name.
name = “Joseph”
2. Print the number of characters in the above string.
print(len(name)) or print len(name)
3. Concatenate a string and a number.
“age: ” + str(20)
4. What will be printed for each of the following:
a. print(3**3) 27
b. print(4 + 5 * 2) 14
c. print(20 / 10) 2
d. print(20.0 / 2) 10.0
e. print(5 % 2) 1
5. Using a for loop and the range function, print the numbers 1 – 10.
6. Using a for loop and the range function, print the even numbers 4 – 16.
7. Use a while loop to print the numbers 1 – 10.
8. Use a while loop to print the numbers 10 – 1.
9. Make a list of 5 names and assign it to a variable name.
names = [“joe”, “tom”, “jane”, “amy”, “cathy”]
10. Add a value to the list.
names.append(“john”)
11. Print the third item in the list.
print(names[2])
12. Get the index of the second item.
names.index("tom")
13. Loop through the list and print out each name on a separate line using the for-in loop.
14. Loop through the list and print out each name on a separate line using the for-range loop.
15. How many errors are in this Python code?
16. Write an example of getting input from a user: ask for the user’s name and assign it to a
variable.
17. Write the code for getting a score from user input, then, using if/elif/else, compare the
input to a range of scores to determine a letter grade, which is assigned to a variable
called grade.
18. Write a function that calculates the area of a rectangle (length multiplied by width). It
should have two parameters and return the result of the calculation as a variable. Call the
function with appropriate parameter arguments and print the result.
**Know how to get continuous input from user until the user enters “q” to quit:
Download