Introduction to Python (15) Functions (3)

Author: Xiou

1. return value

Instead of always displaying output directly, a function can also manipulate some data and return a value or set of values. The value returned by a function is called the return value. In a function, use the return statement to return a value to the line of code that called the function. Return values ​​allow you to simplify the main program by moving most of the heavy lifting of your program into functions.

1.1 Returning simple values

Let's look at a function that takes a first and last name and returns the tidy name:

  def get_formatted_name(first_name, last_name):
      """返回整洁的姓名。"""
      full_name = f"{
      
      first_name} {
      
      last_name}"
      return full_name.title()

  musician = get_formatted_name('jimi', 'hendrix')
  print(musician)

The function get_formatted_name() is defined to accept a first and last name as parameters. It combines the first and last name into one, puts a space in between, and assigns the result to the variable full_name. Then, convert the value of full_name to initial capitalization and return the result on the function call line.

When calling a function that returns a value, you need to provide a variable into which to assign the returned value. Here, the return value is assigned to the variable musician. Output as tidy names:

insert image description here

Originally, you only need to write the following code to output a neat name. Compared with this, the previous work seems to be too much:

print("Jimi Hendrix")

But in larger programs that need to store a large number of first and last names separately, functions like get_formatted_name() are very useful. First name and last name can be stored separately, and this function is called whenever the name needs to be displayed.

1.2 Make arguments optional

Sometimes it is desirable to make arguments optional so that the user of the function can provide additional information only when necessary. Default values ​​can be used to make arguments optional.

For example, suppose you want to extend the function get_formatted_name() to also handle middle names. To do this, modify it to look like this:

def get_formatted_name(first_name, middle_name, last_name):
    """返回整洁的姓名。"""
    full_name = f"{
      
      first_name} {
      
      middle_name} {
      
      last_name}"
    return full_name.title()

musician = get_formatted_name('john', 'lee', 'hooker')
print(musician)

This function works correctly as long as you provide first, middle, and last names together. It creates a string from these three parts, adds spaces where appropriate, and converts the result to capitalized format:

insert image description here
Not all people have a middle name, but if this function is called with only a first and last name, it won't work correctly. To make the middle name optional, specify an empty default value for the middle_name parameter and not use it if the user does not supply a middle name. To make get_formatted_name() work when no middle name is provided, set the default value of the middle_name parameter to the empty string and move it to the end of the parameter list:

  def get_formatted_name(first_name, last_name, middle_name=''):
      """返回整洁的姓名。"""
      if middle_name:
          full_name = f"{
      
      first_name} {
      
      middle_name} {
      
      last_name}"
      else:
          full_name = f"{
      
      first_name} {
      
      last_name}"
      return full_name.title()

  musician = get_formatted_name('jimi', 'hendrix')
  print(musician)

  musician = get_formatted_name('john', 'hooker', 'lee')
  print(musician)

In this example, the name is created from three possible parts provided. Since people have first and last names, these two formal parameters are listed first in the function definition. The middle name is optional, so this parameter is listed last in the function definition, and its default value is set to the empty string.

In the function body, check if a middle name was provided. Python interprets non-empty strings as True, so ifmiddle_name will be True if a middle name is provided in the function call. If a middle name is provided, combine the first, middle, and last names into the first name, capitalize it, and return to the function call line. On the function call line, the returned value is assigned to the variable musician, and the value of this variable is printed. If no middle name is provided, middle_name will be an empty string, causing the if test to fail and the else code block to be executed:

Generates the name using only the first and last name, and returns the formatted name to the function call line. On the function call line, the returned value is assigned to the variable musician, and the value of this variable is printed.

This modified version works not only for people with only a first and last name, but also for people with a middle name:

Jimi Hendrix
John Lee Hooker

Optional values ​​allow functions to handle a variety of different situations while keeping function calls as simple as possible.

1.3 return dictionary

Functions can return any type of value, including more complex data structures such as lists and dictionaries. For example, the following function takes the components of a name and returns a dictionary representing people:

  def build_person(first_name, last_name):
      """返回一个字典,其中包含有关一个人的信息。"""
      person = {
    
    'first': first_name, 'last': last_name}
      return person

  musician = build_person('jimi', 'hendrix')
  print(musician)

The function build_person() takes a first and last name and puts these values ​​into a dictionary. When storing the value of first_name, the key used is 'first', and when storing the value of last_name, the key used is 'last'. Finally, return the entire dictionary representing people.
Print the returned value. At this time, the original two text information is stored in a dictionary:

insert image description here

This function takes simple text information and puts it in a more suitable data structure, allowing you to not only print the information, but also process it in other ways. Currently, the strings 'jimi' and 'hendrix' are tokenized as first and last names. You can easily extend this function to accept optional values ​​such as middle name, age, occupation, or any other information you want to store. For example, the following modification allows you to store ages:

def build_person(first_name, last_name, age=None):
    """返回一个字典,其中包含有关一个人的信息。"""
    person = {
    
    'first': first_name, 'last': last_name}
    if age:
        person['age'] = age
    return person

musician = build_person('jimi', 'hendrix', age=27)
print(musician)

In the function definition, an optional formal parameter age is added, and its default value is set to the special value None (indicating that the variable has no value). Think of None as a placeholder value. In conditional tests, None is equivalent to False. If the function call includes the value of the formal parameter age, this value will be stored in the dictionary. In any case, this function stores the person's name, but can be modified to also store other information about the person.

1.4 Combining functions and while loops

Functions can be combined with any of the Python constructs described above. For example, the following uses the function get_formatted_name() in combination with a while loop to greet the user in a more formal way. Here's an attempt to greet a user by first and last name:

  def get_formatted_name(first_name, last_name):
      """返回整洁的姓名。"""
      full_name = f"{
      
      first_name} {
      
      last_name}"
      return full_name.title()

  # 这是一个无限循环!
  while True:
      print("\nPlease tell me your name:")
      f_name = input("First name: ")
      l_name = input("Last name: ")

      formatted_name = get_formatted_name(f_name, l_name)
      print(f"\nHello, {
      
      formatted_name}!")

In this example, a simple version of get_formatted_name() is used that does not involve the middle name. The while loop lets the user enter a name: the user is prompted for first and last name in turn.

But there is a problem with this while loop: no exit condition is defined. When asking the user to provide a series of inputs, where should you provide an exit method? To make it as easy as possible for the user to log out, provide a way to log out every time the user is prompted for input. Use the break statement to provide an easy way out of the loop each time the user is prompted for input:

def get_formatted_name(first_name, last_name):
    """返回整洁的姓名。"""
    full_name = f"{
      
      first_name} {
      
      last_name}"
    return full_name.title()

while True:
    print("\nPlease tell me your name:")
    print("(enter 'q' at any time to quit)")

    f_name = input("First name: ")
    if f_name == 'q':
        break

    l_name = input("Last name: ")
    if l_name == 'q':
        break

    formatted_name = get_formatted_name(f_name, l_name)
    print(f"\nHello, {
      
      formatted_name}!")

We add a message to tell the user how to log out, and then every time the user is prompted for input, we check to see if the value he entered is the logout value. If yes, exit the loop. Now, this program will keep greeting until the user enters a first or last name 'q':

insert image description here

Guess you like

Origin blog.csdn.net/qq_41600018/article/details/130956950