0% found this document useful (0 votes)
2 views10 pages

Functions classnote

The document provides a comprehensive overview of Python functions, including their definition, benefits, and various types of arguments such as positional, keyword, and arbitrary arguments. It also covers advanced topics like recursion, default parameter values, and examples of common functions like factorial, prime number generation, and string reversal. Overall, it serves as a detailed guide for understanding and utilizing functions in Python programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views10 pages

Functions classnote

The document provides a comprehensive overview of Python functions, including their definition, benefits, and various types of arguments such as positional, keyword, and arbitrary arguments. It also covers advanced topics like recursion, default parameter values, and examples of common functions like factorial, prime number generation, and string reversal. Overall, it serves as a detailed guide for understanding and utilizing functions in Python programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 10

PYTHON FUNCTIONS Python Functions is a block of statements that return the specific task.

The idea is to put some commonly or repeatedly done


tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse
code contained in it over and over again.

Some Benefits of Using Functions

Increase Code Readability Increase Code Reusability

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 In Python a function is defined using the def keyword:

In [ ]: def my_function():
print("Hello from a function")

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

In [2]:
def my_function():
print("Hello from a function")
my_function()

Hello from a function

# Arguments Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a
comma.

The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the
function to print the full name:

In [3]:
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Emil Refsnes
Tobias Refsnes
Linus Refsnes

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. This function expects 2 arguments, and gets 2 arguments:

In [4]: def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")

Emil Refsnes

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.

This way the function will receive a tuple of arguments, and can access the items accordingly:

In [6]:
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

The youngest child is Linus

Keyword Arguments You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

In [7]:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

The youngest child is Linus

Arbitrary Keyword Arguments, kwargs If you do not know how many keyword arguments that will be passed into your function, add two asterisk:
before the parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the items accordingly:

In [8]:
def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

His last name is Refsnes

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:

In [9]:
def my_function(country = "Norway"):
print("I am from " + country)

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

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

Passing a List as an Argument You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the
same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the function:

In [10]:
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

apple
banana
cherry

Return Values To let a function return a value, use the return statement:

In [11]:
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

15
25
45

In [5]: def square_value(num):


"""This function returns the square
value of the entered number"""
return num**2

print(square_value(2))
print(square_value(-4))

4
16

The pass Statement function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass
statement to avoid getting an error.

In [ ]:
def myfunction():
pass

Positional Arguments

We used the Position argument during the function call so that the first argument (or value) is assigned to name and the second argument (or value) is
assigned to age. By changing the position, or if you forget the order of the positions, the values can be used in the wrong places, as shown in the Case-
2 example below, where 27 is assigned to the name and Suraj is assigned to the age.
In [3]:
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)

# You will get correct output because


# argument is given in order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameAge(27, "Suraj")

Case-1:
Hi, I am Suraj
My age is 27

Case-2:
Hi, I am 27
My age is Suraj

Positional-Only Arguments You can specify that a function can have ONLY positional arguments, or ONLY keyword arguments.

To specify that a function can have only positional arguments, add , / after the arguments:

In [15]:
def my_function(x, /):
print(x)

my_function(3)

Without the , / you are actually allowed to use keyword arguments even if the function expects positional arguments:

In [16]:
def my_function(x):
print(x)

my_function(x = 3)

But when adding the , / you will get an error if you try to send a keyword argument:

In [17]:
def my_function(x, /):
print(x)

my_function(x = 3)

