Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. """Lab 10: 10/15/19
  2. 1. YvonnaLeungLab10.py
  3. 2. Author: Yvonna Leung (CS22A, Section 2)
  4. 3. 10/15/19
  5. 4. #Purpose: Lab 10
  6. """
  7. """
  8. Create a list of numbers with at least 7 integer elements entered by the the user.
  9. Display the list.
  10.  
  11. I. Print the 1st, 3rd and 7th element
  12.  
  13. II. Create and display a slice/sub-list containing elements 5th to end of the list
  14.  
  15. III. Use the for loop to calculate the sum of all the numbers stored in the list as
  16. the loop traverses the list elements. Display the sum.
  17.  
  18. IV. Rewrite part III using a while loop.
  19.  
  20. """
  21.  
  22. def getUserList(num=7):
  23. return [1,2,3,4,5,6,7]
  24. mylist = []
  25. for i in range(num):
  26. n = int(input("Enter " + str(num) + " numbers followed by carriage returns."))
  27. mylist.append(n)
  28. return mylist
  29.  
  30. def getUserList2(num=7):
  31. mylist = []
  32. i = 0
  33. while i < num:
  34. n = int(input("Enter " + str(num) + " numbers followed by carriage returns."))
  35. mylist.append(n)
  36. i += 1
  37. return mylist
  38. """
  39. #Problem I
  40. mylist = getUserList()
  41.  
  42. print(mylist[0], mylist[2], mylist[6])
  43.  
  44. #Problem II
  45. mylist = getUserList()
  46. print(mylist[4:])
  47.  
  48.  
  49. #Problem III
  50. """
  51. # Iterator-based for-loop
  52. mylist = getUserList(3)
  53. total = 0
  54. for e in mylist:
  55. total += e
  56. print(total)
  57.  
  58. # WAYYY TOO EXPLICIT version of the above
  59. mylist = getUserList()
  60. it = iter(mylist)
  61. total = 0
  62. while True:
  63. try:
  64. e = next(it)
  65. total += e
  66. except StopIteration:
  67. break
  68. print(total)
  69.  
  70. # Range-based for-loop
  71. mylist = getUserList()
  72. total = 0
  73. for i in range(len(mylist)):
  74. total += mylist[i]
  75. print(total)
  76.  
  77. # Explicit while loop
  78. mylist = getUserList()
  79. total = 0
  80. i = 0
  81. while (i < len(mylist)):
  82. total += mylist[i]
  83. i += 1
  84. print(total)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement