Passing Back More Than One Variable
User-defined functions can pass back more than one variable to the main several ways.
Example: Passing multiple values back as a tuple
A tuple in Python is like a static array. It stores in memory a collection of items that are ordered and cannot be altered. They are created using parentheses/round brackets.
def combine():
x = 1
y = 2
z = 3
return x, y, z
a = combine()
print(a)
for i in a:
print(i)
Output:
(1, 2, 3)
1
2
3
Example: Passing multiple values back as variables
def getInfo():
name = input("Please enter your name: ")
age = int(input("Please enter your age: "))
return name, age
name, age = getInfo()
print("Name: ", name, "\tAge: ", age)
Output:
Please enter your name: Heather
Please enter your age: 25
Name: Heather Age: 25
Example: Passing a Function to a Function
This program passes the getF() function to the convertC() function.
def getF():
f=int(input("Enter F temperature to convert to C:"))
return f
def convertC(f):
c = (f - 32) * (9 / 5)
if c < 0:
print(c, "C. Brr. That's chilly.")
elif c < 30:
print(c, "C. That's not too bad.")
else:
print(c, "C. That's hot!.")
convertC(getF())
Example: Alternate method to previous example
def getF():
f=int(input("Enter F temperature to convert to C:"))
return f
def convertC(f):
c = (f - 32) * (9 / 5)
return c
c = int(convertC(getF()))
if c < 0:
print(c, "C. Brr. That's chilly.")
elif c < 30:
print(c, "C. That's not too bad.")
else:
print(c, "C. That's hot!.")
Example: Passing a function to a function to a function
def getNums():
num1=int(input("Enter number 1:"))
num2=int(input("Enter number 2:"))
return num1, num2
def addNums(nums):
sum_nums = sum(nums)
return sum_nums
def displayNums(total):
print("The sum of the two numbers is", total)
displayNums(addNums(getNums()))
Example: Functions
def getScore():
score = int(input("Enter score: "))
while score < 0 or score > 100:
print ("Invalid score. Please enter value from 0 to 100.")
score = int(input("Enter score: "))
return score
def calcAverage(score1,score2,score3):
avg=(score1+score2+score3)/3
if avg >= 90:
grade="A"
elif avg >= 80:
grade="B"
elif avg >= 70:
grade="C"
elif avg >= 60:
grade="D"
else:
grade="E"
print("Your average is", avg, "which is a", grade)
score1 = getScore()
score2 = getScore()
score3 = getScore()
calcAverage(score1,score2,score3)
Recursion
Recursive functions are functions that call themselves
Example: Recursive function in Python to calculate factorial
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = int(input("Enter a positive number: "))
if num < 0:
print("Sorry. Please enter a positive number.")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of" , num, "is", recur_factorial(num))
Output:
Enter a positive number: 4
The factorial of 4 is 24