One very common way to reuse code in Python is the use of a function, so let's take a look at how functions are used in Python. We'll go ahead and make a working copy of function.py. I'm going to call this function-working.py. Save that and open it up. Then I'll go ahead and maximize this, so we can look at this code. Here, we have a function definition. def is the keyword. It says this is going to define a function.
isprime is the name of the function, and n, in this case, is a parameter. We can have multiple parameters, separated by commas. We'll get into more of the details of how this works. This is the Quick Start. It's going to show you in a nutshell, if you're an experienced programmer, how to create functions. We'll get into the details later on in the course. In this case, this is a simple function for testing if a number is a prime number or not. It checks if it's 1. It checks if it's divisible evenly by other factors, and otherwise it says, this is a prime number.
So all of this code that is the body of the function is indented, as is how blocks of code are done in Python. And it's introduced with this colon. So you have the def, the name of the function, parenthesis, any parameters inside the parenthesis, and a colon, and then indented code for the body of the function. Down here, we call it. Here, we're calling it inside a for loop. And we simply call it by referencing the name and putting any parameters inside.
Now in this case, the parameter is a variable called n, which happens to be the same as what I call it up here. We could have used an x, or any other legal variable name down here, but just so you know that this n is different than this n. All right, so let's go ahead and run it. We'll select Run up here and Python Run. And there we have a list of all of these prime numbers.
So 1 is special. 2 is a prime number. 3 is a prime number. 4 is not a prime number, because it's divisible evenly by 2, and et cetera, et cetera, prime numbers and not prime numbers. So this function is getting called over and over inside of this loop. And we only have to have the code there once. And that, of course, is the value of a function or a subroutine. So that's how functions are defined and used in Python.
And of course, they're used quite a bit, and we'll see a lot more examples of this as we go through the course.
Get unlimited access to all courses for just $25/month.Become a member
82 Video lessons · 98575 Viewers
61 Video lessons · 85870 Viewers
71 Video lessons · 69760 Viewers
56 Video lessons · 102063 Viewers
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Your file was successfully uploaded.