Problem Statement

Write a program to print the sum of the first n prime numbers, where n is provided as input from the user.

Handling Input

def main():

main()

Handling Input

def positive_input():
    x = int(input("Enter a positive integer: "))
    while x <= 0:
        print("Invalid input!")
        x = int(input("Enter a positive integer: "))
    return x

def main(): n = positive_input()
main()

Prime Numbers

def is_prime(n):

Prime Numbers

def is_prime(n):
    for i in range(2, n):

Prime Numbers

def is_prime(n):
    for i in range(2, n):
        if n % i == 0:
            # i equally divides n

Prime Numbers

def is_prime(n):
    for i in range(2, n):
        if n % i == 0:
            return False
    # what if we don't return false?

Prime Numbers

def is_prime(n):
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

Main Function

def main():
    n = positive_input()
    count = 0
    i = 2
    sum = 0
    while count < n:
        if is_prime(i):
            sum = sum + i
            count = count + 1
        i = i + 1
    print("The sum of the first {} prime numbers is {}".
           format(n, sum))

Full Program

def positive_input():
    x = int(input("Enter a positive integer: "))
    while x <= 0:
        print("Invalid input!")
        x = int(input("Enter a positive integer: "))
    return x

def is_prime(n): for i in range(2, n): if n % i == 0: return False return True
def main(): n = positive_input() count = 0 i = 2 sum = 0 while count < n: if is_prime(i): sum = sum + i count = count + 1 i = i + 1 print(f"The sum of the first {n} prime numbers is {sum}")
main()