Arguments
Part of the Fundamentals section of Coddy's Python journey — lesson 44 of 77.
An argument in a function is a value that you pass into the function when you call it. To add arguments to a function, we write them inside the parenthesis ():
def function_name(arg1, arg2, ...):
codeWe can name the arguments as we want, and we can write as many arguments as we need.
To call a function and pass arguments to it, we write:
function_name(value1, value2, value3, ...)Passing too many arguments to a function that is expecting fewer arguments will cause the program to fail
Example of usage:
def is_even(number):
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
for i in range(15, 34):
is_even(i)
for i in range(153, 219):
is_even(i)Here we have a function called is_even that accepts one argument called number and prints if the number is even or odd. Then we call the function twice: one time for all the numbers between 15 and 34, and the second time for all the numbers between 153 and 219.
Challenge
EasyWrite a program that takes two integers as input and calls a function to calculate and print their product.
Cheat sheet
Function arguments are values passed into a function when calling it:
def function_name(arg1, arg2, ...):
# function code
function_name(value1, value2, ...)Example with one argument:
def is_even(number):
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
is_even(4)Note: Passing too many arguments to a function will cause an error.
Try it yourself
# Declare your function here
# print the result of a*b inside the function
a = int(input())
b = int(input())
# Call your function here with the arguments a and bThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2