Coding5: Loops, Functions, and Scope
In this one we talk about loops: For Loops, While Loops, and creating your own custom functions, and a little concept called Scope. Pay attention to Scope, a lot of interviewers ask this.
Quick Recap
As of right now, we have covered extremely simple data types: Integers, and strings. We’ve talked about how you can manipulate basic text data using both Python, and R. We’ve also done some extremely simple math calculations, and talked about how you can actually get the languages to produce an output. Now let’s focus on automating a lot of your tedious work, and creating your own custom function that suits your own specific needs.
Table of Contents:
Custom Functions
Creating Custom Functions
Python
R
What is Scope
Python
R
What are Loops
What are while loops
What are for loops
Custom Functions
As of right now, we’ve primarily been using the default built in functions provided to us when we install Python/R. However, in order to focus in on our specific niche (this substack will focus on Data Science), we will only care about functions that are related to our own specific niche. So, to deal with our own specific problems, we may want to create our own specific functions.
Creating Custom Functions
Every single Function has 2 important parts to it: the function header, and the function body. The function header tells us the following information: what is the name of the function, how many inputs does it require & their labels. The function body tells us what the function will actually do when we call upon it.
Another thing to note is that programming is done top down, meaning you must define your custom functions in the top lines before you can use it in your lines later on. If you try to use your function before you have defined it, you will get an error.
Python
In Python, in order to create our own custom function, we will use the def keyword. Below, I will create a simple function that will be named multiply, it will have 2 inputs: x, y. The function when called upon will multiply x and y together, and RETURN the output.
Keep reading with a 7-day free trial
Subscribe to Data Science & Machine Learning 101 to keep reading this post and get 7 days of free access to the full post archives.