L2 - StackingFlowing/CTProgramming GitHub Wiki

2.1 Some len()gthy stuff

print(len("My name is Douglas"))
#output 18

len() is short for length. As the name suggests, it finds the length of a string.

print(len("Hello"))     # This will print 5
print(len("No"))        # This will print 2

In the code that you saw at the top, we used len(dictionary) to find the length of the string "abcdefghijklmnopqrstuvwxyz". What value is it equal to?

2.2 What is % and how to sit the correct exam

We know that                7 / 3 = 2.333...
Is the same as saying       7 / 3 = 2 remainder 1

We can also write this as   7 % 3 = 1

In everyday context, % is a symbol to show a percentage.

In Python, % has nothing to do with percentage. % stands for modulo, which is just another way of saying:

What is the remainder if I divide something by something else?

Imagine that we want to equally split students into different groups. There is a total of 100 students, and each person will receive a number from 1 to 100. If we want to put them into 3 groups, we can let

  • Student #1 go to group 1 because 1 % 7 = 1;
  • Student #2 go to group 2 because 2 % 7 = 2;
  • Student #3 go to group 0 because 3 % 3 = 0;
  • Student #4 go to group 1 because 4 % 3 = 1;
  • ...
  • Student #100 go to group 1 because 100 % 3 = 1.

(If you find the name "group 0" confusing, you can rename it to "group 3". We cannot get 3 as remainder because 3 can be divided by itself again.)

You might wonder, Why don't we just divide by 3?

You will be right. But division only shows how many students will be in a group. Modulo shows you which group a chosen student will go to.

During an exam, aparticipants go to different rooms. They can know their room number by the following rule:

        room number = participant ID number % total amount of rooms

Which room should the participant go if:
a) their ID is 5001 and there are 51 rooms
b) their ID is 1680 and there are 111 rooms

You can solve the above problem using a calculator or use Python to type in print(5001 % 51) and print(1680 % 111). Participant in a) should go to room #3 and b) goes to room #15.