当前位置:网站首页>Basic function exercises
Basic function exercises
2022-07-04 10:38:00 【She was your flaw】
Function basis
One 、 Call function
1. Call function
‘’’
Function name ( Argument list )
- Defining a function does not execute the function body , Call the function to execute the function body .( How many calls , How many times will the function body be executed )
- When you call a function , The number of arguments is determined by the formal parameters of the called function .( The process of assigning values to formal parameters with actual parameters is called parameter passing )
- Function call procedure ( Simple version )
When the code executes the function call statement , The subsequent execution process is as follows :
First step : Return to the position defined by the function
The second step : The ginseng ( Assign values to formal parameters with arguments )
The third step : Execute function body
Step four : Determine the return value ( For the time being )
Step five : Returns the location of the function call , Then go back
‘’’
def func2(x, y, z):
# x=10, y=20, z=30
print(f'x:{
x}, y:{
y}, z:{
z}')
Two 、 The parameters of the function
- Location parameters and keyword parameters
‘’’
According to the different ways of providing arguments when calling functions , Actual parameters are divided into position parameters and keyword parameters
Positional arguments
Directly provide the data corresponding to the arguments , Let the arguments and formal parameters correspond in position one by onekeyword
With ’ Shape parameter 1= Actual parameters 1, Shape parameter 2= Actual parameters 2, …' In the form of biographyA mixture of
Positional parameters and keyword parameters can be used together , When used together, you must ensure that the location parameter is in front of the keyword parameter
‘’’
def func1(a, b, c):
print(f'a:{
a}, b:{
b}, c:{
c}')
# Positional arguments
func1(100, 200, 300) # a:100, b:200, c:300
func1(200, 100, 300) # a:200, b:100, c:300
# Key parameters
func1(a=100, b=200, c=300) # a:100, b:200, c:300
func1(c=300, a=100, b=200) # a:100, b:200, c:300
# A mixture of
func1(10, b=20, c=30) # a:10, b=20, c=30
func1(10, c=20, b=30) # a:10, b:30, c:20
func1(10, 20, c=30) # a:10, b:20, c:30
2. Parameter default
‘’’
When defining a function, you can use ’ The name of the parameter = value ’ Provide default values for formal parameters in the form of ;
If a parameter has a default value , Then parameters with default values can be called without passing parameters .
If some parameters have default values when defining a function , Some parameters do not , Then the parameter without default value must be in front of the parameter with default value .
‘’’
def func2(a=10, b=20, c=30):
print(f'a:{
a}, b:{
b}, c:{
c}')
func2() # a:10, b:20, c:30
func2(100) # a:100, b:20, c:30
func2(100, 200) # a:100, b:200, c:30
func2(100, 200, 300) # a:100, b:200, c:300
func2(c=300) # a:10, b:20, c:300 ( Skip parameters with default values before , Pass the following parameters with keyword parameters )
def func3(a, c, b=20):
print(f'a:{
a}, b:{
b}, c:{
c}')
func3(20, 30)
func3(10, 20, 30)
- Parameter type description
‘’’
Parameters with default values ; What is the default value , Type description is what type
Parameters without default : You need to add ’: Type name ’
‘’’
def func4(x: list, y=''):
pass
4. Indefinite length parameter
‘’’
- belt Indefinite length parameter of – If you add , Then this formal parameter can accept any number of arguments
belt * The essence of the indefinite length parameter of is a tuple , The corresponding multiple arguments are elements in tuples .
Be careful :a. belt Indefinite length parameter of , Position parameters must be used when transferring parameters
b. If the fixed length parameter is in band After the parameter of ( Sometimes it's directly in * Behind ), Then the following variable length parameter calls must use keyword parameters to pass parameters
- belt ** Indefinite length parameter of ( understand )
‘’’
def func5(*x):
pass
func5()
func5(10)
func5(10, 20)
func5(10, 20, 90, 8)
# practice : Define a function to sum multiple numbers .
def sum2(*nums):
s = 0
for x in nums:
s += x
print(s)
sum2(10, 20)
sum2(10, 20, 30)
def func6(a, b, *c):
print(f'a:{
a}, b:{
b}, c:{
c}')
func6(10, 20)
func6(10, 20, 43, 56, 78, 90)
def func7(*a, b, c):
print(f'a:{
a}, b:{
b}, c:{
c}')
func7(10, 20, 30, 40, b=2, c=1)
def func8(*, a, b, c):
print(f'a:{
a}, b:{
b}, c:{
c}')
func8(a=10, b=20, c=30)
def func9(**x):
print(x)
func9()
func9(a=10)
func9(a=10, b=20)
func9(a=10, b=20, x=100, y=200)
def func10(*args, **kwargs):
pass
func10()
func10(10, 20, 30, 40)
func10(a=10, x=20, b=9)
func10(10, 20, x=2, y=9)
3、 ... and 、 The return value of the function
The function of return value is
The function of return value is to convert the data generated inside the function , Pass to the outside of the function
How do beginners determine whether a function needs a return value : See if the function generates new data , If any, return the new data as the return valueDetermine the return value of the function ( How to take data as return value )
‘’’
In the body of a function by return Keyword returns the return value of the function :return data
Be careful :1) If you do not encounter return, The return value of the function is None
2) return It also has the function of ending the function in advance ( Where to meet when executing the function body return, Where does the function end )
‘’’
- How to get the return value of a function outside of a function
‘’’
To get the value of the function call expression is to get the return value of the function .
Function call expression – The statement that calls the function
Every function call statement actually has a result ( It's all data ), This result is the return value of the function at the time of this call
The return value of a function depends on the time when the function is called return What is the following value ,return What is the following value , What is the result of the function call expression outside the function .
‘’’
def sum2(num1, num2):
s = num1 + num2
return s
a = sum2(78, 90)
print('a:', a) # 168
print('========================================')
# I haven't met return The return value is None
def func3():
print('abc')
result = func3()
print(' Return value :', result) # Return value : None
def func4(x):
if x % 2:
return 100
print(' Return value :', func4(20)) # Return value : None
print(' Return value :', func4(21)) # Return value : 100
def func5():
for x in range(100):
return x
print(func5()) # 0
Function job
Write a function , Exchange the specified dictionary key and value.
for example :dict1={ 'a':1, 'b':2, 'c':3} --> dict1={ 1:'a', 2:'b', 3:'c'}
def func1(): dict1 = { 'a': 1, 'b': 2, 'c': 3} new_dict1 = { dict1[key]: key for key in dict1} return new_dict1 print(func1())
Write a function , Extract all letters in the specified string , Then spliced together to produce a new string
for example : Pass in '12a&bc12d-+' --> 'abcd'
def str3(): str1 = '12a&bc12d-+' str2 = '' for x in str1: if 'a' <= x <= 'z' or 'A' <= x <= 'Z': str2 += x return str2 print(str3())
Write your own capitalize function , Can change the first letter of the specified string into uppercase letter
for example : 'abc' -> 'Abc' '12asd' --> '12asd'
str1 = 'rjr43453' def str2(): if 'a' <= str1[0] <= 'z': str3 = chr(ord(str1[0]) - 32) + str1[1:] return str3 else: return str1 print(str2())
Write your own endswith function , Determines whether a string has ended with the specified string
for example : character string 1:'abc231ab' character string 2:'ab' The result of the function is : True
character string 1:'abc231ab' character string 2:'ab1' The result of the function is : False
def my_endswith(str1: str, str2: str):
if len(str2) > len(str1):
return False
else:
# Reverse the string
str1 = ''.join(str1[::-1])
str2 = ''.join(str2[::-1])
# Determine whether the short string is part of the beginning of the long string ( continuity )
for index1 in range(len(str2)):
if str2[index1] != str1[index1]:
return False
return True
print(my_endswith('abc123', '123'))
print(my_endswith('abc321', '123'))
Write your own isdigit function , Determine whether a string is a pure numeric string
for example : '1234921' result : True '23 function ' result : False 'a2390' result : False
def str2(): str1 = '534uuuu55' for x in str1: if not '0' <= x <= '9': return False else: return True print(str2())
Write your own upper function , Change all lowercase letters in a string into uppercase letters
for example : 'abH23 good rp1' result : 'ABH23 good RP1'
def str2(str1): str3 = '' for x in str1: if 'a' <= x <= 'z': str3 += chr(ord(x)-32) else: str3 += x return str3 print(str2('asd perform 13ATrh565'))
Write your own rjust function , Create a string whose length is the specified length , The original string is right justified in the new string , 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 '
def str1(x, y): a = x.rjust(7, '^') b = y.rjust(5, '0') return a, b print(str1('abc', 'wd'))
Write your own index function , Counts all subscripts of the specified elements in the specified list , If no element is specified in the list, return -1
for example : list : [1, 2, 45, 'abc', 1, ' Hello ', 1, 0] Elements : 1 result : 0,4,6 list : [' zhaoyun ', ' Guo Jia ', ' Zhugeliang ', ' Cao Cao ', ' zhaoyun ', ' king of Wu in the Three Kingdoms Era '] Elements : ' zhaoyun ' result : 0,4 list : [' zhaoyun ', ' Guo Jia ', ' Zhugeliang ', ' Cao Cao ', ' zhaoyun ', ' king of Wu in the Three Kingdoms Era '] Elements : ' Guan yu ' result : -1
def my_index(list1, item): new_list = [] for i in range(len(list1)): if list1[i] == item: new_list.append(str(i)) if new_list != []: return new_list else: return -1 print(my_index([' zhaoyun ', ' Guo Jia ', ' Zhugeliang ', ' Cao Cao ', ' zhaoyun ', ' king of Wu in the Three Kingdoms Era '], ' zhaoyun '))
Write your own len function , 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 my_len(list1):
count = 0
for _ in list1:
count += 1
return count
print(my_len([1, 2, 3, 6, ‘ Love ’, ’ ', ‘ hate ’]))
```
Write your own max function , Gets the maximum value of the element 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 my_max(nums): if type(nums) == dict: list_keys = [key for key in nums] max1 = nums[list_keys[0]] for x in range(1, len(list_keys)): if nums[list_keys[x]] > max1: max1 = nums[list_keys[x]] return max1 else: max1 = nums[0] for y in range(1, len(nums)): if nums[y] > max1: max1 = nums[y] return max1 print(my_max({ ' Xiao Ming ': 90, ' Zhang San ': 76, ' Monkey D Luffy ': 30, ' floret ': 98})) print(my_max('abcdpzasdz')) print(my_max([-7, -12, -1, 9]))
Write a function to realize yourself in operation , Determine the number of... In the specified sequence , Whether the specified element exists
for example : Sequence : **(12, 90, 'abc')** Elements : '90' result : False Sequence : [12, 90, 'abc'] Elements : 90 result : True
def my_in(nums, item): for x in nums: if item == x: return True else: return False print(my_in((12, 90, 'abc'), 'abc'))
Write your own replace function , Converts the old string specified in the specified string to 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 my_replace(str1, str2, str3):
return str3.join(str1.split(str2))
print(my_replace('how are you? and you?', 'you', 'me'))
边栏推荐
- 【Day1】 deep-learning-basics
- Hidden C2 tunnel -- use of icmpsh of ICMP
- Reasons and solutions for the 8-hour difference in mongodb data date display
- Batch distribution of SSH keys and batch execution of ansible
- What is an excellent architect in my heart?
- [advantages and disadvantages of outsourcing software development in 2022]
- Const's constant member function after the function; Form, characteristics and use of inline function
- [Galaxy Kirin V10] [desktop] login system flash back
- Article publishing experiment
- The most detailed teaching -- realize win10 multi-user remote login to intranet machine at the same time -- win10+frp+rdpwrap+ Alibaba cloud server
猜你喜欢
Safety reinforcement learning based on linear function approximation safe RL with linear function approximation translation 2
How do microservices aggregate API documents? This wave of show~
Tables in the thesis of latex learning
[Galaxy Kirin V10] [server] NUMA Technology
【FAQ】华为帐号服务报错 907135701的常见原因总结和解决方法
20 minutes to learn what XML is_ XML learning notes_ What is an XML file_ Basic grammatical rules_ How to parse
The time difference between the past time and the present time of uniapp processing, such as just, a few minutes ago, a few hours ago, a few months ago
system design
【Day1】 deep-learning-basics
For programmers, if it hurts the most...
随机推荐
IPv6 comprehensive experiment
【FAQ】华为帐号服务报错 907135701的常见原因总结和解决方法
Error C4996 ‘WSAAsyncSelect‘: Use WSAEventSelect() instead or define _ WINSOCK_ DEPRECATED_ NO_ WARN
DCL statement of MySQL Foundation
[Galaxy Kirin V10] [server] NUMA Technology
DML statement of MySQL Foundation
Knapsack problem and 0-1 knapsack problem
Static comprehensive experiment ---hcip1
Native div has editing ability
/*Rewrite the program, find the value of the element, and return the iterator 9.13: pointing to the found element. Make sure that the program works correctly when the element you are looking for does
DDL statement of MySQL Foundation
Occasional pit compiled by idea
MPLS: multi protocol label switching
Rhcsa operation
[Galaxy Kirin V10] [desktop] printer
PHP code audit 3 - system reload vulnerability
Basic data types of MySQL
如果不知道這4種緩存模式,敢說懂緩存嗎?
Today's sleep quality record 78 points
Student achievement management system (C language)