Check a prime number

Check a prime number

MediumIf-Else Programs · 6 of 64

Write a Python program to check whether a given number is prime.

Input
2, 15, 17, 1
Output
2 is prime
15 is not prime
17 is prime
1 is not prime

Approach

  1. Numbers below 2 are not prime.
  2. Try divisors from 2 to the square root; if one divides exactly, it is not prime.

Solution

Python
def is_prime(n):    if n < 2:        return False    for d in range(2, int(n ** 0.5) + 1):        if n % d == 0:            return False    return True for n in [2, 15, 17, 1]:    if is_prime(n):        print(n, "is prime")    else:        print(n, "is not prime")
Output
2 is prime
15 is not prime
17 is prime
1 is not prime

Line by line

Lines 2-3

0 and 1 are not prime by definition.

Line 4

Checking divisors up to √n is enough.

Lines 5-6

Return early as soon as a divisor is found.

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs

Square a number divisible by 11

Square a number divisible by 11

EasyIf-Else Programs · 5 of 64

Write a Python program to print the square of a number if it is divisible by 11.

Input
121, 50
Output
121 is divisible by 11, square = 14641
50 is not divisible by 11

Approach

  1. Check n % 11 == 0; if true print n ** 2.

Solution

Python
for n in [121, 50]:    if n % 11 == 0:        print(f"{n} is divisible by 11, square = {n ** 2}")    else:        print(f"{n} is not divisible by 11")
Output
121 is divisible by 11, square = 14641
50 is not divisible by 11

Line by line

Line 3

The square is calculated inside the f-string.

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs

Check divisibility by 3 and 5

Check divisibility by 3 and 5

EasyIf-Else Programs · 4 of 64

Write a Python program to check whether a number is divisible by both 3 and 5.

Input
45, 30, 9, 10
Output
45 is divisible by 3 and 5
30 is divisible by 3 and 5
9 is divisible by 3 only
10 is divisible by 5 only

Approach

  1. Combine the two remainder checks with and.

Solution

Python
for n in [45, 30, 9, 10]:    if n % 3 == 0 and n % 5 == 0:        print(n, "is divisible by 3 and 5")    elif n % 3 == 0:        print(n, "is divisible by 3 only")    elif n % 5 == 0:        print(n, "is divisible by 5 only")
Output
45 is divisible by 3 and 5
30 is divisible by 3 and 5
9 is divisible by 3 only
10 is divisible by 5 only

Line by line

Line 2

and is true only when both conditions are true; this test must come first.

Lines 4-7

The other branches report partial matches.

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs

Assign grades from marks

Assign grades from marks

EasyIf-Else Programs · 3 of 64

Write a Python program to assign a grade from total marks: below 40 Fail, 40-49 C, 50-59 B, 60-69 A, 70-79 A+, 80-89 A++, 90-100 Excellent, anything else Invalid.

Input
35, 47, 68, 85, 100, 105
Output
35 -> Fail
47 -> C
68 -> A
85 -> A++
100 -> Excellent
105 -> Invalid marks

Approach

  1. Reject values outside 0-100 first.
  2. Then test the ranges from the highest down, so each elif only needs a lower bound.

Solution

Python
def grade(marks):    if marks < 0 or marks > 100:        return "Invalid marks"    elif marks >= 90:        return "Excellent"    elif marks >= 80:        return "A++"    elif marks >= 70:        return "A+"    elif marks >= 60:        return "A"    elif marks >= 50:        return "B"    elif marks >= 40:        return "C"    else:        return "Fail" for m in [35, 47, 68, 85, 100, 105]:    print(m, "->", grade(m))
Output
35 -> Fail
47 -> C
68 -> A
85 -> A++
100 -> Excellent
105 -> Invalid marks

Line by line

Lines 2-3

Invalid input is handled first so the other branches can assume 0 to 100.

Lines 4-15

Because Python stops at the first true branch, testing from the top down means marks >= 80 only runs for marks below 90.

Lines 16-17

Anything below 40 falls through to else.

Note

The original task listed “marks > 40: Fail”, which would fail almost everyone. It should be marks below 40.

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs

Numbers from 1 to 30 divisible by 3

Numbers from 1 to 30 divisible by 3

EasyIf-Else Programs · 2 of 64

Write a Python program to print all the numbers from 1 to 30 that are divisible by 3.

Output
3 6 9 12 15 18 21 24 27 30 

Approach

  1. Loop from 1 to 30 and print a number only when n % 3 == 0.

Solution 1: loop with if

