An Introduction to Python

Loops

This notebook contains the programming exercises for An Introduction to Python: Loops.

Exercises

Do the following problems.

Jupyter Notebook Shortcuts:

There are two modes when a cell is highlighted.

Command Mode: Press ESC to activate. The cell has a blue border if this mode is active. In this mode, you can add, delete, create, copy and paste cells.

  • create a new cell above the current cell: a
  • create a new cell below the current cell: b
  • delete the current cell: dd
  • change the current cell’s type to “Code”: y
  • change the current cell’s type to “Markdown”: m

Edit Mode: Press ENTER to activate. The cell has a green border if this mode is active. In this mode, you can edit and type text into the cell.

  • execute the current cell and create a new cell: SHIFT + ENTER

Provide an equivalent Python range() expression for each of the following integer sequences.

(a) 1,2,3,4,5

(b) 5,4,3,2,1

(c) 5,10,15,20,25,30

(d) 30,25,20,15,10,5

(e) Empty sequence

In [ ]:
 
In [ ]:
 

Write a for loop that prints out all even numbers between 1 and 24 separated by spaces. Use python's modulo (%) operator

In [ ]:
 

Write a for loop that prints out the numbers in descending order from 20 to 1 separated by spaces.

In [ ]:
 

Write a while loop to print out all multiples of 3 between 3 and 30 separated by spaces.

In [ ]:
 

Rewrite the following code fragment so it eliminates the continue statement. Your new code’s logic should be simpler than the logic of this fragment.

x = 5
while x > 0:
    y = int(input())
    if y == 25:
        continue
    x -= 1
    print('x =', x)
In [ ]:
 

Suppose we like to generate the following sequence of numbers: Given a positive starting number $n$.

- If the current term is even, the next term is the current term divided by 2.

- If the current term is odd, the next term is the $3$ times the current term plus 1.

Generate the sequence until the sequence reaches a $1$. The famous Collatz Conjecture says that this sequence will always reach 1 regardless of the initial starting value.

Example: n = 12, 6, 3, 10, 5, 16, 8, 4, 2, 1.

Write a segment of code that ask the user to input a positive integer n and use a while loop that generates the Collatz sequence.

In [ ]:
 

Write nested loops that generate the following:

a)

2 2 2 2

4 4 4 4

6 6 6 6

8 8 8 8

b)

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

In [ ]:
 

Use the code above for generating the Collatz sequence and write a segment of code that prints out the Collatz sequence for each number from 1-10.

In [ ]: