220
How_to create_lib.txt
### Part1 ### You should not include UI functions in library or backend functions/methods. ### The purpose of function is to reuse the code. #Here is the wrong way, def fullName(fname, lname): print("My name is ", fname, " ", lname) #Here is the correct way def fullName(fname, lname): return (fname, " ", lname) #The caller can do add any message to the name such as print("Hello Mr. ", fullName("James","Bond")) or print("Hello Mrs. ", fullName("Peggy","Bundy")) ### Part2 ### calling def function from loop def fullName(fname, lname): return (lname+', '+fname) while True: wfname = input("Enter first name -> ") wlname = input("Enter last name -> ") wname = fullName(wfname, wlname) print("Hello my name is", wname) print("\n") yn=input("more names? y/n -> ") if yn=="y": continue else: print("Thanks for using our system ") break #*--- the output """ Enter first name -> James Bond Enter last name -> Bond Hello my name is Bond, James Bond more names? y/n -> y Enter first name -> Al Bundy Enter last name -> Bundy Hello my name is Bundy, Al Bundy more names? y/n -> n Thanks for using our system """ ### Part 3 ### Why should not use print() or input() in library function. ### or function for reuse. # here is add() def add(fn, sn): return fn+sn # using add() print(add(5,7)) # now we need a function to double add() def double_add(fn,sn): return 2*add(fn,sn) # if add() has any UI function such print() or input() # you will not be able to do 2*add() # test double_add() print( double_add(5,7))
Test_lib.py
def g_add(n1,n2): return n1+n2 def double_g_add(n1,n2): return g_add(n1,n2) * 2 """ Bad functions These functions contain UI such as print(), input()... def b_add(n1,n2): print("The result ",n1+n2) def double_b_add(n1,n2): return b_add(n1,n2) * 2 """
Test_lib_prg.py
import Test_lib as tl # if you do this all functions must be prefexed with tl after "as" # this is the prefered method for clarity """ or you can do this from Test_lib import scalc or this from Test_lib import * The above you do not have to prefex the library name """ n1=2 n2=4 print(tl.g_add(n1,n2)) print(tl.double_g_add(n1,n2)) print("The numbers are",n1,",",n2,"The sum is", tl.g_add(n1,n2), "and the double is",tl.double_g_add(n1,n2)) """ Play with this code in www.pythontutor.com def g_add(n1,n2): return n1+n2 def double_g_add(n1,n2): return g_add(n1,n2) * 2 def b_add(n1,n2): print("The sum ",n1+n2) def double_b_add(n1,n2): return b_add(n1,n2) * 2 ### test functions print("Good functions") print(g_add(5,7)) print(double_g_add(5,7)) print("Bad functions") print("The result is ",b_add(5,7)) print("The double is ",double_b_add(5,7)) """