ByteBoard Notes Notes

Display all prime numbers in a range using a function is_prime()

Computer Science XII · Experiment 01 of 29 · Python

12-CSPython programs
Expt. No.01
Page No.2

Prime numbers with a function

Aim

To write a Python program with a user-defined function is_prime(n) that returns True or False, and use it to display all prime numbers in a given range.

Concepts used

Algorithm

  1. Define is_prime(n): return False if n < 2; return False if any number from 2 to n−1 divides n; otherwise return True.
  2. Input the lower and upper limits.
  3. For each number in the range, call is_prime() and print the number if it returns True.

Program

# Display all prime numbers in a range using a function def is_prime(n):    # returns True if n is prime, else False    if n < 2:        return False    for i in range(2, n):        if n % i == 0:            return False    return True lower = int(input("Enter the lower limit: "))upper = int(input("Enter the upper limit: "))print("Prime numbers from", lower, "to", upper, ":")for num in range(lower, upper + 1):    if is_prime(num):        print(num, end=" ")print()

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python primes_with_function.py
Enter the lower limit: 10 Enter the upper limit: 50 Prime numbers from 10 to 50 : 11 13 17 19 23 29 31 37 41 43 47

✓ Printed by running this program, not typed by hand.

Result

The function was called once for every number from 10 to 50, and the 11 primes 11, 13, 17, 19, 23, 29, 31, 37, 41, 43 and 47 were displayed.

Viva voce: what the examiner may ask

01What is the difference between a parameter and an argument?

A parameter is the name in the function definition (n); an argument is the value passed in the call (num).

02What happens when a return statement runs inside the loop?

The function ends at once and sends the value back; the rest of the loop does not run.

03What does a function return if it has no return statement?

None.

Variations for the lab test

  1. Write a function that returns the number of primes in a range.
  2. Write is_perfect(n) and display the perfect numbers below 1000.
  3. Write a function that returns the sum of the digits of a number.
! Common mistake Writing print(True) inside the function instead of return True: the if is_prime(num): test then receives None and no prime is ever displayed.
Back to the 12-CS index