understanding functions in python :)

function is basically a reusable task we can control 2 things on task “what to do”, “when to do” what to do -> writing the function (behavior) when to do -> calling the function (timing) suppose i gave you a task -> print table of 5 you might take one approach like # 5 * 1 = 5 # 5 * 2 = 10 # 5 * 3 = 15 # . # . # 5 * 10 = 50 # well this is one of the correct approach but can we be more pythonic about it? n = 5 for x in range(1, 11): print(f”{n} * {x} = {x*n}”) # this seems easy right? but what if i told you i want table of 10 now? n = 10 for x in range(1, 11): print(f”{n} * {x} = {x*n}”) # well if you notice from above code most of our code is repeated except the n part # i don’t like to re-write same code over and over and im assuming you neither # can we minimize it ? # Yes, by writing a function # in python we use def keyword to make a function # def functionName(parameters): # print(“inside the function”) def table(n=0): for x in range(1, 11): print(f”{n} * {x} = {x * n}”) # but if we run it ? nothing is going to happen why? # because remember i told you function is a task # with task we can control 2 things “what to do” and “when to do” # we created a function but python wont run it unless we call the function by its name # when to do python don’t know that # this is how you call the function # functionName(parameter=argument) table(n=5) # parameter is the variable that your function is dependent for existence # arguments are values we are passing when we call the function table(n=35) # HW # what are arguments and parameters # create a function that finds if number if even or odd (HINT: modules operator | print(5%2)). # create a function that adds two strings. # create a function that adds two numbers. # create a function that adds three numbers. # banList = [“kai”, “zeno”, “yusuf”] …write a function to check particular user is in banlist or not
Design a site like this with WordPress.com
Get started