程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python Basics_ Functions and jobs

編輯:Python
# function : Define the functional implementation , And it can be implemented repeatedly
'''
1. keyword :def
2.def The name of the function ():
The body of the function to be indented
The code to realize the function
'''
# Definition of function
# Basic grammar
def get_money(): # After the colon , Is the implementation code
print(' Take it 500 ten thousand !!') # The body of the function
print(' How happy! !')
# call The name of the function ()
get_money() # Don't know how to achieve , But I just used
# Function parameter
'''
1. Formal parameters and actual parameters
2. Definition time , Is a formal parameter
3. Invocation time , Pass argument
'''
# Second version
# Use of position parameters
'''
1.() Prepare several pits , It is equivalent to telling the user that the pit must be filled , Otherwise it won't work
2. Definition time ,() Put formal parameters , Not specific data , Formal parameters are expressed by variables , Formal parameters are used to receive - The data actually transmitted by the caller
3. The number of formal parameters depends on your requirements
'''
def get_money_v2(card,passworld,count): # Put formal parameters
''' # Three quotes Line feed brings out Function function description
:param card: Card number
:param passworld: password
:param count: Withdrawal amount
:return: Return value
'''
# The card number must be greater than 10 position , Is string
if len(card) < 10:
print(' Wrong card number , bye !')
# Password must be 6 position , Otherwise an error
if len(passworld) != 6:
print(' Password length error , bye !')
# Amount must be 100 Integer multiple , Otherwise, it will prompt you to report the wrong amount
if int(count) % 100 != 0:
print(' Amount is not 100 Integer multiple ')
pass # Use pass placeholder I haven't thought of writing anything yet . Thought of writing
'''
# Call function
# 1. All parameters must be passed
# 2. Location reference , The corresponding position transmits the corresponding value
# 3. When called , It transmits specific data , It's called an argument
'''
get_money_v2('12345678900','4567','500') # Passed argument ‘ password ’ Can't meet the conditions
# print() # ctrl+B Look at the source code
# Third edition
# Use of default parameters
'''
# Default parameters : If you do not pass the corresponding arguments , I default to the values I provide when defining
# Definition time : Shape parameter = value
# The default parameter is at the end
# There is no limit to the number of
'''
def get_money_v3(card,passworld='123456',count=1000): # Defining formal parameters = value
# The card number must be greater than 10 position , Is string
if len(card) < 10:
print(' Wrong card number , bye !')
# Password must be 6 position
if len(passworld) != 6:
print(' Password length error , bye !')
# Amount must be 100 Integer multiple , Otherwise, it will prompt you to report the wrong amount
if int(count) % 100 != 0:
print(' Amount is not 100 Integer multiple ')
else:
print(card,passworld,count) # Execute print all parameters
# There are three scenarios for calling parameters :
# The first uses the default value : Defining formal parameters = value
get_money_v3('12345678900',) # Because the first position parameter must be transmitted , Back 2 The definition has been Shape parameter = value 了
# The second part uses default values , Can pass but not pass :
get_money_v3('12345678900','123000') # count The default value parameter is used
# The third is when calling , Key parameters . Reference time , Shape parameter = value Can
get_money_v3('12345678900',count=2000) # Key parameters : Shape parameter = value , You can skip a parameter directly
# The fourth version
# Indefinite length parameter (*args( You can send more than one , In the form of a tuple ),**kwargs( You must use the key : Worth the form , In the form of a dictionary ))
def get_money_v4(card,*args,**kwargs):
# args Is a tuple () form kwargs It's a dictionary , You must use the key : Worth the form
# The card number must be greater than 10 position , Is string
if len(card) < 10:
print(' Wrong card number , bye !')
print(card)
print(args)
print(kwargs)
for item in args: # Traversal value
print(item)
# Call function
get_money_v4('12345678900') # Output empty tuples and empty dictionaries
# call args Parameters , It can be applied to multiple parameters , Output a tuple
get_money_v4('12345678900',True,'123456',100,) # Output one Tuples
# call kwargs Parameters , With {key:value}, Output a dictionary
get_money_v4('12345678900',True,'123456',100,name=' Smile ',city=' Shenzhen ') # Output one Dictionaries
# Positional arguments ( Will pass ), Default parameters ( Can pass but not pass ), Indefinite length parameter ( Support multiple transmission )
# The order ( Reference resources print): Indefinite length parameter , Default parameters ( Can pass but not pass )
# *args,*keargs
'''
Several methods of function parameters :
1. Must pass parameters
2. Default parameters : Shape parameter = Actual parameters
3. Indefinite length parameter :*args,*keargs
Positional arguments 》 Indefinite length parameter 》 Default parameters
'''
# Return value (return) In town
# The fifth version
'''
Return value keyword :return
1. Function none return, The default return value after the call is None
2.return value , Values can be any type
3.return You can not follow the value , Indicates that the return is None
4. When you call a function , encounter return, It means that the function call ends
'''
def get_money_v5(card,passworld='123456',count=1000):
# The card number must be greater than 10 position , Is string
if len(card) < 10:
print(' Wrong card number , bye !')
return # encounter return Just exit the function call
# Password must be 6 position
if len(passworld) != 6:
print(' Password length error , bye !')
return
# Amount must be 100 Integer multiple , Otherwise, it will prompt you to report the wrong amount
if int(count) % 100 != 0:
print(' Amount is not 100 Integer multiple ')
else:
# All three conditions are met , I will spit money for you
print(' Conditions met , Ready to spit money ')
return card,count
# Accept return value Variable = Function call
get_money_v5('12345678900') # Call but return no result
# The first one can receive multiple... Using only one variable
res = get_money_v5('12345678900') # Receive return tuple form
print(res)
# The second is to use multiple variables to receive
carn,money = get_money_v5('12345678900') # It's independent
print(carn,money)
# res = get_money_v5('12345678900','12345') # One of the branches is not satisfied , Encountered in the course of execution return, Exit function call
# print(res)
'''
summary :
1. What is a function ? Function realization
2. The function is defined before calling
3. Definition :def The name of the function ():
Realization function
4. Parameters : Interact with users . When implementing functions , Need to interact with the outside , External data is required , To achieve the function
5. Demand determines , There are no parameters , There are several parameters
6. Type of parameter : Positional arguments , Default parameters , Indefinite length parameter (*args,**kwargs)
7. When called , Required position parameters , Default parameters can be omitted , You can also use keywords to pass parameters ( Shape parameter = Actual parameters ), Variable length parameters can be passed to multiple
8. Function after call , Output to users , There are inputs and outputs , Feedback
9. Return value ,return Keyword implementation
1. Function none return, The default return value after the call is None
2.return value , Values can be any type
3.return You can not follow the value , Indicates that the return is None
4. When you call a function , encounter return, It means that the function call ends
10. Accept the output of the function : Variable = Function call
'''
# Homework after class
'''
1、 Defined function :( requirement : Define function processing logic .input The input operation is outside the function .)
Multiply all the numbers entered by the user to 20 Take the remainder , The number of numbers entered by the user is uncertain
'''
print(' The first 1 topic ,********************************************************************************')
numb_1 = input(' Please enter a number :')
def pou(my_list):
my_list2 = my_list.split(',')
nice = 1
for k in my_list2:
nice *= int(k)
return nice % 20
print(pou(numb_1))
# 2、 Write function , Check the length of the incoming list , If it is greater than 2, So just keep the first two lengths , And return the new content to
print(' The first 2 topic ,********************************************************************************')
def check_list1(list2): # Use the function to check the incoming list 2
if len(list2) > 2: # If the list 2 Is longer than 2
list3 = list2[0:2]
return list3
else:
return list2
list4 = [1, 2, 3, 4, 5]
print(check_list1(list4))
# 3、 List to heavy
# Define a function def remove_element(m_list):, Will list [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1] Remove duplicate elements
print(' The first 3 Problem list de duplication ,********************************************************************************')
my_list1 = [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1] # Define a list 1
def remove(my_list): # Define a function
my_list2 = set(my_list) # Make a list 1 duplicate removal
print(my_list2) # Print the list after de duplication 2
remove(my_list1)
'''
4. Write the following program ( requirement : Define function processing logic .input The input operation is outside the function .)
Try function encapsulation :
Enter a person's height (m) And weight (kg), according to BMI The formula ( Weight divided by the square of height ) Calculate his BMI Index
a. for example : One 65 Kilogram people , Height is 1.62m, be BMI by : 65 / 1.62 ** 2 = 24.8
b. according to BMI Index , Give corresponding reminders
lower than 18.5: Over light 18.5-25: normal 25-28: overweight 28-32: obesity higher than 32: Severe obesity
'''
print(' The first 4 topic *************************************************************')
# The first method
height = float(input(' Please enter your height (m):')) # Enter the height
weight = int(input(' Please enter your weight (kg):')) # Enter the weight
BMI = weight / (height**2) # according to BMI The formula ( Weight divided by the square of height ) Calculate his BMI Index
if BMI < 18.5: # Conditions 1,BMI The index is below 18.5, Execute this condition
print(' Yours BMI The index is too light ')
elif 18.5 <= BMI < 25: # Conditions 2,BMI The index is greater than or equal to 18.5 Less than 25, Execute this condition
print(' Yours BMI The index is normal ')
elif 25 <= BMI < 28: # Conditions 3,BMI The index is greater than or equal to 25 Less than 28, Execute this condition
print(' Yours BMI The index shows you are overweight ')
elif 28 <= BMI < 32: # Conditions 4,BMI The index is greater than or equal to 28 Less than 32, Execute this condition
print(' Yours BMI The index shows that you are obese ')
else: # Conditions 5,BMI Index greater than 32, Execute this condition
print(' Yours BMI The index shows severe obesity ')
# The second method
def get_bmi(height,weight):
bmi = weight / height**2
if bmi < 18.5: # Conditions 1,BMI The index is below 18.5, Execute this condition
return ' Yours BMI The index is too light '
elif 18.5 <= bmi < 25: # Conditions 2,BMI The index is greater than or equal to 18.5 Less than 25, Execute this condition
return ' Yours BMI The index is normal '
elif 25 <= bmi < 28: # Conditions 3,BMI The index is greater than or equal to 25 Less than 28, Execute this condition
return ' Yours BMI The index shows you are overweight '
elif 28 <= bmi < 32: # Conditions 4,BMI The index is greater than or equal to 28 Less than 32, Execute this condition
return ' Yours BMI The index shows that you are obese '
else: # Conditions 5,BMI Index greater than 32, Execute this condition
return ' Yours BMI The index shows severe obesity '
h = 1.65
w = 90
bo = get_bmi(h,w)
print(' And what you get is :{}'.format(bo))
# 5. Define a function , Pass in a dictionary and a string , Determine whether the string is a value in the dictionary , If the string is not in the dictionary , Is added to the dictionary , And return to the new dictionary
print(' The first 5 topic ,********************************************************************************')
def add(di_1,st_1): # Define a function , Dictionaries 1 And string 1
di_1 = {'age': 15,'sex': ' male '} # Define a dictionary 1
st_1 = 'python30' # Define a string 1
if st_1 not in di_1: # If the string 1 Not in the dictionary 1 In the words of
di_1[st_1] = ' I'm going bald ' # Then add a string to the dictionary
else: # conversely
print(' This already exists !')
return di_1 # Return the value of the dictionary to end the function call
r = add({'age':12,'sex':'bbu'},'morn') # Given value
print(r)
# 6. By defining a calculator function , The calling function passes two parameters , Then prompt for selection 【1】 Add 【2】 reduce 【3】 ride 【4】 except operation , Select and return the value of the corresponding operation .
print(' The first 6 topic ,********************************************************************************')
numb = int(input(' Please choose :[1] Add [2] reduce [3] ride [4] except :')) # use input To enter the desired number
def choinse(a,b): # Define a function
if numb == 1: # If the input number equals 1
cou1 = a + b # Then perform 1 This condition
return cou1 # Call the return value and end the function call
elif numb == 2: # If the input number equals 2
cou2 = a - b # Then perform 2 This condition
return cou2 # Call the return value and end the function call
elif numb == 3: # If the input number equals 3
cou3 = a * b # Then perform 3 This condition
return cou3 # Call the return value and end the function call
elif numb == 4: # If the input number equals 4
cou4 = a / b # Then perform 4 This condition
return cou4 # Call the return value and end the function call
else: # If you enter except 1,2,3,4 Values other than execute this
print(' Please select the operation method you want ')
return # Call the return value and end the function call
res = choinse(30,7) # Accept return value
print(res)
'''
7. A football team is looking for age in 15 To the age of 22 A - year-old girl is a cheerleader ( Include 15 Age and 22 year ) Join in . Write a program , Ask the user's gender and age ,
Then a message is displayed indicating whether the person can join the team , inquiry 10 Next time , Output the total number of people who meet the conditions .
( requirement : Define function processing logic . however input The input operation is outside the function . stay for Cycle of , call input And their own defined functions )
'''
print(' The first 7 topic ,********************************************************************************')
def search(count): # To define a function
num = 0
for count in range(0,count): # The number of times you need to cycle
sex = input(' Please enter the child's gender :') # Enter gender
if sex == ' Woman ': # Conditions 1, If the entered gender is equal to the condition 1 Execute next line
age = int(input(' Please enter the child's age :')) # Enter the age
if 15 <= age <= 22: # Conditions 2 , If the age entered is equal to the condition 2 Execute next line
num += 1 # The number of cycles is increased each time 1
print(' congratulations , You can join the team ') # Conditions 1, Conditions 2 All satisfied with , Execution printing
else: # conversely , Not meeting the conditions 2, perform
print(' I'm sorry your age doesn't meet the requirements ')
else: # conversely , Not meeting the conditions 1, perform
print(' I'm sorry your gender doesn't meet the requirements ')
print(' Altogether {} People meet the requirements , You can join Lala right '.format(num)) # Use format Function statistics execution 10 The second condition
search(10) # Call function

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved