From 0e645479f57570c73c1dc5f8168aa3df176429a8 Mon Sep 17 00:00:00 2001 From: anivkuttan Date: Tue, 19 Aug 2025 23:03:36 +0530 Subject: [PATCH] functions --- src/basic/functions.py | 117 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 src/basic/functions.py diff --git a/src/basic/functions.py b/src/basic/functions.py new file mode 100644 index 0000000..dc582fd --- /dev/null +++ b/src/basic/functions.py @@ -0,0 +1,117 @@ + + +def my_function(): + print("Anikuttan") + + +# calling the function +my_function() + + +# name is Positional Arguments +def say_my_name(name): + print(f"Hello {name}") + + +# calling +say_my_name("Kuttan") +say_my_name(name="Kuttan") +say_my_name() # gives error because the positional arguments is missing +say_my_name(name1="Kuttan") # it gives unexpected keyword argument + + +def say_my_full_name(first_name, last_name): + print(first_name + " " + last_name) + + +say_my_full_name(first_name="Ani", last_name="kuttan") # calling + +# If the number of positional arguments is unknown, add a * before the parameter name +# *args give the tuple of arguments, + + +def my_function(*kids): + print("The youngest child is " + str(kids[0])) + print(type(kids)) + + +my_function("Emil", "Tobias", "Linus") + + +# If the number of keyword arguments is unknown, add a ** before the parameter name +# **kwargs give the dict of arguments, +def my_function2(**kids): + print("The youngest child is " + str(kids)) + print("The youngest child is " + str(kids['name'])) + print(type(kids)) + + +my_function2(name="Emil", month="May", age="12") + + +# default value +def say_my_name(name="Name"): + print(name) + + +say_my_name() +say_my_name("Anikuttan") + +# Return Values + + +def my_function(x): + return 5 * x + + +print(my_function(3)) +print(my_function(5)) +print(my_function(9)) + +# To specify function can have only positional arguments, add , / after the arguments: + + +def my_function(x, /): + print(x) + + +# my_function(3) +# my_function(x=3) +my_function(x=3) + + +# Keyword-Only Arguments +# To specify that a function can have only keyword arguments, add *, before the arguments +def my_function(*, x): + print(x) + + +my_function(x=3) + + +# Combine Positional-Only and Keyword-Only +# a, b is positional +# c, d is keyword +def my_function(a, b, /, *, c, d): + print(a + b + c + d) + + +my_function(5, 6, c=7, d=8) + +# return type + + +def say_my_name(name) -> str: + return name + + +my_name = say_my_name("ANikuttan") +print(my_name) + + +def add(a, b) -> int: + return a + b + + +number = add(a=10, b=20) +print(number)