Python
for n in range(1, 31):    if n % 3 == 0:        print(n, end=" ")print()
Output
3 6 9 12 15 18 21 24 27 30 

Line by line

Line 1

range(1, 31) stops before 31, so 30 is included.

Line 3

end=" " keeps the numbers on one line.

Line 4

An empty print() ends the line.

Solution 2: range with a step

Python
print(list(range(3, 31, 3)))
Output
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

Line by line

Line 1

Starting at 3 with a step of 3 produces only multiples of 3, so no if is needed.

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs

Check if a number is divisible by 3

Check if a number is divisible by 3

EasyIf-Else Programs · 1 of 64

Write a Python program to check whether a given number is divisible by 3.

Input
21, 22
Output
21 is divisible by 3
22 is not divisible by 3

Approach

  1. A number is divisible by 3 when the remainder n % 3 is 0.

Solution

Python
for n in [21, 22]:    if n % 3 == 0:        print(n, "is divisible by 3")    else:        print(n, "is not divisible by 3")
Output
21 is divisible by 3
22 is not divisible by 3

Line by line

Line 1

The loop tests two sample numbers so both branches run.

Line 2

% gives the remainder; a remainder of 0 means an exact division.

Lines 4-5

else handles every other case.

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs

Lowercase letter diamond

Python Practice › Loop Programs › Program 90

Lowercase letter diamond

MediumLoop Programs · 90 of 90

Write a Python program to print the letters a to y in rows of 1, 3, 5, 7, 5, 3, 1 letters.

Output
a
b c d
e f g h i
j k l m n o p
q r s t u
v w x
y

Approach

  1. Same idea as the previous program with different row sizes.

Solution

Python
import string letters = iter(string.ascii_lowercase)for size in [1, 3, 5, 7, 5, 3, 1]:    print(" ".join(next(letters) for _ in range(size)))
Output
a
b c d
e f g h i
j k l m n o p
q r s t u
v w x
y

Line by line

Line 3

An iterator hands out the letters one at a time across all rows.

Line 5

next(letters) takes the following letter each time it is called.

Learn the concept

New to this topic? Read the lesson, then come back.

More loop programs

← All 90 Loop Programs

Uppercase letter diamond

Python Practice › Loop Programs › Program 89

Uppercase letter diamond

MediumLoop Programs · 89 of 90

Write a Python program to print the letters A to Y in rows of 1, 2, 3, 4, 5, 4, 3, 2, 1 letters.

Output
A
B C
D E F
G H I J
K L M N O
P Q R S
T U V
W X
Y

Approach

  1. Keep a letter counter and print the right number of letters on each row.

Solution

Python
sizes = [1, 2, 3, 4, 5, 4, 3, 2, 1]code = ord("A")for size in sizes:    row = [chr(code + i) for i in range(size)]    print(" ".join(row))    code += size
Output
A
B C
D E F
G H I J
K L M N O
P Q R S
T U V
W X
Y

Line by line

Line 2

ord("A") is 65; adding to it walks through the alphabet.

Line 4

Each row takes the next size letters.

Learn the concept

New to this topic? Read the lesson, then come back.

More loop programs

← All 90 Loop Programs

Maximum number in a list

Python Practice › Loop Programs › Program 88

Maximum number in a list

EasyLoop Programs · 88 of 90

Write a Python program to find the largest number in a list using a loop.

Input
[12, 14, 45, 88, 63, 97, 88]
Output
Maximum number: 97

Approach

  1. Assume the first item is the largest and replace it whenever a bigger one appears.

Solution

Python
numbers = [12, 14, 45, 88, 63, 97, 88]largest = numbers[0]for n in numbers[1:]:    if n > largest:        largest = nprint("Maximum number:", largest)
Output
Maximum number: 97

Line by line

Line 2

Starting from the first item works for negative numbers too, unlike starting from 0.

Learn the concept

New to this topic? Read the lesson, then come back.

More loop programs

← All 90 Loop Programs

Copy and sort descending

Python Practice › Loop Programs › Program 87

Copy and sort descending

EasyLoop Programs · 87 of 90

Write a Python program to copy elements from one list into an empty list and print them in descending order.

Input
[2, 5, 8, 0, 1, 4]
Output
[8, 5, 4, 2, 1, 0]

Approach

  1. Copy with a loop, then sort with reverse=True.

Solution

Python
a = [2, 5, 8, 0, 1, 4]b = []for x in a:    b.append(x)b.sort(reverse=True)print(b)
Output
[8, 5, 4, 2, 1, 0]

Learn the concept

New to this topic? Read the lesson, then come back.

More loop programs

← All 90 Loop Programs