"python019--Functions and processes"

Source: Internet
Author: User

I. Functions and processes

1, Python only function no process

>>> def hello ():
Print (' Hello fishc! ')
>>> temp = Hello ()
Hello fishc!
>>> Temp
>>> Type (temp)
<class ' Nonetype ' >
>>>

Explanation: Hello is assigned to temp, and the value returned by individual temp is none

2. Python can return multiple values

>>> def back ():
return [1, ' Dusty ', 3.14]

>>> back ()
[1, ' Dusty ', 3.14]
>>> def back ():
Return 1, ' Dusty ', 3.14
---Use a list to return multiple values
>>> back ()
(1, ' dusty ', 3.14)
---return multiple values using tuples

Second, local variables and global variables

Locals: Local Variable global variables: Globals Variable

Arguments within functions and variables called local variables, variables outside the function are global variables and local variables cannot be accessed outside the function

1. Local variables for out-of-function

def discounts (price,rate):
Fina_price = Price * Rate #局部变量
Return Fina_price

Old_price = float (input (' Please enter the original price: '))
Rate = Float (input (' Please enter discount ratio: '))
New_price = Discounts (old_price,rate)
Price (' After a discount: ', New_price)
Print (the value of the ' out-of-function printing local variable final_price: ', Final_price) #函数外调用局部变量final_price

================= RESTART:/users/wufq/desktop/Global variables & local variables. PY =================
Please enter the original price: 100
Please enter a discount rate: 0.8
Traceback (most recent):
File "/users/wufq/desktop/global variable & local variable. py", line 8, in <module>
Price (' After a discount: ', New_price)
Nameerror:name ' price ' isn't defined

Why the error? Reason: A local variable cannot be accessed outside the function

2. Calling global variables within a function

def discounts (price,rate):
Fina_price = Price * Rate #局部变量
Old_price = 50
Print (' Modified Old_price1: ', Old_price)
Return Fina_price

# Old_price,rate,new_price are global variables, scoped throughout the file, the entire module
Old_price = float (input (' Please enter the original price: '))
Rate = Float (input (' Please enter discount ratio: '))
New_price = Discounts (old_price,rate)
Print (' Old_price2 before modification: ', old_price)
Print (' Price after Discount: ', New_price)

================= RESTART:/users/wufq/desktop/Global variables & local variables. PY =================
Please enter the original price: 100
Please enter a discount rate: 0.8
Modified OLD_PRICE1:50
old_price2:100.0 before the change
Price after discount is: 80.0
>>>

Explain:
1, the printed content can be seen in the results or according to the value of the variable before the change
2, modify the global variable Old_price in the function, will generate a new local variable, but the name and all variables are the same, strongly require to prohibit the definition of a variable name within the function
Local variables with the same name as the global variable

Three, exercises

1, write a function, determine whether the passed string parameter is "back to Federation" (back to federation that is written in palindrome form couplets, can be read, can also be inverted read. For example: Shanghai tap water from the sea)

Ideas:

A, determine the length of the input string, the last one, determine the middle position, the flag bit

B, comparing the first and last, and finally descending after the contrast

def palindrome (String):
Length = Len (string) #获取输入string的长度
last = Length-1 #序列是从索引0开始计数, find the index of the final character, namely: subscript
Length//=2 #地板除, take half of the length of the string so that the back of the For loop half string comparison
Flag = 1 #标记位, always 1 is back Federation

For per in range (length): #理解难点, one by one comparison of elements with a for loop, each taking 0,1,2,3
If string[each]!= String[last]: #前后一个一个的对比
Flag =0 #如果不一样, flag = 0, that is: non-return

Last-=1 #对比完一组以后, in descending contrast to the second group

#通过flag是否等于1, to decide if it's back to the text.
If flag ==1:
Return 1
Else
return 0

String = input (' Please enter a word: ')
If Palindrome (string) ==1:
Print ("Back to the text")
Else
Print ("Not back to text")

2, Python implementation of the centralized method of reversing strings

Invert string = "abcdef" to "FEDCBA"

string = "ABCdef"

#第一种: Using string slices
def string_reverse1 (String):
return String[::-1]

Print ("string_reverse1=", String_reverse1 (String))

#第二种: Using the reversed () function
def string_reverse2 (String):
Return '. Join (Reversed (string))

#join () function: Generates a new string from the elements in the sequence with the specified character connection

Print ("string_reverse2=", String_reverse2 (String))

#第三种: Position of letters before and after swapping
def string_reverse3 (String):
T=list (String)
L = Len (t)

