Square or cube depending on divisibility

Square or cube depending on divisibility

EasyIf-Else Programs · 11 of 64

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.

Input
4, 9, 6, 7
Output
4 square: 16
9 cube: 729
6 square: 36
7 is divisible by neither 2 nor 3

Approach

  1. Check divisibility by 2 first, then by 3.

Solution

Python
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")
Output
4 square: 16
9 cube: 729
6 square: 36
7 is divisible by neither 2 nor 3

Line by line

Lines 2-5

6 is divisible by both; because the % 2 test comes first, it prints the square.

Tip

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.

More if-else programs

← All 64 If-Else Programs

Validate a user id in a list

Validate a user id in a list

EasyIf-Else Programs · 10 of 64

Write a Python program to check whether a user id is present in a list of user ids.

Input
ids = [101, 102, 205, 309]; check 205 and 404
Output
205 is a valid user id
404 is not a valid user id

Approach

  1. Use the in operator to test membership.

Solution

Python
user_ids = [101, 102, 205, 309] for uid in [205, 404]:    if uid in user_ids:        print(uid, "is a valid user id")    else:        print(uid, "is not a valid user id")
Output
205 is a valid user id
404 is not a valid user id

Line by line

Line 4

in checks every item of the list and returns True or False.

Learn the concept

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

More if-else programs

← All 64 If-Else Programs

Check username and password

Check username and password

EasyIf-Else Programs · 9 of 64

Write a Python program to check login with a given username and password.

Input
("admin", "Admin@123"), ("admin", "wrong"), ("guest", "x")
Output
admin -> Login successful
admin -> Wrong password
guest -> Unknown user

Approach

  1. Compare both values; give a different message for a wrong user and a wrong password.

Solution

Python
USERNAME = "admin"PASSWORD = "Admin@123" def login(user, pwd):    if user == USERNAME and pwd == PASSWORD:        return "Login successful"    elif user == USERNAME:        return "Wrong password"    else:        return "Unknown user" for u, p in [("admin", "Admin@123"), ("admin", "wrong"), ("guest", "x")]:    print(u, "->", login(u, p))
Output
admin -> Login successful
admin -> Wrong password
guest -> Unknown user

Line by line

Lines 1-2

The expected credentials are constants (upper-case names).

Line 5

Both must match, so the checks are joined with and.

Line 7

Reaching this line means the password was wrong for a known user.

Watch out

Real applications never store plain-text passwords; they store a salted hash and compare hashes. This program only practises if-else logic.

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 in the Fibonacci series

Check if a number is in the Fibonacci series

MediumIf-Else Programs · 8 of 64

Write a Python program to check whether a given number is part of the Fibonacci series (1, 1, 2, 3, 5, 8, 13, …).

Input
8, 10
Output
8 is a Fibonacci number
10 is not a Fibonacci number

Approach

  1. Generate Fibonacci numbers until they reach or pass the given number.
  2. If one of them equals the number, it is in the series.

Solution

Python
def is_fibonacci(n):    a, b = 0, 1    while a < n:        a, b = b, a + b    return a == n for n in [8, 10]:    print(n, "is a Fibonacci number" if is_fibonacci(n) else "is not a Fibonacci number")
Output
8 is a Fibonacci number
10 is not a Fibonacci number

Line by line

Lines 3-4

Keep stepping through the series while the current value is smaller than n.

Line 5

When the loop stops, a is either equal to n (found) or the first value past it (not found).

Learn the concept

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

More if-else programs

← All 64 If-Else Programs

Check odd or even

Check odd or even

EasyIf-Else Programs · 7 of 64

Write a Python program to check whether a number is odd or even.

Input
8, 13, 0
Output
8 is even
13 is odd
0 is even

Approach

  1. Even numbers leave remainder 0 when divided by 2.

Solution

Python
for n in [8, 13, 0]:    if n % 2 == 0:        print(n, "is even")    else:        print(n, "is odd")
Output
8 is even
13 is odd
0 is even

Line by line

Line 2

0 % 2 is 0, so 0 is correctly reported as even.

Learn the concept

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

More if-else programs

← All 64 If-Else Programs

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