1, function.
defprofit (volume, price,cost):Print("We sell%d ice cream a day."%volume)Print("You can buy a ice cream at the price of%d dollars"%Price )Print("Make an ice cream would cost us%d dollars."%Cost )Print("Then we daily profit can be%d dollars."% ((price-cost) *volume))Print("We can just give the function numbers directly:") Profit (500,20,10)Print("Or We can use the variables from our script:") Volume= 200 Price=10 Cost= 3profit (Volume,price,cost)
Output Result:
2, functions and files.
fromSysImportArgvscript, Input_file=argvdefPrint_all (f):Print(F.read ())defRewind (f): F.seek (0)defPrint_a_line (line_count,f):Print(Line_count,f.readline ()) Current_file=Open (input_file)Print("First let ' s print the whole file:\n") Print_all (current_file)Print("Now let's rewind, kind of like a tape).") Rewind (current_file)Print("Let ' s print three lines:") Current_line= 1print_a_line (current_line,current_file) current_line= Current_line+1print_a_line (current_line,current_file) current_line= Current_line+1print_a_line (current_line,current_file)
Output Result:
To understand the role of + = , I changed the code to:
fromSysImportArgvscript, Input_file=argvdefPrint_all (f):Print(F.read ())defRewind (f): F.seek (2)defPrint_a_line (line_count,f):Print(Line_count,f.readline ()) Current_file=Open (input_file)Print("First let ' s print the whole file:\n") Print_all (current_file)Print("Now let's rewind, kind of like a tape.") Rewind (current_file)Print("Let ' s print three lines:") Current_line= 1print_a_line (current_line,current_file) current_line+ = Current_line+1print_a_line (current_line,current_file)
Output Result:
As you can see, the contents of the second line are not printed.
Conclusion:
A+ =B is the a=a+b
3.return
defAdd (A, b):Print("ADDING%d +%d"%(A, b))returnA +bdefSubtract (A, b):Print("subtracting%d-%d"%(A, b))return(A-b)defMultiply (A, b):Print("multiplying%d *%d"%(A, b))return(A *b)defDivide (A, b):Print("dividing%d/%d"%(A, b))return(Ab)Print("Let's do some math with just functions!") Age= Add (30,5) Height= Subtract (70,4) Weight=multiply (90,2) IQ= Divide (150,2)Print("Age :%d, Height:%d, Weight:%d, IQ:%d"%(AGE,HEIGHT,WEIGHT,IQ))Print("Here is a puzzle.") What= Add (age, Subtract (height,multiply (weight, divide (iq,2))))Print("that becomes:", What,"\ nthe Can do it by hand?")
Output Result:
Python Learning 7--function