# Fundamentals and exercises of Python functions

## Function basis

### 1. Define function

#### 1. What is a function

1. concept

A function is the encapsulation of the code that implements a specific function - > a function corresponds to a function (the function stored in the function)

2. Classification (by who created the function)

• System functions - there are functions that have been created in Python language (Python's own functions), such as print, input, type, id, max, min, sorted, sum, etc
• Custom function - a function created by the programmer himself

#### Machine building function (2)

1. Syntax:

```def Function name(parameter list ):
Function description document
Function body
```
2. explain:

• def - keyword; Fixed writing

• Function name - named by the programmer;

Requirement: identifier, not keyword

Specification: see the name to know the meaning (see the function name to roughly know what the function is)
Do not use the system function name, class name, module name
All letters are lowercase, and multiple words are separated by underscores

• (): - Fixed writing

• Formal parameter list - exists in the form of 'variable name 1, variable name 2, variable name 3,...', where each variable is a formal parameter; Formal parameters can be none or multiple. Formal parameters can transfer data outside the function to the inside of the function; How many formal parameters are needed when defining a function? It depends on whether additional data is needed to implement the function. How many parameters are needed

• Function description document - the essence is to keep an indented multi line comment with def; It is used to describe the function, parameters and return value of a function

• Function body - one or more statements that maintain an indentation with def, which is essentially the code to realize the function. (circuit structure and mechanical mechanism)

```# Exercise 1: write a function to sum two numbers
def sum2(num1, num2):
"""
(Function description area)Find the sum of any two numbers
:param num1: (Parameter description) Number 1
:param num2: Number 1
:return: (Return value description) None
"""
print(num1 + num2)

sum2(10, 20)
```
```# Exercise 2: write a function to count the number of numeric characters in a specified string
def count_number(str1):
"""Number of statistics characters"""
count = 0
for x in str1:
if x.isdigit():
count += 1
print(count)

count_number('ajhf1238 Shanhaijing 02')
count_number('2791 of the number')
```
```# Exercise 3: define a function to get the ten digits of any integer (both positive and negative)
def get_tens_digit(num):
"""Get ten digits"""
if num < 0:
num *= -1
print(num // 10 % 10)

get_tens_digit(123)
get_tens_digit(-132)
```
```# Exercise 4: define a function to get all numeric elements in the specified list
def get_numbers(list1):
"""Get numeric element"""
new_list = []
for x in list1:
if type(x) in (int, float):
new_list.append(x)
print(new_list)

get_numbers([19, 'yes d', 23.8, True, None])
```
```# Exercise 5: define a function to get the common part of two strings
def get_common_char(str1, str2):
"""Gets the common part of two strings"""
result = set(str1) & set(str2)
print(''.join(result))

get_common_char('abcn', '123ba92')
```
```# Exercise 6: define a function exchange Dictionary of keys and values
def change_key_value(dict1):
new_dict = {}
for key in dict1:
new_dict[dict1[key]] = key
print(new_dict)

change_key_value({'a': 10, 'b': 20, 'c': 30})
```

### 2. Call function

1. Important conclusion: the function will not be executed when defining the function, but only when calling

2. Syntax:

```Function name(Argument list)
```
3. explain:

• Function name - call the function of which function you need, and write the function name of which function you want to call

Note: the function name here must be the function name of the defined function

• () - Fixed writing

• Argument list - exists in the form of 'data 1, data 2, data 3,...'; Arguments are the data that is really passed to the function through formal parameters; The number of arguments is determined by the formal parameters. By default, the number of arguments is required when the function is called

4. Function call procedure:

When the code executes the function call statement:
Step 2: pass parameters (the process of assigning values to formal parameters with actual parameters). When passing parameters, you must ensure that each formal parameter has a value
Step 3: execute the function body
Step 4: determine the return value
Step 5: return to the location of the function call, and then execute it later

### 3. Parameters of function

#### 1. Location parameter and keyword parameter - according to the different transfer methods of the arguments, the arguments of the function are divided into these two types

1. Location parameters

When calling a function, separate multiple data directly with commas, and the actual parameters and formal parameters correspond to each other in position

2. Keyword parameters

When calling the function, add 'formal parameter name =' in front of the data, and the actual parameter and formal parameter are corresponding by the formal parameter name

3. Mixed use of two parameters

It is required to ensure that the location parameter is in front of the keyword parameter

```def func1(x, y, z):
print(f'x:{x}, y:{y}, z:{z}')

func1(10, 20, 30)
func1(20, 10, 30)
func1(x=100, y=200, z=300)
func1(z=3, x=1, y=2)
func1(10, y=20, z=30)
func1(10, z=30, y=20)
func1(10, 20, z=30)
# func1(10, b=20, 30)   # report errors! SyntaxError: positional argument follows keyword argument
```

#### 2. Parameter default value

1. When defining a function, you can assign default values to formal parameters. When calling a function, there are already default parameters. You can directly use the default values without passing parameters.
2. If you assign default values to some parameters, you must ensure that the parameters without default values precede the parameters with default values

#### 3. Parameter type description

Parameter type description: specify the parameter type when defining the function

1. Add type description for parameters without default value

```Formal parameter name:data type
```
2. For parameters with default values, the type of default value is the type of parameter

#### 4. Variable length parameters

Variable length parameter with *:

• Add * before the formal parameter, and the parameter becomes a tuple, which is used to receive all the corresponding arguments (the arguments are the elements in the tuple)
• Remember: if the function parameter is after the parameter with *, the latter parameters must use keyword parameters when calling

### 4. Return value of function

#### What is a return value

1. significance:

• The return value is the data passed from inside the function to outside the function
2. How to determine the return value (how to pass the data inside the function to the outside of the function as the return value):

• In the function body, put the data to be returned after return;
• The return value of the function is the value after return. If there is no return, the return value is None
3. How to get the return value (how to get the data passed from inside the function outside the function):

• Obtain the result of the function call expression outside the function;
• The value of the function call expression is the return value of the function
4. When to return a value:

• If new data is generated by implementing the function of the function, the new data is returned as the return value
```def sum2(n1, n2):
# n1 = 10; n2 = 20
result = n1 + n2     # result = 30
print(f'inside:{result}')
return result      # return 30

a = sum2(10, 20)      # The value of the function call expression is the return value of the function
print(f'a:{a}')
```

1. Write a function to exchange the key and value of the specified dictionary.

```  for example:dict1={'a':1, 'b':2, 'c':3}  -->  dict1={1:'a', 2:'b', 3:'c'}
```
```def change_key_value(dict1: dict):
dict0 = {}
for key, value in dict1.items():
dict0.setdefault(value, key)
return dict0

a = change_key_value({'a': 1, 'b': 2, 'c': 3})
print(a)
```
2. Write a function to extract all the letters in the specified string, and then splice them together to produce a new string

```   for example: afferent'12a&bc12d-+'   -->  'abcd'
```
```def get_alphabet(str1: str):
str0 = ''
for x in str1:
if 'a' <= x <= 'z' or 'A' <= x <= 'Z':
str0 += x
return str0

a = get_alphabet('1acXS3w4')
print(a)
```
3. Write your own capitalize function, which can turn the first letter of the specified string into uppercase letters

```  for example: 'abc' -> 'Abc'   '12asd'  --> '12asd'
```
```def turn_majuscule(str1: str):
for x, y in enumerate(str1):
if 'a' <= y <= 'z':
result = str1.replace(y, chr(ord(y) - 32), x+1)
break
return result

a = turn_majuscule('12abc')
print(a)
```
4. Write your own endswitch function to judge whether a string has ended with the specified string

```   for example: String 1:'abc231ab' String 2:'ab' The result of the function is: True
String 1:'abc231ab' String 2:'ab1' The result of the function is: False
```
```def judge_ending(str1: str, str0: str):
return str1[-len(str0):] == str0

judge_ending('abc231ab', 'ab1')
```
5. Write your own isdigit function to judge whether a string is a pure digital string

```   for example: '1234921'  result: True
'23 function'   result: False
'a2390'    result: False
```
```def judge_pure_number(str1: str):
for x in str1:
if x < '0' or x > '9':
return(False)
return True

judge_pure_number('123xd')
```
6. Write your own upper function to change all lowercase letters in a string into uppercase letters

```    for example: 'abH23 good rp1'   result: 'ABH23 good RP1'
```
```def minuscule_turn_majuscule(str1: str):
str0 = ''
for x in str1:
if 'a' <= x <= 'z':
x = chr(ord(x) - 32)
str0 += x
return str0

a = minuscule_turn_majuscule('abH23 good rp1')
print(a)
```
7. Write your own rjust function to create a string whose length is the specified length. The original string is right aligned in the new string, and the rest is filled with the specified characters

```   for example: Original character:'abc'  width: 7  character:'^'    result: '^^^^abc'
Original character:'how are you'  width: 5  character:'0'    result: '00 how are you'
```
```# Method 1:
def rjust_function(str1: str, width: int, element):
result = ''
for x in range(width - len(str1)):
result += element
result += str1
return result

a = rjust_function('how are you', 5, '0')
print(a)

# Method 2:
def rjust(str1: str, width: int, char: str):
"""
:param str1: Original string
:param width: New length
:param char: To fill in characters, you need a string with a length of 1
:return: New filled string
"""
if len(char) != 1:
raise TypeError

len1 = len(str1)
if width <= len1:
return str1
return char * (width - len1) + str1

print(rjust('sa', 5, 'x'))
```
8. Write your own index function to count all the subscripts of the specified elements in the specified list. If there is no specified element in the list, return - 1

```   for example: list: [1, 2, 45, 'abc', 1, 'Hello', 1, 0]  element: 1   result: 0,4,6
list: ['Zhao Yun', 'Guo Jia', 'Zhuge Liang', 'Cao Cao', 'Zhao Yun', 'Sun Quan']  element: 'Zhao Yun'   result: 0,4
list: ['Zhao Yun', 'Guo Jia', 'Zhuge Liang', 'Cao Cao', 'Zhao Yun', 'Sun Quan']  element: 'Guan Yu'   result: -1
```
```def index(list1: list, item):
indexs = []
for i, x in enumerate(list1):
if x == item:
indexs.append(i)
if indexs:
return ','.join(str(x) for x in indexs)
return -1

print(index([10, 20, 30, 10, 40], 100))
```
9. Write your own len function to count the number of elements in the specified sequence

```    for example: sequence:[1, 3, 5, 6]    result: 4
sequence:(1, 34, 'a', 45, 'bbb')  result: 5
sequence:'hello w'    result: 7
```
```def count_number(sequence):
count = 0
for x in sequence:
count += 1
return count

a = count_number('hell0 wo')
print(a)
```
10. Write your own max function to get the maximum value of the elements in the specified sequence. If the sequence is a dictionary, take the maximum value of the dictionary value

```  for example: sequence:[-7, -12, -1, -9]    result: -1
sequence:'abcdpzasdz'    result: 'z'
sequence:{'Xiao Ming':90, 'Zhang San': 76, 'Monkey D Luffy':30, 'floret': 98}   result: 98
```
```def max2(seq):
if type(seq) == dict:
seq = list(seq.values())
else:
seq = list(seq)
m = seq[0]
for x in seq[1:]:
if x > m:
m = x
return m

print(max2([10, 23, 78, 2]))
print(max2({230, 9, 7281, 90}))
print(max2({'xiaoming': 90, 'floret': 89, 'Xiao Hong': 76, 'Xiao Hei': 98}))
```
11. Write a function to realize its own in operation and judge whether the specified element exists in the specified sequence

```    for example: sequence: (12, 90, 'abc')   element: '90'     result: False
sequence: [12, 90, 'abc']   element: 90     result: True
```
```def judge_in(sequence, element):
for x in sequence:
if x == element:
return True
return False

judge_in([12, 90, 'abc'], 90)
```
12. Write your own replace function to convert the old string specified in the specified string into the new string specified

```    for example: Original string: 'how are you? and you?'   Old string: 'you'  New string:'me'  result: 'how are me? and me?'
```
```def replace(str1: str, old: str, new: str):
# Method 1:
# new_str = new.join(str1.split(old))
# return new_str
# Method 2:
index = 0
old_len = len(old)
new_str = ''
while index < len(str1):
if str1[index: index+old_len] == old:
new_str += new
index += old_len
else:
new_str += str1[index]
index += 1
return new_str

print(replace('how are you? and you?', 'you', 'me'))
```

Keywords: Python Back-end

Added by jibosh on Wed, 02 Mar 2022 14:30:50 +0200