Python Programming Examples: Function

Python Function Examples

Below are some Python function examples along with their solutions, descriptions, and unique features that each implementation teaches.

Example 1: Factorial of a Number

Question: Write a Python script named factorial.py that asks the user for a number and prints the factorial of that number.

def factorial(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

number = int(input("Enter a number: "))
print(f"Factorial of {number} is {factorial(number)}")

Output:

C:\> python factorial.py
Enter a number: 5
Factorial of 5 is 120
C:\>

Description: The factorial(n) function multiplies all the numbers from 1 to n to calculate the factorial. The program then takes user input, calls the function, and prints the factorial of the number.

Unique Feature: This implementation demonstrates the use of a for loop to iterate from 2 to n, which is efficient and easy to understand. It highlights the importance of iterative multiplication in calculating factorials.

💡

Hint: Factorials grow rapidly with the increase in numbers, which makes them important in combinatorial mathematics and probability theory. However, Python's integers can handle large values, so you don't need to worry about overflow as in other programming languages.

Example 2: Find the Largest Number in a List

Question: Create a Python script named find_largest.py that takes a list of numbers as input and prints the largest number in the list.

def find_largest(numbers):
    largest = numbers[0]
    for number in numbers:
        if number > largest:
            largest = number
    return largest

numbers = list(map(int, input("Enter numbers separated by space: ").split()))
print(f"The largest number is {find_largest(numbers)}")

Output:

C:\> python find_largest.py
Enter numbers separated by space: 10 20 30 5
The largest number is 30
C:\>

Description: The find_largest(numbers) function iterates through a list and compares each number to find the largest one. The program asks the user for a list of numbers, calls the function, and prints the largest number.

Unique Feature: This implementation teaches how to use comparison within a loop to determine the maximum value in a list. It also introduces list input handling using map() and split().

💡

Tip: Using the max() function is an alternative way to find the largest number in a list. However, implementing the logic manually, as shown here, helps you understand the underlying process.

Example 3: Convert Celsius to Fahrenheit

Question: Write a Python script named celsius_to_fahrenheit.py that converts a temperature from Celsius to Fahrenheit.

def celsius_to_fahrenheit(celsius):
    return (celsius * 9/5) + 32

celsius = float(input("Enter temperature in Celsius: "))
print(f"{celsius}°C is equal to {celsius_to_fahrenheit(celsius)}°F")

Output:

C:\> python celsius_to_fahrenheit.py
Enter temperature in Celsius: 25
25.0°C is equal to 77.0°F
C:\>

Description: The celsius_to_fahrenheit(celsius) function applies the formula (celsius * 9/5) + 32 to convert the temperature. The program gets the Celsius value from the user, converts it, and prints the Fahrenheit equivalent.

Unique Feature: This example emphasizes the simplicity and importance of using arithmetic operations within functions to perform conversions.

Example 4: Calculate the Area of a Circle

Question: Create a Python script named area_of_circle.py that calculates the area of a circle given its radius.

import math

def area_of_circle(radius):
    return math.pi * (radius ** 2)

radius = float(input("Enter the radius of the circle: "))
print(f"The area of the circle is {area_of_circle(radius)}")

Output:

C:\> python area_of_circle.py
Enter the radius of the circle: 5
The area of the circle is 78.53981633974483
C:\>

Description: The area_of_circle(radius) function calculates the area using the formula πr² where π is accessed from the math module. The user inputs the radius, and the program calculates and prints the area.

Unique Feature: This implementation highlights the use of the math module for accessing mathematical constants like π. It also demonstrates the power of Python's built-in libraries for performing common mathematical operations.

💡

Trivia: The value of π is a mathematical constant that represents the ratio of a circle's circumference to its diameter. The symbol π has been used for this purpose for over 250 years.

Example 5: Sum of First N Natural Numbers

Question: Write a Python script named sum_of_n_numbers.py that calculates the sum of the first n natural numbers.

def sum_of_n_numbers(n):
    return n * (n + 1) // 2

n = int(input("Enter a number: "))
print(f"The sum of the first {n} natural numbers is {sum_of_n_numbers(n)}")

Output:

C:\> python sum_of_n_numbers.py
Enter a number: 10
The sum of the first 10 natural numbers is 55
C:\>

Description: The sum_of_n_numbers(n) function calculates the sum using the formula n * (n + 1) // 2. The user provides a number n, and the program prints the sum of the first n natural numbers.

Unique Feature: This example introduces the formula for the sum of an arithmetic series and shows how such formulas can simplify code and improve efficiency compared to iterative summation.

💡

Tip: The formula n * (n + 1) // 2 is a quick way to calculate the sum of the first n natural numbers. It avoids the need for loops and is very efficient even for large values of n.

Example 6: Check if a Number is Prime

Question: Create a Python script named is_prime.py that checks whether a given number is prime or not.

import math

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

number = int(input("Enter a number: "))
print(f"{number} is {'a prime number' if is_prime(number) else 'not a prime number'}")

Output:

C:\> python is_prime.py
Enter a number: 17
17 is a prime number
C:\>

Description: The is_prime(n) function checks if the number has any divisors other than 1 and itself by iterating up to the square root of n. The program then informs the user if the number is prime or not.

Unique Feature: This implementation teaches an optimized approach to checking for primality by reducing the number of iterations required, leveraging the mathematical property that a larger factor of a number must be greater than its square root.

💡

Tip: Checking up to the square root of n significantly reduces the number of iterations needed to determine primality. This is a key optimization in many algorithms involving divisibility checks.

Example 7: Reverse a String

Question: Write a Python script named reverse_string.py that takes a string as input and prints the reversed string.

def reverse_string(s):
    return s[::-1]

string = input("Enter a string: ")
print(f"Reversed string is {reverse_string(string)}")

Output:

C:\> python reverse_string.py
Enter a string: Python
Reversed string is nohtyP
C:\>

Description: The reverse_string(s) function uses slicing to reverse the input string. The program takes a string from the user and prints its reversed form.

Unique Feature: This example demonstrates the use of Python's powerful slicing feature to manipulate sequences efficiently, emphasizing the simplicity and readability of Python code.

💡

Tip: Slicing is not only useful for reversing strings but also for extracting substrings, skipping elements, and more. Mastering slicing will greatly enhance your Python skills.

Example 8: Find the GCD of Two Numbers

Question: Create a Python script named gcd.py that calculates the greatest common divisor (GCD) of two numbers.

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
print(f"The GCD of {a} and {b} is {gcd(a, b)}")

Output:

C:\> python gcd.py
Enter the first number: 48
Enter the second number: 18
The GCD of 48 and 18 is 6
C:\>

Description: The gcd(a, b) function uses the Euclidean algorithm to find the GCD. The program prompts the user for two numbers and prints their GCD.

Unique Feature: This example illustrates the use of the Euclidean algorithm for efficiently finding the GCD, highlighting how swapping and modulo operations can be combined to solve mathematical problems.

💡

Trivia: The Euclidean algorithm, which dates back to ancient Greece, is one of the oldest known algorithms and is still widely used in modern computing for tasks involving divisibility and modular arithmetic.

Example 9: Calculate the Sum of a List of Numbers

Question: Write a Python script named sum_of_list.py that takes a list of numbers and calculates their sum.

def sum_of_list(numbers):
    total = 0
    for number in numbers:
        total += number
    return total

numbers = list(map(int, input("Enter numbers separated by space: ").split()))
print(f"The sum of the numbers is {sum_of_list(numbers)}")

Output:

C:\> python sum_of_list.py
Enter numbers separated by space: 1 2 3 4 5
The sum of the numbers is 15
C:\>

Description: The sum_of_list(numbers) function iterates through the list, adding each element to calculate the total sum. The program then displays the sum to the user.

Unique Feature: This implementation reinforces the concept of iteration and accumulation within a loop, demonstrating a fundamental pattern in programming for summing values.

💡

Tip: Python provides a built-in function sum() that can achieve the same result with less code. However, understanding the underlying loop logic is essential for more complex summation tasks.

Example 10: Calculate the Square of a Number

Question: Create a Python script named square.py that calculates the square of a given number.

def square(n):
    return n ** 2

number = int(input("Enter a number: "))
print(f"The square of {number} is {square(number)}")

Output:

C:\> python square.py
Enter a number: 7
The square of 7 is 49
C:\>

Description: The square(n) function simply returns n ** 2, the square of the input number. The user provides a number, and the program outputs its square.

Unique Feature: This example highlights the use of Python's exponentiation operator ** for performing power calculations, emphasizing the simplicity and expressiveness of the language.

💡

Hint: Using the exponentiation operator ** is the most direct way to calculate powers in Python. This operator supports any integer power, making it a versatile tool for mathematical computations.