---------------------------------------------------------------------------TypeError Traceback (most recent call las


1 def my_function(x, /):
2 print(x)
----> 4 my_function(x = 3)
TypeError: my_function() got some positional-only arguments passed as keyword arguments: 'x'

Keyword-Only Arguments To specify that a function can have only keyword arguments, add *, before the arguments:

In [2]: def my_function(*, x):


print(x)

my_function(x=3)

Without the *, you are allowed to use positionale arguments even if the function expects keyword arguments:

In [18]: def my_function(x):


print(x)

my_function(3)

But with the *, you will get an error if you try to send a positional argument:

In [19]:
def my_function(*, x):
print(x)

my_function(3)
---------------------------------------------------------------------------TypeError Traceback (most recent call las
1 def my_function(*, x):
2 print(x)
----> 4 my_function(3)
TypeError: my_function() takes 0 positional arguments but 1 was given

Combine Positional-Only and Keyword-Only You can combine the two argument types in the same function.

Any argument before the / , are positional-only, and any argument after the *, are keyword-only.

In [20]: def my_function(a, b, /, *, c, d):


print(a + b + c + d)

my_function(5, 6, c = 7, d = 8)

26

Recursion Python also accepts function recursion, which means a defined function can call itself.

Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can
loop through data to reach a result.

The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses
excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant
approach to programming.

In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the k variable as the data, which decrements (-1)
every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).

To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and modifying it.

In [21]:
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("Recursion Example Results:")


tri_recursion(6)

Recursion Example Results:


1
3
6
10
15
21

Out [21]: 21

Factorial of a number

In [4]: def factorial(n):


if n == 0:
return 1
else:
return n * factorial(n - 1)

print(factorial(4))

24

In [6]: # Python3 code to demonstrate


# def keyword

# function for subtraction of 2 numbers.


def python_def_subNumbers(x, y):
return (x-y)

# main code
a = 90
b = 50

# finding subtraction
result = python_def_subNumbers(a, b)

# print statement
print("subtraction of ", a, " and ", b, " is = ", result)

subtraction of 90 and 50 is = 40

In [7]:
# Python program to print first 10
# prime numbers
# A function name prime is defined
# using def
def python_def_prime(n):
x = 2
count = 0
while count < n:
for d in range(2, x, 1):
if x % d == 0:
x += 1
else:
print(x)
x += 1
count += 1

# Driver Code
n = 10

# print statement
print("First 10 prime numbers are: ")
python_def_prime(n)

First 10 prime numbers are:


2
3
5
7
11
13
17
19
23
27

In [9]: # Python program to find the


# factorial of a number

# Function name factorial is defined


def python_def_factorial(n):
if n == 1:
return n
else:
return n*python_def_factorial(n-1)

# Main code
num = 6

# check is the number is negative


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", python_def_factorial(num))

The factorial of 6 is 720

In [10]:
def python_def_keyword(*args):
for arg in args:
print(arg)
python_def_keyword(1, 2, 3)
python_def_keyword('apple', 'banana', 'cherry', 'date')
python_def_keyword(True, False, True, False, True)

1
2
3
apple
banana
cherry
date
True
False
True
False
True

In [11]:
def python_def_keyword(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
python_def_keyword(name='Alice',
age=25, city='New York')
python_def_keyword(country='Canada',
language='French', population=38000000)
python_def_keyword(color='blue',
shape='square', size='large', material='wood')
name: Alice
age: 25
city: New York
country: Canada
language: French
population: 38000000
color: blue
shape: square
size: large
material: wood

Find the Max of three numbers

In [12]:
# Define a function that returns the maximum of two numbers
def max_of_two(x, y):
# Check if x is greater than y
if x > y:
# If x is greater, return x
return x
# If y is greater or equal to x, return y
return y

# Define a function that returns the maximum of three numbers


def max_of_three(x, y, z):
# Call max_of_two function to find the maximum of y and z,
# then compare it with x to find the overall maximum
return max_of_two(x, max_of_two(y, z))

# Print the result of calling max_of_three function with arguments 3, 6, and -5


print(max_of_three(3, 6, -5))

sum all the numbers in a list.

In [13]:
# Define a function named 'sum' that takes a list of numbers as input
def sum(numbers):
# Initialize a variable 'total' to store the sum of numbers, starting at 0
total = 0

# Iterate through each element 'x' in the 'numbers' list


for x in numbers:
# Add the current element 'x' to the 'total'
total += x

# Return the final sum stored in the 'total' variable


return total

# Print the result of calling the 'sum' function with a tuple of numbers (8, 2, 3, 0, 7)
print(sum((8, 2, 3, 0, 7)))

20

Multiply all the numbers in a list

In [14]:
# Define a function named 'multiply' that takes a list of numbers as input
def multiply(numbers):
# Initialize a variable 'total' to store the multiplication result, starting at 1
total = 1

# Iterate through each element 'x' in the 'numbers' list


for x in numbers:
# Multiply the current element 'x' with the 'total'
total *= x

# Return the final multiplication result stored in the 'total' variable


return total

# Print the result of calling the 'multiply' function with a tuple of numbers (8, 2, 3, -1, 7)
print(multiply((8, 2, 3, -1, 7)))

-336

Reverse a string

In [15]:
# Define a function named 'string_reverse' that takes a string 'str1' as input
def string_reverse(str1):
# Initialize an empty string 'rstr1' to store the reversed string
rstr1 = ''
# Calculate the length of the input string 'str1'
index = len(str1)

# Execute a while loop until 'index' becomes 0


while index > 0:
# Concatenate the character at index - 1 of 'str1' to 'rstr1'
rstr1 += str1[index - 1]

# Decrement the 'index' by 1 for the next iteration


index = index - 1

# Return the reversed string stored in 'rstr1'


return rstr1

# Print the result of calling the 'string_reverse' function with the input string '1234abcd'
print(string_reverse('1234abcd'))

dcba4321

Calculate the factorial of a number

In [16]:
# Define a function named 'factorial' that calculates the factorial of a number 'n'
def factorial(n):
# Check if the number 'n' is 0
if n == 0:
# If 'n' is 0, return 1 (factorial of 0 is 1)
return 1
else:
# If 'n' is not 0, recursively call the 'factorial' function with (n-1) and multiply it with 'n'
return n * factorial(n - 1)

# Ask the user to input a number to compute its factorial and store it in variable 'n'
n = int(input("Input a number to compute the factorial: "))

# Print the factorial of the number entered by the user by calling the 'factorial' function
print(factorial(n))

24

whether a number falls in a given range

In [1]:
# Define a function named 'test_range' that checks if a number 'n' is within the range 3 to 8 (inclusive)
def test_range(n):
# Check if 'n' is within the range from 3 to 8 (inclusive) using the 'in range()' statement
if n in range(3, 9):
# If 'n' is within the range, print that 'n' is within the given range
print("%s is in the range" % str(n))
else:
# If 'n' is outside the range, print that the number is outside the given range
print("The number is outside the given range.")

# Call the 'test_range' function with the argument 5


test_range(5)

5 is in the range

the number of upper / lower case letters in a string

In [2]:
# Define a function named 'string_test' that counts the number of upper and lower case characters in a string
def string_test(s):
# Create a dictionary 'd' to store the count of upper and lower case characters
d = {"UPPER_CASE": 0, "LOWER_CASE": 0}

# Iterate through each character 'c' in the string 's'


for c in s:
# Check if the character 'c' is in upper case
if c.isupper():
# If 'c' is upper case, increment the count of upper case characters in the dictionary
d["UPPER_CASE"] += 1
# Check if the character 'c' is in lower case
elif c.islower():
# If 'c' is lower case, increment the count of lower case characters in the dictionary
d["LOWER_CASE"] += 1
else:
# If 'c' is neither upper nor lower case (e.g., punctuation, spaces), do nothing
pass
# Print the original string 's'
print("Original String: ", s)

# Print the count of upper case characters


print("No. of Upper case characters: ", d["UPPER_CASE"])

# Print the count of lower case characters


print("No. of Lower case Characters: ", d["LOWER_CASE"])

# Call the 'string_test' function with the input string 'The quick Brown Fox'
string_test('The quick Brown Fox')

Original String: The quick Brown Fox


No. of Upper case characters: 3
No. of Lower case Characters: 13

Unique elements from a list

In [3]:
# Define a function named 'unique_list' that takes a list 'l' as input and returns a list of unique elements
def unique_list(l):
# Create an empty list 'x' to store unique elements
x = []

# Iterate through each element 'a' in the input list 'l'


for a in l:
# Check if the element 'a' is not already present in the list 'x'
if a not in x:
# If 'a' is not in 'x', add it to the list 'x'
x.append(a)

# Return the list 'x' containing unique elements


return x

# Print the result of calling the 'unique_list' function with a list containing duplicate elements
print(unique_list([1, 2, 3, 3, 3, 3, 4, 5]))

[1, 2, 3, 4, 5]

Test the number is prime or not

In [4]:
# Define a function named 'test_prime' that checks if a number 'n' is a prime number
def test_prime(n):
# Check if 'n' is equal to 1
if (n == 1):
# If 'n' is 1, return False (1 is not a prime number)
return False
# Check if 'n' is equal to 2
elif (n == 2):
# If 'n' is 2, return True (2 is a prime number)
return True
else:
# Iterate through numbers from 2 to (n-1) using 'x' as the iterator
for x in range(2, n):
# Check if 'n' is divisible by 'x' without any remainder
if (n % x == 0):
# If 'n' is divisible by 'x', return False (not a prime number)
return False
# If 'n' is not divisible by any number from 2 to (n-1), return True (prime number)
return True

# Print the result of checking if 9 is a prime number by calling the 'test_prime' function
print(test_prime(9))

False

string is palindrome or not

In [5]:
# Define a function named 'isPalindrome' that checks if a string is a palindrome
def isPalindrome(string):
# Initialize left and right pointers to check characters from the start and end of the string
left_pos = 0
right_pos = len(string) - 1

# Loop until the pointers meet or cross each other


while right_pos >= left_pos:
# Check if the characters at the left and right positions are not equal
if not string[left_pos] == string[right_pos]:
# If characters don't match, return False (not a palindrome)
return False

# Move the left pointer to the right and the right pointer to the left to continue checking
left_pos += 1
right_pos -= 1

# If the loop finishes without returning False, the string is a palindrome, so return True
return True

# Print the result of checking if the string 'aza' is a palindrome by calling the 'isPalindrome' function
print(isPalindrome('aza'))

True

Pascal's triangle

In [6]:
# Define a function named 'pascal_triangle' that generates Pascal's Triangle up to row 'n'
def pascal_triangle(n):
# Initialize the first row of Pascal's Triangle with value 1 as a starting point
trow = [1]

# Create a list 'y' filled with zeros to be used for calculations


y = [0]

# Iterate through a range starting from 0 up to the maximum of 'n' or 0 (taking the maximum to handle negat
for x in range(max(n, 0)):
# Print the current row of Pascal's Triangle
print(trow)

# Update the current row based on the previous row by calculating the next row using list comprehension
# The formula for generating the next row in Pascal's Triangle is based on addition of consecutive elem
trow = [l + r for l, r in zip(trow + y, y + trow)]

# Return True if 'n' is greater than or equal to 1, else return False


return n >= 1

# Generate Pascal's Triangle up to row 6 by calling the 'pascal_triangle' function


pascal_triangle(6)

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]

Out [6]: True

Write a Python function to check whether a string is a pangram or not. Note : Pangrams are words or sentences containing every letter of the alphabet
at least once. For example : "The quick brown fox jumps over the lazy dog"

In [7]: # Import the 'string' and 'sys' modules


import string
import sys

# Define a function named 'ispangram' that checks if a string is a pangram


def ispangram(str1, alphabet=string.ascii_lowercase):
# Create a set 'alphaset' containing all lowercase letters from the provided alphabet
alphaset = set(alphabet)

# Convert the input string to lowercase and create a set from it


str_set = set(str1.lower())

# Check if the set of lowercase characters in the input string covers all characters in 'alphaset'
return alphaset <= str_set

# Print the result of checking if the string is a pangram by calling the 'ispangram' function
print(ispangram('The quick brown fox jumps over the lazy dog'))

True

list where the values are square of numbers between two numbers

In [8]:
# Define a function named 'printValues' that generates a list of squares of numbers from 1 to 20
def printValues():
# Create an empty list 'l'
l = list()

# Iterate through numbers from 1 to 20 (inclusive)


for i in range(1, 21):
# Calculate the square of 'i' and append it to the list 'l'
l.append(i**2)

# Print the list containing squares of numbers from 1 to 20


print(l)

# Call the 'printValues' function to generate and print the list of squares
printValues()

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]

multiplication table

In [9]:
def mul(num):
"""
Prints the multipliaction table of a given number
"""
for i in range(1, 11):
print("{multiplier} * {multiplicand} = {multiplicantion}".format(
multiplier=num, multiplicand=i, multiplicantion=num * i))

mul(9)

9 * 1 = 9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
9 * 10 = 90

You might also like