Python design your own function

Python Designing Your Own Functions At this point, we should be able to confidently design a function that meets our project needs. We’ll integrate all the knowledge above to design a simple sensitive word filter. But before that, let’s first learn about a new function: open.

This function is very simple to use; it only requires two parameters: the full path and name of the file, and the method to open it.

First, create a file named text.txt on your desktop. Windows users can create a file by right-clicking on the desktop to bring up the context menu. Mac users can open Pages, create a file, click Export Format, and select txt. Now, let’s use the open function to open it:

open('/Users/Hou/Desktop/text.txt')

If you’re a Windows user, you should enter your path like this:

open('C://Users/Hou/Desktop/')

If you typed the code exactly as it appears, the file should already be open, but…it seems we can’t tell. So, let’s learn a new method: write. In Chapter 1, we already mentioned how to use methods. (If you’re still confused about the relationship between functions and methods, to make things easier, I can explain that methods are just a type of function, just in a different location. The principles of use are very similar.) Here, we’ll copy the replace method from Chapter 3 to learn how to use the write method:

file = open('/Users/Hou/Desktop/text.txt','w')
file.write('Hello World')

After writing this, let’s run the program to see the results:

Python Design Your Own Function

Now that we’ve mastered the basics of open and write, we can start designing functions. The requirements are as follows: We pass in the name parameter and msg can be used to write the file name and content to the desktop using the text_create function. If there’s no such file on the desktop, it will be created before writing. Let’s get started!

def text_create(name, msg):
desktop_path = '/Users/Hou/Desktop/'
full_path = desktop_path + name + '.txt'
file = open(full_path, 'w')
file.write(msg)
file.close()
print('Done')
text_create('hello', 'hello world') # Calling the function

Let’s explain this code line by line.

  • Line 1: Defines the function name and parameters.
  • Line 2: As we learned earlier, the open function needs to open a complete path, so the desktop path is used first.
  • Line 3: We name the file, which is the parameter passed in, plus the desktop path, followed by a suffix to create the complete file path.
  • Line 4: Opens the file. The ‘w’ parameter indicates write mode, meaning: if a file with that name doesn’t exist, it will be created in the same directory; if it does exist, it will be appended to overwrite the contents.
  • Line 5: Writes the passed parameter msg (i.e., the content).
  • Line 6: Closes the file.

This completes the first part of the sensitive word filter. Incidentally, this function is the one we mentioned earlier that doesn’t require a return statement to function. The final print statement simply serves as a reminder to indicate that all the above statements have been executed. Next, we implement the second part, sensitive word filtering. The requirements are as follows: define a function called text_filter, pass in parameters word, cencored_word, and changed_word to implement filtering. The sensitive word cencored_word defaults to ‘lame’, and the replacement word changed_word defaults to ‘Awesome’. Now let’s continue:

def text_filter(word,censored_word = 'lame',changed_word = 'Awesome'):
return word.replace(censored_word, changed_word)
text_filter('Python is lame!') # Calling the function

This function is much simpler. The first line defines the function by setting default parameters, and the second line directly returns the result of the replace operation. Now that both functions are complete, you can try calling them and see the results for low-risk reasons.

Now let’s try to solve a more complex problem by merging two functions: creating a function called text_censored_create . This function creates a text field on the desktop where text can be entered. However, if the text contains sensitive words, it will be filtered by default and written to a file. The file name parameter is name, and the message parameter is msg. You can try writing this yourself first and then compare it with the following:

def censored_text_create(name, msg):
clean_msg = text_filter(msg)
text_create(name,clean_msg)
censored_text_create('Try','lame!lame!lame!') # Call the function

We use the first function to filter the incoming msg and store it in a variable named clean_msg. Then, we pass the passed file name parameter and the filtered text clean_msg as parameters to the text_create function. The result is the filtered text.

Once you’re done, you have a text filter!

This chapter only uses mathematics to illustrate how functions work. However, if you need to solve a lot of mathematical problems, you can refer to the following table. Experimenting will reveal how to use it. Don’t hesitate to experiment; your computer won’t crash because of a single line of code.
Assuming a=10, b=20, the calculation example is as follows:
Python Design Your Own Function

Leave a Reply

Your email address will not be published. Required fields are marked *