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.
  2. Use a list comprehension to create a list of all odd numbers in the range [0,50]. Print the list to test it.
  3. Use a list comprehension to create a list of all numbers divisible by 4 within the range [0,100], that is, the list 0,4,8,..,100. Print the list to test.
  4. Use a list comprehension to create a list of size 10 with alternating True/False values, beginning with True. Print the list to test it. It should appear as [True,False,True,False,True,False,True,False,True,False]
  5. Use a list comprehension to create a list of the squares of the first 20 positive integers, that is, the list 1,4,9,25,36, etc. Print the list to test it.

How to submit

Submit your working python file to Moodle.