Back to all posts

Functions and Modules in Python

def Grreting(name): print("Hello, " + name + "! Welcome to Python programming.") def main(): user_name = input("Please enter your name: ") Grreting(user_na…

Python
def Grreting(name):
    print("Hello, " + name + "! Welcome to Python programming.")

def main():
    user_name = input("Please enter your name: ")
    Grreting(user_name)

if __name__ == "__main__":
    main()

# This code defines a function to greet the user and calls it in the main function.
# The user is prompted to enter their name, and a personalized greeting is displayed.
# The code is structured to run the greeting function when executed directly.
Python
def sum(a, b):
    return a + b

def sumPrint(a, b):
    result = sum(a, b)
    print(f"The sum of {a} and {b} is: {result}")

print(sum(4,5))
sumPrint(4, 5)


# Lambda Functions in Python
# A lambda function is a small anonymous ("ऐसी function जिसका कोई नाम नहीं होता") function that can take any number of arguments but can only have one expression.

x = lambda a, b: a ** b
result = x(5, 3)
print("The result of the lambda function is:", result)


numbers = 
numbers = 
print(numbers)  # Output: 


# same for lambda function
numbers = 
numbers = list(map(lambda x: x ** x, numbers))
print(numbers)  # Output: 

#Recursion in Python=>
# This function calculates the factorial of a number using recursion

def factorial(n):
    if n < 0:
        return "Factorial is not defined for negative numbers"
    elif n == 0 or n == 1:
        return 1
    else:
        value = factorial(n - 1) 
        result = n * value
        return result
    

print(factorial(5))  # Output: 120

for i, x in enumerate(range(1, 6), start=1):
    if i == 1:
        y = x
    y *= x
    print(y) # Output: 120

Modules and Pip - Using External Libraries

Python
import math
def calculate_circle_area(radius):
    if radius < 0:
        raise ValueError("Radius cannot be negative")
    return math.pi * (radius ** 2)

print(calculate_circle_area(5))  # Output: 78.53981633974483


#Save file like greet.py
# This is a simple Python script that defines a function to greet a user.

def greet(name):
    return f"Hello, {name}!"


import greet
print(greet.greet("Alice"))  # Output: Hello, Alice!

Types of Scope in Python

Local Scope (inside a function) – Variables declared inside a function are accessible only within that function.
Global Scope (accessible everywhere) – Variables declared outside any function can be used throughout the program.

Python
x = 10 # Global variable
def my_func():
    x = 5 # Local variable
print(x) # Output: 5
my_func()
print(x) # Output: 10 (global x remains unchanged)


x = 10 # Global variable
def modify_global():
    x = 5 
    print("Inside function:", x) # Output: 5


modify_global()
print(x) # Output: 10



x = 10 # Global variable
def modify_global():
    global x
    x = 5 
    print("Inside function:", x) # Output: 5


modify_global()
print(x) # Output: 5

Docstrings - Writing Function Documentation

Python
def add(a, b):
    """Returns the sum of two numbers."""
    return a + b

print(add.__doc__) # Output: Returns the sum of two numbers.

Other

Python
# Making an Argument Optional
def get_formatted_name(first_name, last_name, middle_name=''):
  if middle_name:
    full_name = f"{first_name} {middle_name} {last_name}"
  else:
    full_name = f"{first_name} {last_name}"
  return full_name.title()

musician = get_formatted_name('jimi', 'hendrix')
print(musician) #Jimi Hendrix

musician = get_formatted_name('john', 'hooker', 'lee')
print(musician) #John Lee Hooker
Python
#  Passing an Arbitrary Number of Arguments
'''
The asterisk in the parameter name *toppings tells Python to make a
tuple called toppings, containing all the values this function receives.
'''

def make_pizza(*toppings):
    """Print the list of toppings that have been requested."""
    print(toppings)


make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

#('pepperoni',)
# ('mushrooms', 'green peppers', 'extra cheese')
Python
def make_pizza(size, *toppings):
  """Summarize the pizza we are about to make."""
  print(f"\nMaking a {size}-inch pizza with the following toppings:")
  for topping in toppings:
        print(f"- {topping}")

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

Using Arbitrary Keyword Arguments: Sometimes you’ll want to accept an arbitrary number of arguments, but you won’t know ahead of time what kind of information will be passed to the function. In this case, you can write functions that accept as many key-value pairs as the calling statement provides. One example involves building user profiles: you know you’ll get information about a user, but you’re not sure what kind of information you’ll receive. The function build_profile() in the following example always takes in a first and last name, but it accepts an arbitrary number of keyword arguments as well:

Python
def build_profile(first, last, **user_info):
  user_info&#091;'first_name'] = first
  user_info&#091;'last_name'] = last
  return user_info

user_profile = build_profile('albert', 'einstein',
                             location='princeton',
                             field='physics'
                             )
print(user_profile)

'''
The double asterisks before the parameter **user_info cause Python to create
a dictionary called user_info containing all the extra name-value pairs the
function receives.
'''

Python
class Person:
        def __init__(self, name, age):
            self.name = name
            self._age = age  # Convention: _age indicates it's intended to be "private"

        def get_age(self): # Getter for age
            return self._age
        
        def set_age(self, new_age): # Setter for age
            if new_age >= 0 and new_age <= 150: # Validation
                self._age = new_age
            else:
                print("Invalid age!")


person = Person("Alice", 30)
print(person.get_age()) # Output: 30
person.set_age(35)
print(person.get_age()) # Output: 35

Keep building your data skillset

Explore more SQL, Python, analytics, and engineering tutorials.