Python Essentials Classroom Series – 29/Jul/2021

Functions

  • Function is a block of statements/instructions which enable reusability
  • The syntax of function used a def keyword
def <function-name>(arguments):
    # function code
  • Sample code to print all the prime numbers from 10 to 1000
def is_prime(number: int):
    """
    This function finds if the number is prime
    Returns:
        True if prime false otherwise
    """
    for index in range(2, number):
        if number%index == 0:
            return False
    return True


for index in range(10, 1000):
    if is_prime(number=index):
        print(index)

def is_prime(number: int):
    """
    This function finds if the number is prime
    Returns:
        True if prime false otherwise
    """
    for index in range(2, number):
        if number%index == 0:
            return False
    return True


# https://projecteuler.net/problem=7
prime_count = 0
number = 2
while prime_count != 10001:
    if is_prime(number):
        prime_count += 1
    number += 1

print(number-1)
    

def is_prime(number: int):
    """
    This function finds if the number is prime
    Returns:
        True if prime false otherwise
    """

    for index in range(2, (number//2) + 1):
        if number%index == 0:
            return False
    return True


# https://projecteuler.net/problem=10

sum = 0
max_number = 2000000 
print("Calculating prime numbers")
for index in range(2, max_number):
    print(index, end=',', sep='')
    if is_prime(index):
        sum += index
print()
print(f"sum of all prime numbers till {max_number} is {sum}")

  • Some sample functions
def is_even(number:int):
    """
    This function verifies if the number is even or not

    Returns:
        True if even false other wise
    """
    return number % 2 == 0

def is_prime(number: int):
    """
    This function finds if the number is prime
    Returns:
        True if prime false otherwise
    """
    for index in range(2, (number//2) + 1):
        if number%index == 0:
            return False
    return True

def factorial(number: int):
    """
    This function calculates the factorial of a number
    """
    result = 1
    for index in range(1,number+1):
        result *= index
    return result

def simple_interest(principal: float, rate: float, time: int):
    """
    This function will calculate the simple interest
    """
    return (principal * time * rate / 100)

def compound_interest(principal: float, rate: float, time: int):
    pass


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin