functions

This commit is contained in:
2025-08-19 23:03:36 +05:30
parent 839a835f2a
commit 0e645479f5

117
src/basic/functions.py Normal file
View File

@@ -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)