Aiki da Bayyana Ayyuka a Python
A cikin Python, aiki toshe ne na lamba wanda ke yin takamaiman aiki kuma ana iya sake amfani da shi a cikin shirin. Ƙayyadaddun aiki a ciki Python ya ƙunshi matakai masu zuwa:
Ma'anar Ma'anar Aiki
Don ayyana aiki a cikin Python, kuna amfani def
da kalmar maɓalli, sannan sunan aikin da jerin sigogin shigarwar da ke haɗe a cikin baka ()
. Lambar da ke yin aikin aikin ana sanya shi a cikin jikin aikin, wanda ke ciki a cikin toshe def
. Aiki na iya dawo da ƙima(ko ƙima mai yawa) ta amfani da return
kalmar maɓalli. Idan babu return
bayani a cikin aikin, aikin zai dawo ta atomatik None
.
Amfani da Ma'aunin Shigarwa
Aiki na iya karɓar bayanai daga waje ta hanyar sigogin shigarwa. Ma'auni sune ƙimar da kuke bayarwa lokacin kiran aikin. Za a yi amfani da waɗannan sigogi a cikin jikin aikin don yin takamaiman ayyuka.
Mayar da Darajoji daga Aiki
Da zarar aikin ya gama aikinsa, zaku iya amfani da return
kalmar don dawo da ƙima daga aikin. Idan aikin ba shi da return
sanarwa, aikin zai dawo ta atomatik None
.
Kiran Aiki
Don amfani da ƙayyadaddun aiki, kawai kuna kiran sunan aikin kuma ku wuce kowace ƙimar siga da ake buƙata(idan akwai). Sakamakon da aka dawo daga aikin(idan akwai) ana iya adana shi a cikin mai canzawa don amfani na gaba ko buga shi zuwa allon.
Cikakken Misali
# Define a function to calculate the sum of two numbers
def calculate_sum(a, b):
sum_result = a + b
return sum_result
# Define a function to greet the user
def greet_user(name):
return "Welcome, " + name + "!"
# Call the functions and print the results
num1 = 5
num2 = 3
result = calculate_sum(num1, num2)
print("The sum of", num1, "and", num2, "is:", result) # Output: The sum of 5 and 3 is: 8
name = "John"
greeting_message = greet_user(name)
print(greeting_message) # Output: Welcome, John!
A cikin misalin da ke sama, mun bayyana ayyuka guda biyu: calculate_sum()
don ƙididdige jimlar lambobi biyu da greet_user()
ƙirƙirar saƙon gaisuwa. Sa'an nan, mun kira wadannan ayyuka da kuma buga sakamakon.