#Python a summary of the relevant knowledge points for---functions:

Source: Internet
Author: User
Tags define local function definition types of functions

#1: Defining functions
Def printinfo ():
Print ("I love python!")

#调用函数
#注意: The function definition is not executed by default and can only be done by calling it
Printinfo ()

#2: Passing information to a function: that is, parameters
#求两个数的和
def sumnum (b): #这里的a, B is formal parameter (formal parameters)
Print ("%d"% (a+b))

Sumnum (10,20) #这里的10, 20 is the actual parameter passed in (argument)

#3: Positional arguments/keyword arguments: When you call a function with parameters, you can specify the order of the arguments
def mypet (PetType, PetName):
Print ("My pet is a" +pettype+ ", its name is" +petname+ ")

#以下两种调用方式输出的结果一样
Mypet (pettype = ' Puppy ', petname = ' Jenson ')
Mypet (petname = ' Jenson ', pettype = ' puppy ')

#4: A function with a return value
Def sumnum (A, B):
Return a+b

#调用函数, by the way, saves the function's return value for later use
result = Sumnum (11,22)
Print (Result)


#5: Four common types of functions
‘‘‘
No parameter, no return value (as above 1)
No parameters, with return values (see below)
With parameters, no return value (as above 2)
With parameters, there are return values (as above 4)
‘‘‘
Def getId ():
Return 2001234

Idnum = GetId ()
Print ("id =%d"%idnum)


#6: Nested calls to functions

Def testA1 ():
Print ("Start executing function A1 ...")

Def TestA ():
Print ("Start executing function a ...")
TestA1 ()
Print ("Function a execution ends.")

TestA ()

#函数嵌套调用实例: Write a function to calculate the number of three and the average of three
def getsum (a,b,c):
sum = a + B + C
return sum

Defavgvalue (A,B,C):
result = Getsum (a,b,c)
Average = result/3.0
return average

result = Avgvalue (20,30,40)
Print (the average of three numbers is:%f "%result)

#7: Local variables and global variables for functions
‘‘‘
A local variable, which is a variable defined inside a function
Different functions can define local variables of the same name, but each use of the individual will not have an effect
The role of local variables, in order to temporarily save the data need to define variables in the function to be stored, which is its role
‘‘‘

def test1 ():
A = #这里的a就是局部变量, only works within the Test1 function

Def test2 ():
Print ("a=%d"%a) #在test2中不能使用a

Test1 ()
#test2 () #报错
#print ("a=%d"%a) #会报错


#如果一个变量既能在这个函数中使用也能在其他函数中使用, then such a variable is a global variable
A = #全局变量
def test1 ():
Print (a)

Def test2 ():
Print (a)

Test1 ()
Test2 ()

#全局变量和局部变量名称可以相同
b = 1000
Def testA2 ():
b = #这里打印的b是局部变量
Print (b)

Def testA3 ():
Print (b) #这里打印的b是全局变量

TestA2 ()
TestA3 ()

#如果需要在函数中修改全局变量, then you need to declare it with global, or it will go wrong.
c = 1000
Def testB1 ():
Global C
Print ("Pre-modification: c=%d"%c)
C = 2000
Print ("Modified: c=%d"%c) #这里打印的c的值已经发生变化

Def testB2 ():
Print (c) #这里打印的c的值也将发生变化

TestB1 ()
TestB2 ()

#练习一: Calculates the 1~ of the specified number of

#定义求和函数, there is a return value
def getsum (num):
i = 1
sum = 0
While I<=num:
Sum+=i
I+=1

return sum

#将返回值保存在一个变量中
result = Getsum (1000)
Print ("-" *20)
Print ("Sum result:%d"%result)
Print ("-" *20)


#练习二: Business Card Management System First Edition

#主界面函数: 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 Business Card ")
Print ("4. Query Business Card ")
Print ("5. Traverse Business Card ")
Print ("6. Exit System ")
Print ("-" *30)

#获取用户输入的信息: There are no parameters, there is a return value
Def getchoice ():
selectedkey = Int (Input ("Enter the selected ordinal:"))
Return Selectedkey

#有参数, no return value
def printallinfo (namelisttemp):
Print ("=" *20)
For temp in namelisttemp:
Print (temp)
Print ("=" *20)

NameList = []
i = 0
While i<10:

 #打印提示
DisplayMenu ()

  #等待用户选择
Key = Getchoice ()

If key = = 1:
Print ("You have selected business card add Features")
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 wrong, please re-enter!")

I+=1


#练习三:

‘‘‘
To prepare the Student management System (first edition), the initial requirements are as follows:
You must use a custom function to complete the modularity of the program
Student confidence includes at least: name, age, school number, and can be added appropriately
Features that must be completed: Add, delete, modify, query, Traverse, exit
‘‘‘

#定义一个列表用来存储多个学生的信息
Stulist = []

#定义系统菜单显示函数
Def displaymenu ():
  #完成显示系统菜单的功能
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 Student Management System ")
Print ("*" *40)

def addnewstu (tempstulist):
  #完成添加学生信息的功能
Name = input ("Please enter student's name:")
Stuid = input ("Please enter student's number:")
Age = Input ("Please enter student's ages:")

  #定义一个字典用来存储每个学生的信息
Studict = {}
studict[' name '] = Name
studict[' stuid '] = Stuid
studict[' age ') = Age

#将每个学生的信息添加到列表中
Tempstulist.append (studict)

Def delstu ():
  #完成删除学生信息的功能
delnum = Int (Input ("Enter the number of the student you want to delete:"))
Del Stulist[delnum]

Def revisestu ():
  #完成修改学生信息的功能
revisenum = Int (Input ("Enter the number of the student you want to modify:"))
Tempstudict = Stulist[revisenum]
#输入要修改学生的信息
NewName = input ("Please enter the name of the student to be modified:")
Newstuid = input ("Please enter student's number 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 ():
   #完成查询学生信息的功能
inquirenum = Int (Input ("Enter the number of the student you want to query:"))
Inquirestudict = Stulist[inquirenum]
Print ("The student you are inquiring about is:")
Print ("Name:%s School Number:%s Age:%s"% (inquirestudict[' name '], inquirestudict[' Stuid '), inquirestudict[' ages '))

Def bianlistu ():
   #完成遍历学生信息的功能
Print ("Name Number Age")
For Tempstu in Stulist:
Print ("%s%s"% (tempstu[' name '], tempstu[' Stuid '], tempstu[' age '))

While True:

   #提示用户选择功能
key = Int (Input ("Enter the function number you selected:"))
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 ("Pro, are you sure you want to exit?") (y/n) ~~~~>_<~~~~ ")
if ssmu = = ' Y ':
Break
Else
Print ("Input wrong, please re-enter!")

#Python a summary of the relevant knowledge points for---functions:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.