Activity: Practice with Lists and While Loops

Create a new file list-and-while.py to save to your cs100/ch5 folder.

  1. Here is list a=["1", "2", "3", "4", "5"]. Use list comprehension to create list b consisting of the integers [1, 2, 3, 4, 5]. Print the list to test.

  2. Use list comprehension to create the list c consisting of all odd numbers within the range [0,20]. Print the list to test.

  3. Use list comprehension to create the list d consisting of all numbers divisible by 3 within the range [0, 100]. Print the list to test.

  4. Write code that sums up all the positive numbers entered by the user. When the user enters a negative number, the program displays the sum of the positive numbers and how many numbers were entered. Hint: Use a while loop to check if the number is positive or negative. Note that the negative number doesn’t contribute to the sum. An example execution is below:
    Enter next number (negative number to stop): 5
    Enter next number (negative number to stop): 10
    Enter next number (negative number to stop): 3
    Enter next number (negative number to stop): -1
    Sum of all positive numbers:  18
    
  5. Add more code to the while loop you wrote in the previous question in order to compute the average of all numbers entered by the user. An example output is as follows:
    Enter next number (negative number to stop): 10
    Enter next number (negative number to stop): 11
    Enter next number (negative number to stop): 9
    Enter next number (negative number to stop): 30
    Enter next number (negative number to stop): 18
    Enter next number (negative number to stop): -3
    Sum of all positive numbers:  78
    Average of all positive numbers:  15.6
    

If you finish early

  1. Modify your code to, in addition to printing the sum and average, printing out the mode (most often occuring value the user entered). Hint: use a dictionary.

How to submit

Submit your working python file to Moodle.