The #zip () function is used to take an iterative object as an argument, package the corresponding element in the object into a tuple, and then return an object consisting of these tuples
#如果各个迭代对象的元素个数不一致, the returned object is the same length as the shortest possible iteration object
#利用 * operator, which, in contrast to zip, extracts
For i,j in Zip (range (l-1,0,-1), Range (L//2)):
T[i],t[j]=t[j],t[i]

Return '. Join (t)

Print ("string_reverse3=", String_reverse3 (String))

The "For Loop" is a difficult point to parse at 1.1 points:
1. List List (range (l-1,0,-1)), the result is: [5, 4, 3, 2, 1] here the l=6
2. List List (range (L//2)), the result of the printing is: [0, 1, 2]
3, Zip (range (l-1,0,-1), Range (L//2)), Printed results: [(5, 0), (4, 1), (3, 2)]
4, T[i],t[j]=t[j],t[i], is to exchange the contents of the meta-group into [(0, 5), (1, 4), (2, 3)]
5, using join (t), is to concatenate the characters in the tuple into a new string, that is, exchanged, became: FEDCBA ""

#第四种: A recursive way to output one character at a time
def string_reverse4 (String):
If Len (String) <= 1:
return string
Return String_reverse4 (string[1:]) +string[0]

Print ("string_reverse4=", String_reverse4 (String))

#第五种: Output from left to right using for loop
def string_reverse5 (String):
#return '. Join (String[len (String)-i] for I in range (1, len (string) +1))
Return '. Join (String[i] for I in Range (len (String)-1,-1,-1))
Print ("string_reverse5=", String_reverse5 (String))

3. Write a function that counts the number of letters, spaces, numbers, and other characters of the passed-in string parameter, respectively.
--python There are 4 ways to pass, the required parameter fun (param), the default argument fun (param=value), the keyword parameter fun (**param), variable parameter fun (*param)
#1, Required parameters fun (param)
#定义函数时参数个数, the order has been defined, in the call function, the number of parameters, the order must be consistent, no more can not be less or disorderly

def test (PARAM1,PARAM2,PARAM3):
Print (PARAM1,PARAM2,PARAM3)

Test (1, ' hello ', ' dusty ')
Test (' Hello ', 1, ' dusty ')

"' Execution Result:
1 Hello Dusty
Hello 1 dust-laden ""
Print (' ************************* ')
#2, default parameter fun (Param=value)
#a, defining a function, a default value has been passed to the parameter, and when the function is called without a re-argument, the default value of the parameter is displayed
#b, if the required parameter and default parameter are also present, the default parameter must follow the required parameter
#c, if you have more than one default parameter, the call order can be inconsistent, but you must display which default parameter is indicated, but it is recommended to use it in a uniform order defined by the function

def fun (param1,param2 = 100,param3= True):
Print (PARAM1,PARAM2,PARAM3)

Fun (1)
Fun (1,200) #默认参数在必选参数后面
Fun (1,param3=false,param2=300) #调用顺序也可以不一致

"' Execution Result:
1 True
1 True
1 False "

Print (' ************************* ')
#3, optional parameter fun (*param)
#a, when defining a function, when the number of arguments passed is indeterminate, it could be 0, 1, 2 ... When multiple, optional parameters can be selected, writing format is the parameter name plus a * number
#b, optional parameters are called in the form of a tuple tuple, that is, Param is a tuple
#c, when an optional parameter is defined, a list or tuple can be passed as a parameter, simply by adding the * number in front of the pass
#d, when there are required parameters, default parameters, optional parameters, must be defined as required, default, optional parameters

def fun (PARAM1,PARAM2=100,*PARAM3):

Def fun1 ():
Print (PARAM1,PARAM2)

Def fun2 ():
Print (Param1,param2,param3,type (PARAM3))

Fun2 () If Len (param3)!=0 else fun1 ()

Fun (1,2,3,4,5,6) #验证可选函数在调用时是已一个tuple元组形式存在
Li =[1,2,3]
Ti= (a)
Fun (1,2,*li) #验证传入的可变参数是一个列表
Fun (1,2,*ti) #验证 the variable parameter passed in is a tuple
Fun ($)

"' Execution Result:
1 2 (3, 4, 5, 6) <class ' tuple ' >
1 2 (1, 2, 3) <class ' tuple ' >
1 2 (1, 2, 3) <class ' tuple ' >
1 2 "

Print (' ************************* ')
#4, keyword parameter fun (**param)
#a, when defining a function, you can also choose the keyword argument when the number of arguments passed in is undefined, and the difference from an optional parameter is that the parameter must be passed in the form of a default parameter, for example: Param1=1,param2 =2
#b, the keyword parameter is called in the form of a dict dictionary, that is, param
#c, define a keyword parameter, you can pass a list as a whole, just need to add * * At the time of delivery
#d, when there are required parameters, default parameters, optional parameters, keyword parameters, must be defined according to required, default, optional, keyword parameters

def fun (PARAM1,PARAM2=100,*PARAM3,**PARAM4):

Def fun1 ():
Print (PARAM1,PARAM2)

Def fun2 ():
Print (Param1,param2,param3,param4,type (PARAM4))

Fun2 () If Len (param3)!=0 and Len (param4)!=0 else fun1 ()

Fun (1,2,3,4,a=5,b=6,c=7) #验证可选函数在调用时是已一个tuple元组形式存在, the keyword function exists in the form of a dictionary when it is called
dict= {"A": 1, "B": 2, "C": 3}
Fun (1,2,3,4,**dict) #传入的可变参数是一个字典dict
Fun ($)

#需求: Write a function that counts the number of letters, spaces, numbers, and other characters of the passed string parameter, respectively

def count (*param): #可选参数
length = Len (param) #获取传入参数的长度

For I in range (length):

#给英文字母, spaces, numbers, and one of the other initial values
Letter = 0
Space = 0
Digit = 0
others = 0

#在参数内进行循环判断
For each in Param[i]:
If Each.isalpha ():
Letter +=1
Elif Each.isspace ():
Space +=1
Elif Each.isdigit ():
Digit +=1
Else
Others +=1

Print ('%d ' string total: English letter%d, space%d, number%d, other characters%d '% (i+1,letter,space,digit,others))

Count (' I love the www.yizhibo.com/666 ', ' I love you ', ' You Love Me ')

"' Execution Result:
1th string total: English alphabet 18, Space 2, number 3, other characters 3
2nd string Total: English alphabet 8, Space 2, number 0, other characters 0
3rd string Total: English alphabet 9, Space 2, number 0, other characters 0
‘‘‘







"python019--Functions and processes"

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.