0
0
DSA Pythonprogramming~10 mins

Check if Number is Prime in DSA Python - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check if a number is prime by testing divisibility starting from 2.

DSA Python
def is_prime(num):
    if num <= 1:
        return False
    for i in range(2, [1]):
        if num % i == 0:
            return False
    return True
Drag options to blanks, or click blank then click option'
Anum
Bnum + 1
Cnum // 2 + 1
Dint(num ** 0.5) + 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using num + 1 includes num itself, incorrectly returning False for primes.
Using int(num ** 0.5) + 1 is an optimization but not for this easy task.
2fill in blank
medium

Complete the code to optimize prime check by testing divisors only up to the square root of the number.

DSA Python
def is_prime(num):
    if num <= 1:
        return False
    for i in range(2, [1]):
        if num % i == 0:
            return False
    return True
Drag options to blanks, or click blank then click option'
Anum // 2
Bnum
Cint(num ** 0.5) + 1
Dnum // 3
Attempts:
3 left
💡 Hint
Common Mistakes
Checking up to num wastes time.
Using num // 2 is less efficient.
3fill in blank
hard

Fix the error in the code to correctly check if a number is prime by returning False immediately when a divisor is found.

DSA Python
def is_prime(num):
    if num <= 1:
        return False
    for i in range(2, int(num ** 0.5) + 1):
        if num [1] i == 0:
            return False
    return True
Drag options to blanks, or click blank then click option'
A%
B//
C*
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using == instead of % causes a syntax error.
Using // or * does not check divisibility.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps numbers to True if prime, False otherwise, for numbers 2 to 10.

DSA Python
primes = {num: is_prime(num) for num in [1] if num [2] 1}
Drag options to blanks, or click blank then click option'
Arange(2, 11)
Brange(1, 11)
C>
D>=
Attempts:
3 left
💡 Hint
Common Mistakes
Using range(1, 11) includes 1 which is not prime.
Using >= includes 1 which is not prime.
5fill in blank
hard

Fill all three blanks to create a list comprehension that lists all prime numbers between 10 and 20.

DSA Python
prime_numbers = [[1] for n in [2] if is_prime([3])]
Drag options to blanks, or click blank then click option'
An
Brange(10, 21)
Drange(11, 20)
Attempts:
3 left
💡 Hint
Common Mistakes
Using range(11, 20) excludes 10 and 20.
Using different variables in the comprehension causes errors.