0
What is the easy way to learn about functions??
I am now learning about object oriented
2 Respostas
0
A function is like a form of abstraction. It allows you to refer to a block of code by name that can be executed when called. A function typically has a specific job. For example:
def print_numbers(amount):
print(amount)
print_numbers(26)
# Output: 26
Obviously this is just a simple example. The function's job, in this case, is to print out whatever number that's placed into it's input (argument). After it does this, the function is finished. You can call the function as many times as you like. It can help in situations where you need to do something several times. Instead of writing that 'same' code over and over again, the function is simply called to handle it.
That is the most basic explanation.
0
functions are just code that is re-callable. For instance if you have a calculator, you could have a function for add, subtract, multiply, or divide. Here is a basic calculator.. Note the functions. they are defined before they are call. they each have 2 arguments to pass in the numbers you want to use. and they have return statements. return is what you get back when you call the function.
def add(a,b):
return a+b
def sub(a,b):
return a-b
def mult(a,b):
return a*b
def div(a,b):
if a!=0 or b!=0:
return a/b
else:
return 0
run=True
while run:
funct=input("1-Add - 2-Sub - 3-Multiply - 4-Divide ")
num1=float(int(input("Enter 1st Number ")))
num2=float(int(input("Enter 2nd Number ")))
if funct=="1":
print(add(num1,num2))
if funct=="2":
print(sub(num1,num2))
if funct=="3":
print(mult(num1,num2))
if funct=="4":
print(div(num1,num2))