Additional Session 1 Exercises#

Swapping the contents of variables#

Explain what the overall effect of this code is:

left = 'L'
right = 'R'

temp = left
left = right
right = temp

Compare it to:

left, right = right, left

Do they always do the same thing? Which do you find easier to read?

In-Place Operators#

Python (and most other languages in the C family) provides in-place operators that work like this:

x = 1  # original value
x += 1 # add one to x, assigning result back to x
x *= 3 # multiply x by 3
print(x)
6

Write some code that sums the positive and negative numbers in a list separately, using in-place operators. Do you think the result is more or less readable than writing the same without in-place operators?

Here pass means “don’t do anything”. In this particular case, it’s not actually needed, since if num == 0 neither sum needs to change, but it illustrates the use of elif and pass.


Turn a String into a List#

Use a for-loop to convert the string “hello” into a list of letters: [“h”, “e”, “l”, “l”, “o”]


Reverse a String#

Knowing that two strings can be concatenated using the + operator, write a loop that takes a string and produces a new string with the characters in reverse order, so 'Newton' becomes 'notweN'.