Modulo operator

by ashleyaelder on February 20, 2016

Here is a program that lists all numbers between 1 and 100, and prints an additional string when a number is a multiple of 4.

The modulo operator (%) finds the remainder after one number is divided by another.

For this example, the remainder is set to 0, because any number that is a multiple of 4 will have a remainder of 0 when divided by 4.

# prints multiples of 4

for n in range(1, 100):
    if n%4 == 0:
        print(n, " is a multiple of 4!")
    else:
        print(n)

Output:

1
2
3
4 is a multiple of 4!
5
6
7
8 is a multiple of 4!
9
10
11
12 is a multiple of 4!
13
14
15
16 is a multiple of 4!
17
18
19
20 is a multiple of 4!
21
22
23
24 is a multiple of 4!
25
26
27
28 is a multiple of 4!
29
30
31
32 is a multiple of 4!
33
34
35
36 is a multiple of 4!
37
38
39
40 is a multiple of 4!
41
42
43
44 is a multiple of 4!
45
46
47
48 is a multiple of 4!
49
50
51
52 is a multiple of 4!
53
54
55
56 is a multiple of 4!
57
58
59
60 is a multiple of 4!
61
62
63
64 is a multiple of 4!
65
66
67
68 is a multiple of 4!
69
70
71
72 is a multiple of 4!
73
74
75
76 is a multiple of 4!
77
78
79
80 is a multiple of 4!
81
82
83
84 is a multiple of 4!
85
86
87
88 is a multiple of 4!
89
90
91
92 is a multiple of 4!
93
94
95
96 is a multiple of 4!
97
98
99

{ 0 comments… add one now }

Leave a Comment

Next post: