0% found this document useful (0 votes)
1 views11 pages

Python Programming Module 2

The document provides an overview of Python functions, including how to create, call, and use parameters and arguments. It also covers built-in functions, the random and datetime modules, the math module, lambda functions, function composition, and recursion. Each section includes examples to illustrate the concepts discussed.

Uploaded by

antony09141
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views11 pages

Python Programming Module 2

The document provides an overview of Python functions, including how to create, call, and use parameters and arguments. It also covers built-in functions, the random and datetime modules, the math module, lambda functions, function composition, and recursion. Each section includes examples to illustrate the concepts discussed.

Uploaded by

antony09141
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Python Programming- Module 2

Python Functions
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.

Creating a Function (User defined functions)

In Python a function is defined using the def keyword:

Example:

def my_function():
print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

Example:

def my_function():
print("Hello from a function")

my_function()

Output:
Hello from a function
Arguments

• Information can be passed into functions as arguments.


• Arguments are specified after the function name, inside the parentheses

Example:

def my_function(name):
print(name , " World")

my_function("Hello")
my_function("Hai")
my_function("Welcome")

Output:

Hello World
Hai World
Welcome World

Parameters or Arguments?

The terms parameter and argument can be used for the same thing: information that
are passed into a function.

From a function's perspective:

• A parameter is the variable listed inside the parentheses in the function


definition.
• An argument is the value that is sent to the function when it is called.

Number of Arguments

By default, a function must be called with the correct number of arguments.


Meaning that if your function expects 2 arguments, you have to call the function
with 2 arguments, not more, and not less.
Example:

This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname," ",lname)

my_function("Hello", "World")

Output:

Hello World

Arbitrary Arguments, *args

If you do not know how many arguments that will be passed into your function,
add a * before the parameter name in the function definition.

Example:

If the number of arguments is unknown, add a * before the parameter name:

def my_function(*kids):
print(kids)

my_function("Abc", "Def", "Ghi")

Output:

('Abc', 'Def', 'Ghi')

Default Parameter Value

The following example shows how to use a default parameter value.


If we call the function without argument, it uses the default value:
Example:

def my_function(country = "Norway"):


print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Output:

I am from Sweden
I am from India
I am from Norway
I am from Brazil

Python In-Build Functions

Built-in functions are functions that are pre-defined in Python,


meaning they are always available without needing to import any
additional modules.

1. print():

• Prints the specified message to the screen or other standard output device.
• Example: print("Hello, World!")

2. len():

• Returns the length (number of items) of an object like a list, string, or tuple.
• Example: len("Python") # Output: 6

3. type():
• Returns the type of the object passed to it (e.g., whether it's an integer, list,
etc.).
• Example: type(42) # Output: <class 'int'>

4. sum():

• Returns the sum of all items in an iterable (e.g., a list or tuple).


• Example: sum([1, 2, 3]) # Output: 6

5. max():

• Returns the largest item in an iterable or the largest of two or more arguments.
• Example: max(1, 5, 3) # Output: 5

6. min():

• Returns the smallest item in an iterable or the smallest of two or more


arguments.
• Example: min([4, 2, 8]) # Output: 2

7. input():

• Allows the user to input data from the keyboard. Returns the input as a string.
• Example: name = input("Enter your name: ")

8. abs():

• Returns the absolute value of a number, i.e., the non-negative value.


• Example: abs(-5) # Output: 5

9. round():

• Rounds a floating-point number to the nearest integer or to a given number of


decimal places.
• Example: round(3.14159, 2) # Output: 3.14

10. sorted():

• Returns a new sorted list from the elements of any iterable.


• Example: sorted([3, 1, 2]) # Output: [1, 2, 3]
random module

In Python, random numbers can be generated using functions from the random
module. Here are three commonly used random number generating functions:

1. random()

• Description: Generates a random floating-point number between 0.0 and 1.0,


where 0.0 is inclusive, and 1.0 is exclusive.
• Syntax: random.random()
• Example:

import random
print(random.random()) # Output: 0.7451 (example output)

2. randint(a, b)

• Description: Returns a random integer between two specified integers a and


b, inclusive of both a and b.
• Syntax: random.randint(a, b)
• Example:

import random
print(random.randint(1, 10)) # Output: 4 (example output)

3. uniform(a, b)

• Description: Returns a random floating-point number between two specified


numbers a and b, where a is inclusive and b is exclusive.
• Syntax: random.uniform(a, b)
• Example:

import random
print(random.uniform(1.5, 5.5)) # Output: 3.7345 (example output)
DateTime Module

The datetime module in Python provides several classes for working with dates and
times. Here are the primary classes in the datetime module:

1. datetime.date

from datetime import date

# Create a date object for a specific date


d = date(2024, 8, 5)
print(d) # Output: 2024-08-05

# Get today's date


today = date.today()
print(today) # Output: (e.g., 2024-08-05)

# Access year, month, and day


print(today.year) # Output: 2024
print(today.month) # Output: 8
print(today.day) # Output: 5

2. datetime.time

from datetime import time

# Create a time object


t = time(14, 30, 45)
print(t) # Output: 14:30:45

# Access hour, minute, second


print(t.hour) # Output: 14
print(t.minute) # Output: 30
print(t.second) # Output: 45

3. datetime.datetime

from datetime import datetime

# Create a datetime object for a specific date and time


dt = datetime(2024, 8, 5, 14, 30, 45)
print(dt) # Output: 2024-08-05 14:30:45

# Get the current date and time


now = datetime.now()
print(now) # Output: (e.g., 2024-08-05 14:30:45)

# Access year, month, day, hour, minute, second


print(now.year) # Output: 2024
print(now.month) # Output: 8
print(now.day) # Output: 5
print(now.hour) # Output: 14
print(now.minute) # Output: 30
print(now.second) # Output: 45

Math Module

• Math Module consists of mathematical functions and constants. It is a built-


in module made for mathematical tasks.
• The math module provides the math functions to deal with basic operations
such as addition(+), subtraction(-), multiplication(*), division(/), and
advanced operations like trigonometric, logarithmic, and exponential
functions.

Constants in Math Module

The Python math module provides various values of various constants like pi, and
tau. We can easily write their values with these constants. The constants provided
by the math module are:

• Euler’s Number
• Pi
• Tau
• Infinity
• Not a Number (NaN)
• import math
math.e #output: 2.718281828459045
math.pi #ouput: 3.141592653589793

• import math
x=5
math.factorial(x) #Returns the factorial of the number

• math.log2(10) #Computes value of log a with base 2

lambda()

Syntax:
lambda argument(s): expression

• it is a special type of function without the function name


• they are anonymous functions

Example:

# Define a lambda function to add two numbers


add = lambda x, y: x + y

# Use the lambda function


result = add(3, 5)
print(result) # Output: 8

composition of functions
• Function composition is a concept where the output of one
function is used as the input to another function.
• This allows you to combine simple functions to build more
complex operations.
• In Python, function composition can be done using regular
functions or lambda functions.
Example:

def multiply_by_two(x):
return x * 2

def add_three(y):
return y + 3

def compose_functions(f, g, x):


return f(g(x))

# Compose the functions


result = compose_functions(multiply_by_two, add_three, 5)
print(result)

# Output: 16

In this example, the function add_three is applied to the input 5, resulting in 8, and
then multiply_by_two is applied to 8, resulting in 16.

Recursion

Recursion is a common mathematical and programming concept. It means that a


function calls itself.

Example:

def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case
else:
return n * factorial(n - 1)
# Calculate the factorial of 5
result = factorial(5)
print(result)

# Output: 120

You might also like