Python tutorial (learning Python) --2.3.5 Python returns a value problem

    Function this section to learn Python is how to return more than one value problem.

    Found surprised when learning Python, Python function can return multiple values, very interesting.

#define function sum
def sum(x, y):
   z = x + y
   x = x ^ y
   y = x ^ y
   x = x ^ y   
   return z, x, y

#define function main
def main():
   a = int(raw_input("plz input a "))
   b = int(raw_input("plz input b "))
   c = sum(a, b)
   print(c)

#entry of programme
main()

  Have a look first to the execution of the program results

plz input a 12
plz input b 13
(25, 13, 12)

  Results (25,13,12) this seems strange, this is Python tuple (tuples), a new term, we will never mind behind list will mention. In the function sum, in addition to sum (line third) in addition to exchange X and the y value of the operation (fourth ~ 6), return to the Z, x, y (seventh lines) to the main function of the C (line thirteenth) print results (line fourteenth), indeed X and y exchange the value of.

    The main function in the A and B change? A or 12, B or 13? We in the main function in the print (c) (Fourteenth) after two print statements, print a and b values (line 15,16), a and B did not have a look?

#define function sum
def sum(x, y):
   z = x + y
   x = x ^ y
   y = x ^ y
   x = x ^ y   
   return z, x, y

#define function main
def main():
   a = int(raw_input("plz input a "))
   b = int(raw_input("plz input b "))
   c = sum(a, b)
   print(c)
   print(a)
   print(b)

#entry of programme
main()

  The operation results 

plz input a 12
plz input b 13
(25, 13, 12)
12
13

  

    The conclusion is not affected a and b values.







    Call the sum function, the A and b values for X and y a (A and X point to 12 local data unit (b) and Y point to 13 local data unit), in the sum function x and Y through the exchange operation, change the data unit to perform X and Y direction.





Zhi Pu education Python www.jeapedu.com

———————————————————————————————————————————

Posted by Frances at November 21, 2013 - 5:54 AM