Python Function Return Something

You have been using the “=" character to name variables and set them to numbers or strings. I will blow your mind by showing you how to use “=". A new Python function return to set variables to be a value from a function. There will be one thing to pay close attention to, but first type this in:


#Function for addition
def add(a, b):
print ("ADDING %d + %d" % (a, b))
return (a + b)

# function for subtraction
def subtract(a, b):
print ("SUBTRACTING %d - %d" % (a, b))
return (a - b)
# function for multiplication
def multiply(a, b):
print ("MULTIPLYING %d * %d" % (a, b))
return (a * b)
#function for division
def divide(a, b):
print ("DIVIDING %d / %d" % (a, b))
return (a / b)
print ("Let's do some math with just functions!")
age = add(10, 5)
height = subtract(88, 4)
weight = multiply(80, 2)
iq = divide(100, 2)
print ("Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq))
# A puzzle for the extra credit, type it in anyway.
print ("Here is a puzzle.")
# Calling functions inside functions. Look one more them to understand it.
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print ("That becomes: ", what, "Can you do it by hand?")

With help of return we are returning some values from our function and then assigning it to a variable, which we can use anytime.

Output of code

Run this code and see what output you get.

Python function return

We can call function inside a function and so on…

Exercise of day

Try creating a script which ask user to enter a number and perform math algorithm on those numbers.

Python function return can be used to return strings values, try to add some strings and return them.

no comments

Leave me comment