#Python---Function-related knowledge points summary 1:

#1:Define function
def printInfo():
print("I love Python!") #Call

function
#Note: After the function is defined, it will not be executed by default, it can only be executed by calling
printInfo()

 

#2: Pass information to the function: that is, the parameter
# find the sum of two numbers
def sumNum(a,b): #here a,b are formal parameters (formal parameters)
  print("%d"%(a+b) )

sumNum(10,20) #10,20 here are the actual incoming parameters (actual parameters)

#3: Positional Arguments/Keyword Arguments: When calling a function with arguments, you can specify the order of arguments
def myPet(petType, petName):
  print("My pet is a "+petType+", its name is "+petName+".")

#The output of the following two calling methods is the same
myPet(petType = 'puppy', petName = 'jenson')
myPet(petName = 'jenson', petType = 'puppy')

 

#4: Function with return value
def sumNum(a,b):
  return a+b

#Call the function and save the return value of the function for later use
result = sumNum(11,22)
print(result)


#5: The four common types of functions
'''
have no parameters, no return value (as in 1 above),
no parameters, with return values ​​(as follows),
with parameters, and no return values ​​(as in 2 above)
with parameters and return values ​​( As above 4)
'''
def getId():
  return 2001234

idNum = getId()
print("id = %d"%idNum)


#6: Nested Calls of Functions

def testA1():
  print("Start executing function A1...")

def testA():
  print("Start executing function A...")
  testA1()
  print("Function A execution ends.")

head()

 

#Function nested call example: write a function to calculate the sum of three numbers, and find the average of the three numbers
def getSum(a,b,c):
  sum = a + b + c
  return sum

def avgValue(A,B,C):
  result = getSum(A,B,C)
  average = result/3.0
  return average

result = avgValue(20,30,40)
print("The average of the three numbers is: %f"%result)

 

#7: Local variables of functions and global variables
'''
local variables are functions with
different variables defined inside the function. Local variables with the same name can be defined, but each of them will not affect
the effect of local variables. In order to temporarily save data, you need to define variables in the function for storage, this is what it does
'''

def test1():
  a = 100 #here a is a local variable, which only works within the test1 function

def test2():
  print("a=%d"%a) #a cannot be used in test2

test1()
#test2() #Error #print
("a=%d"%a) #Error will be reported


#If a variable can be used both in this function and in other functions, such a variable is a global variable
a = 1000   #global variable
def test1():
  print(a)

def test2():
  print(a)

test1()
test2()

#The names of global variables and local variables can be the same
b = 1000
def testA2():
  b = 2000 #The b printed here is the local variable
print(b)

def testA3():
  print(b) #The b printed here is the global variable

testA2 ()
testA3()

 

#If you need to modify the global variable in the function, then you need to declare it with global, otherwise an error will occur
c = 1000
def testB1():
  global c
  print("Before modification: c=%d"%c)
  c = 2000
  print( "After modification: c=%d"%c) #The value of c printed here has changed

def testB2():
  print(c) #The value of c printed here will also change

testB1()
testB2()

 

#Exercise 1: Calculate the sum of 1~specified number

#Define a summation function with a return value
def getSum(num):
  i = 1
  sum = 0
  while i<=num:
    sum+=i
    i+=1

  return sum

#Save the return value in a variable
result = getSum(1000)
print("-"*20)
print("Sum result is: %d"%result)
print("-"*20)


#Exercise 2: The first version of the business card management system

#Main interface function: no parameter, no return value
def displayMenu():
  print("-"*30)
  print(" Business Card Management System V6.0")
  print(" 1. Add business card")
  print(" 2. Delete business card ")
  print(" 3. Modify the business card")
  print(" 4. Query the business card")
  print(" 5. Traverse the business card")
  print(" 6. Exit the system") 
  print("-"*30)

#Get user input Information: no parameters, there is a return value
def getChoice():
  selectedKey = int(input("Please enter the selected serial number: "))
  return selectedKey

#With parameters, no return value
def printAllInfo(nameListTemp):
  print("="*20)
  for temp in nameListTemp:
  print(temp)
  print("="*20)

nameList = []
i = 0
while i<10: #Print

  prompt
  displayMenu() #Wait

  for the user to select
  key = getChoice()

  if key == 1:
    print("You have selected the function of adding a business card")
    newName = input("Please Enter name: ")
    nameList.append(newName)
  elif key == 3:
    pass
  elif key == 4:
    pass
  elif key == 5:
    printAllInfo(nameList)
  elif key == 6:
    break
  else:
    print("Input error , please re-enter!")

  i+=1


#Exercise three:

'''
Write "Student Management System" (first edition), the initial requirements are as follows:
must use custom functions, complete the modularization of the program.
Students confidence at least include: name, age, student number, in addition to this can be appropriately added
must Completed functions: add, delete, modify, query, traverse, exit
'''

#Define a list to store the information of multiple students
stuList = []

#Define the system menu display function
def displayMenu(): #Complete
  the function of displaying the system menu
  print("*"*40)
  print("Student Management System V2.0")
  print(" 1. Add student information")  
  print(" 2. Delete student information")
  print(" 3. Modify student information")
  print(" 4. Query student information")
  print(" 5. Traverse student information")
  print(" 6. Exit the student management system")
  print( "*"*40)

def addNewStu(tempStuList): #Complete
  the function of adding student information
  name = input("Please enter the student's name:")
  stuId = input("Please enter the student's student number:")
  age = input("Please enter the student's age :") #Define

  a dictionary to store the information of each student
  stuDict = {}
  stuDict['name'] = name
  stuDict['stuId'] = stuId
  stuDict['age'] = age #The

  information of each student add to list
  tempStuList.append(stuDict)

def delStu(): #Complete
  the function of deleting student information
  delNum = int(input("Please enter the number of the student you want to delete: "))
  del stuList[delNum]

def reviseStu(): #Complete
  the function of modifying student information
  reviseNum = int(input("Please enter the number of the student you want to modify: "))
  tempStuDict = stuList[reviseNum] #Enter
  the student's information to be modified
  newName = input(" Please enter the name of the student to be modified:")
  newStuId = input("Please enter the student ID of the student to be modified:")
  newAge = input("Please enter the age of the student to be modified:")
  tempStuDict['name'] = newName
  tempStuDict['stuId'] = newStuId
  tempStuDict['age'] = newAge

def inquireStu(): #Complete
  the function of querying student information
  inquireNum = int(input("Please enter the number of the student you want to query: "))
  inquireStuDict = stuList[inquireNum]
  print("The information of the student you are inquiring is:")
  print("Name: %s Student ID: %s Age: %s"%(inquireStuDict['name'], inquireStuDict['stuId '], inquireStuDict['age']))

def bianliStu(): #Complete
  the function of traversing student information
  print("Name, student number and age")
  for tempStu in stuList:
    print("%s %s %s"%(tempStu['name'], tempStu['stuId'], tempStu['age']))

while True: #Prompt the

  user to select the function
  key = int (input("Please enter the function number of your choice:"))
  print("\n")

  if key == 1:
    displayMenu()
    addNewStu(stuList)
  elif key == 2:
    delStu()
  elif key == 3:
    reviseStu()
  elif key == 4:
    inquireStu()
  elif key == 5:
    bianliStu()
  elif key == 6:
    ssmu = input("Dear, do you really want to quit? (y/n) ~~~~>_ <~~~~")
  if ssmu == 'y':
    break
  else:
    print("The input is incorrect, please re-enter!")

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324975281&siteId=291194637