Intro to Functions Flashcards
Function
Lines of code (1 or more) that are related, grouped together, and named. Once defined, these lines of code are reusable and can be called over and over again.
Invoking a function
“Invoking a function” means “make the lines of code inside of a function definition happen now.” We can invoke a function any number of times (even infinitely!)
Function definition, defining a function
How a function gets defined before it gets invoked
What are Functions?
Functions are lines of code that: hold related, sequential logic usually have a name don't do anything, until we tell it to do something take in data return a result are reusable
Single Responsibility Principle on Functions
Single Responsibility Principle is a programming value/best practice, or a belief that many/most developers value. The Single Responsibility Principle (SRP) states that a function should have one, and only one primary responsibility. This is to say, when developers describe the purpose of a function, ideally, the function isn’t trying to do more than one thing.
Invoking a function
“Invoking a function” means “make the lines of code inside of a function definition happen now.” We can invoke a function any number of times (even infinitely!)
Argument
An argument is a piece of data delivered to a function when it’s being invoked.
Return value
A return value is the piece of data that a function delivers to the code that invoked the function.
What should we understand when we use a function?
We should fully understand the responsibility of each function when we use it. Before using a function, we should be able to describe the following:
the purpose of the function the data that 'goes into' the function the computations inside of the function the data that 'goes out' of the function
len
Based on the one given value, will calculate the length of the given value. The given value is typically either a string or list.
Based on one given value, will display the given value to the “standard output” (like the console, terminal, bash, etc) as best it can.
random.randint
Based on two given values, generate a random integer in the range between the first given value and the second given value
time.time
Calculates the number of seconds passed since epoch. For Unix system, January 1, 1970, 00:00:00 at UTC is epoch (the point where time begins)
Arguments are Positional
The arguments that we pass in to a function have a specific order, and the order matters.
The correct order of arguments is determined by whoever defined the function. An incorrect order of arguments in a function is misusing the function, and will result in bugs/unexpected output.
Passing in the Wrong Number of Arguments
If we pass in the wrong number of arguments, we get errors, like this TypeError