Functions classnote
Functions classnote
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.
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()
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:
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])
Keyword Arguments You can also send arguments with the key = value syntax.
In [7]:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
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"])
Default Parameter Value The following example shows how to use a default parameter 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)
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
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)
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)
Keyword-Only Arguments To specify that a function can have only keyword arguments, add *, before the arguments:
my_function(x=3)
Without the *, you are allowed to use positionale arguments even if the function expects keyword arguments:
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.
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
Out [21]: 21
Factorial of a number
print(factorial(4))
24
# 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)
# Main code
num = 6
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
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
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
# 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
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
# 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)
# Print the result of calling the 'string_reverse' function with the input string '1234abcd'
print(string_reverse('1234abcd'))
dcba4321
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
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.")
5 is in the range
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}
# Call the 'string_test' function with the input string 'The quick Brown Fox'
string_test('The quick Brown Fox')
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 = []
# 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]
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
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
# 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]
# 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)]
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
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"
# 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()
# 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