Square or cube depending on divisibility
Write a Python program that prints the square of a number if it is divisible by 2, or its cube if it is divisible by 3.
4, 9, 6, 7
4 square: 16 9 cube: 729 6 square: 36 7 is divisible by neither 2 nor 3
Approach
- Check divisibility by 2 first, then by 3.
Solution
for n in [4, 9, 6, 7]: if n % 2 == 0: print(n, "square:", n ** 2) elif n % 3 == 0: print(n, "cube:", n ** 3) else: print(n, "is divisible by neither 2 nor 3")4 square: 16 9 cube: 729 6 square: 36 7 is divisible by neither 2 nor 3
Line by line
6 is divisible by both; because the % 2 test comes first, it prints the square.
To print both for numbers like 6, use two separate if statements instead of if / elif.
Learn the concept
New to this topic? Read the lesson, then come back.