Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Lab 10: 10/15/19
- 1. YvonnaLeungLab10.py
- 2. Author: Yvonna Leung (CS22A, Section 2)
- 3. 10/15/19
- 4. #Purpose: Lab 10
- """
- """
- Create a list of numbers with at least 7 integer elements entered by the the user.
- Display the list.
- I. Print the 1st, 3rd and 7th element
- II. Create and display a slice/sub-list containing elements 5th to end of the list
- III. Use the for loop to calculate the sum of all the numbers stored in the list as
- the loop traverses the list elements. Display the sum.
- IV. Rewrite part III using a while loop.
- """
- def getUserList(num=7):
- return [1,2,3,4,5,6,7]
- mylist = []
- for i in range(num):
- n = int(input("Enter " + str(num) + " numbers followed by carriage returns."))
- mylist.append(n)
- return mylist
- def getUserList2(num=7):
- mylist = []
- i = 0
- while i < num:
- n = int(input("Enter " + str(num) + " numbers followed by carriage returns."))
- mylist.append(n)
- i += 1
- return mylist
- """
- #Problem I
- mylist = getUserList()
- print(mylist[0], mylist[2], mylist[6])
- #Problem II
- mylist = getUserList()
- print(mylist[4:])
- #Problem III
- """
- # Iterator-based for-loop
- mylist = getUserList(3)
- total = 0
- for e in mylist:
- total += e
- print(total)
- # WAYYY TOO EXPLICIT version of the above
- mylist = getUserList()
- it = iter(mylist)
- total = 0
- while True:
- try:
- e = next(it)
- total += e
- except StopIteration:
- break
- print(total)
- # Range-based for-loop
- mylist = getUserList()
- total = 0
- for i in range(len(mylist)):
- total += mylist[i]
- print(total)
- # Explicit while loop
- mylist = getUserList()
- total = 0
- i = 0
- while (i < len(mylist)):
- total += mylist[i]
- i += 1
- print(total)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement