
Syntax: Return Statement
Making Python functions give values back with return statements.
Function return Statement
Practice: Function to Multiply Numbers
-
Define a function called
multiplythat takes two parameters:num1andnum2. -
Inside the function, multiply
num1andnum2and return the result. -
After the function definition, call your
multiplyfunction with the numbers6and7. Assign the return value to a variable namedproduct. -
Print
product. -
Run your code and confirm that the output is
42.
HINT*: Click here for a hint
> 42
SOLUTION*: Click here for an example solution
def multiply(num1, num2):
return num1 * num2
product = multiply(6, 7)
print(product)
Practice: Function to Capitalize a String
-
Define a function called
capitalize_wordthat takes one parameter:word. -
Inside the function, capitalize the first letter of word and return the result. The Pyton built in
capitalize()function will help with this. -
After the function definition, call your
capitalize_wordfunction with the string"hello". Assign the return value to a variable namedword_capitalize. -
Print capitalized_word.
-
Run your code and confirm that the output is "Hello".
HINT*: Click here for a hint
> "Hello"
SOLUTION*: Click here for an example solution
def capitalize_word(word):
return word.capitalize()
word_capitalized = capitalize_word("hello")
print(word_capitalized)
Practice: Function to Check if a Number is Odd or Even
-
Define a function called
check_odd_eventhat takes one parameter:num. -
Inside the function, use an
ifstatement to check whethernumis even. If it's even, return the string"Even". If it's not, return the string"Odd". -
After the function definition, call your
check_odd_evenfunction with the number15. Assign the return value to a variable namedresult. -
Print result.
-
Run your code and confirm that the output is
"Odd".
HINT*: Click here for a hint
> "Odd"
SOLUTION*: Click here for an example solution
def check_odd_even(num):
if num % 2 == 0:
return "Even"
else:
return "Odd"
result = check_odd_even(15)
print(result)