Check if a number is in a list

Check if a number is in a list

EasyIf-Else Programs · 13 of 64

Write a Python program to check whether a given number is present in a list of numbers.

Input
numbers = [12, 45, 7, 89, 33]; check 89 and 50
Output
89 found at index 3
50 is not in the list

Approach

  1. Use in; use index() to also report the position.

Solution

Python
numbers = [12, 45, 7, 89, 33] for n in [89, 50]:    if n in numbers:        print(n, "found at index", numbers.index(n))    else:        print(n, "is not in the list")
Output
89 found at index 3
50 is not in the list

Line by line

Line 5

index() is safe here because the if already confirmed the number is present.

Learn the concept

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

More if-else programs

← All 64 If-Else Programs

Interview process with nested if-else

Interview process with nested if-else

EasyIf-Else Programs · 12 of 64

Write a Python program that describes a two-round interview: a candidate who passes round 1 can take round 2, and passing both means placed. Use nested if-else.

Input
("passed", "passed"), ("passed", "failed"), ("failed", "-")
Output
--- round1=passed, round2=passed
Round 1 cleared
Round 2 cleared: you are placed
--- round1=passed, round2=failed
Round 1 cleared
Failed in round 2, please try next time
--- round1=failed, round2=-
Failed in round 1, please try next time

Approach

  1. The outer if checks round 1.
  2. Only inside it does an inner if check round 2.

Solution

Python
def interview(round1, round2):    if round1 == "passed":        print("Round 1 cleared")        if round2 == "passed":            print("Round 2 cleared: you are placed")        else:            print("Failed in round 2, please try next time")    else:        print("Failed in round 1, please try next time") for r1, r2 in [("passed", "passed"), ("passed", "failed"), ("failed", "-")]:    print(f"--- round1={r1}, round2={r2}")    interview(r1, r2)
Output
--- round1=passed, round2=passed
Round 1 cleared
Round 2 cleared: you are placed
--- round1=passed, round2=failed
Round 1 cleared
Failed in round 2, please try next time
--- round1=failed, round2=-
Failed in round 1, please try next time

Line by line

Line 2

The outer condition decides whether round 2 matters at all.

Lines 4-7

The inner if-else only runs for candidates who passed round 1.

Lines 8-9

A failed round 1 skips round 2 entirely.

Learn the concept

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

More if-else programs

← All 64 If-Else Programs

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