from mymodule import divide print(divide(2, 4))
from mymodule import divide import sys print(sys.path) print(divide(22, 7)) print(__name__)
def test_mymodule_divide(): assert mymodule.divide(8, 3) >= -1
from mymodule import ( divide, ) import sys result = divide(10, 20) print(f'code __name__: {__name__}') print(f'result: {result}') print(f'sys.path: {sys.path}') print(f'sys.modules: {sys.modules}')
import mymodule a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) print(mymodule.add(a, b)) print(mymodule.subtract(a, b)) print(mymodule.multiply(a, b)) print(mymodule.divide(a, b))
def test_divide2(): assert abs(mymodule.divide(-4, 2) - (-2)) < TOL
# mymod module test import mymodule print(mymodule.add(10, 20)) print(mymodule.divide(10, 20)) print(mymodule.multiply(10, 20)) print(mymodule.subtract(10, 20)) print(mymodule)
#import mymodule #mymodule.divide(2,2) from mymodule import divide print(divide(10, 20)) print(__name__) import sys # Paths that python looks at to find imports print(sys.path) # Other versions of python require you to create # an __init__.py file in your directories you want # to import from. print(sys.modules)
# adding a libs folder #path = module/libs/mylib.py #sometimes it require the __init__.py file ## Catching error def divide (dividend, divisor): if divisor == 0 : return ZeroDivisionError("No 0") return dividend/divisor grades =[] try: average = divide(sum(grades), len(grades)) print(f"The grade point average is {average}.") except ZeroDivisionError as e: print(e) # prints "No 0" print("There are no grades yet") else: # not putting in try block print(f"The grade point average is {average}.") finally: print("Thanks") #Types of Error RuntimeError ValueError TypeError
def main(): i = 5 print(i) i = i + 1 print("value of i is", i) ############### Testing the method of application of string output s = """This is a multi-line string. This is the second line.""" print(s) s = "This is a string. \ This continues the string." print(s) i = 10 ** 10 print("i = 10**10 = ", i) i = 134 j = 50 k = i // j print(" i =", i, " j =", j, " k = i//j =", k) k = i % j print(" i =", i, " j =", j, " k = i%j =", k) ############### Testing the method of application of for-loop for i in (10, 12, 33, 14, 57): if ~i % 2: print(i, "is an even number.") else: print(i, "is an odd number.") for i in range(0, 3): print(i) else: print("The for loop is over with outputting range(0,3)") for i in range(0, 300, 98): print(i) else: print("The for loop is over with outputting range(0, 300, 98)") ## ############### Testing the method of application of while-if ## number = 23 ## guess = 10 ## while(guess!=number): ## guess = int(input('Enter an integer to guess: ')) ## if guess == number: ## print('Congratulations, you guessed it.') # New block starts here ## print("(but you do not win any prizes!)") # New block ends here ## elif guess < number: ## print('No, it is a little lower than that') # Another block ## # You can do whatever you want in a block ... ## else: ## print('No, it is a little higher than that') ## # you must have guess > number to reach here ## else: ## print('The while loop is over.') ## # Do anything else you want to do here ## print('Done') ## ############### Testing the method of application of break-clause ## while True: ## s = input('Enter something until with quit: ') ## if s == 'quit': ## break ## elif len(s) < 3: ## print('input string is too short to quit') ## continue ## print('Length of the string is', len(s)) ## print('Done') ############### Testing the method of application of call-funtion sayHello() printMax(100, 321) print("maximum(123,142) is", maximum(123, 142)) printMaxDoc(123, 142) print(printMaxDoc.__doc__) help(printMaxDoc) help(printMax) ############### Testing the method of application of modules print("The command line arguments are:") for i in sys.argv: print(i) print("\n\nThe PYTHONPATH is", sys.path, "\n") mymodule.sayhi() print("mymodule.version is", mymodule.version) # Fcn001.main() # the same behavior with the time import first time # print('Fcn001.version is',Fcn001.version) print("math.sqrt(10.2) =", math.sqrt(10.2)) print() print("multiply(10,21) is", mymodule.multiply(10, 21)) print("divide(10,21) is", mymodule.divide(10, 21)) print() ############### Testing the method of application of intrinsic constant if __name__ == "__main__": print("This program is being run by itself") else: print("I am being imported from another module") # print(__path__) # print(__line__) print("current file path is", __file__) ############### Testing the method of application of dir() fcn. zzz = 99 newInt = 100 print("Show the attribute-list of current module as following:") print(dir()) yy = 78 newString = "ABC" print("Show the attribute-list of current module as following:") print(dir()) del yy print("Show the attribute-list of current module as following:") print(dir()) print("Show the attribute-list of sys module as following:") # print(dir(sys)) ############### Testing the method of application of list-data-stucture shoplist = ["apple", "mango", "carrot", "banana"] print("I have", len(shoplist), "items to purchase.") print("These items are:") # Notice the comma at end of the line print("All the items :") for item in shoplist: print(item, " ", " ", sep="->", end="") else: print() shoplist.append("added001") shoplist.append("added002") shoplist.append("added001") shoplist.append(123123) shoplist.append(0.003782) sublist = [12, 32.132, "ABC", "zyx", 31, 1323.1231] shoplist.append(sublist) print("All the items :") for item in shoplist: print(item, " ", " ", sep="->", end="") else: print() print("Output the shoplist : ", shoplist) ############### Testing the method of application of tuple (diffrent from list) zoo = ("wolf", "elephant", "penguin") print("Number of animals in the zoo is", len(zoo)) new_zoo = ("monkey", "dolphin", zoo) print("Number of animals in the new zoo is", len(new_zoo)) print("All animals in new zoo are", new_zoo) print("Animals brought from old zoo are", new_zoo[2]) print("Last animal brought from old zoo is", new_zoo[2][2]) age = 22 name = "Swaroop" print("%s is %d years old" % (name, age)) # tuple mostly are used in print-clause print("Why is %s playing with that python?" % name) ############### Testing the method of application of key-value pair i.e. dictionary data structure ab = { "Swaroop": "*****@*****.**", "Larry": "*****@*****.**", "Matsumoto": "*****@*****.**", "Spammer": "*****@*****.**", } print() print("Swaroop's address is %s" % ab["Swaroop"]) # Adding a key/value pair ab["Guido"] = "*****@*****.**" # Deleting a key/value pair del ab["Spammer"] print("\nThere are %d contacts in the address-book : \n" % len(ab)) for name, address in ab.items(): print("Contact %s at %s" % (name, address)) if "Guido" in ab: # OR ab.has_key('Guido') print("\nGuido's address is %s" % ab["Guido"]) ############### Testing the method of application of sequence shoplist = ["apple", "mango", "carrot", "banana"] # Indexing or 'Subscription' operation print("Item 0 is", shoplist[0]) print("Item 1 is", shoplist[1]) print("Item 2 is", shoplist[2]) print("Item 3 is", shoplist[3]) print("Item -1 is", shoplist[-1]) print("Item -2 is", shoplist[-2]) print("Item -3 is", shoplist[-3]) print("Item -4 is", shoplist[-4]) # Slicing on a list print("Item 1 to 3 is", shoplist[1:3]) print("Item 2 to end is", shoplist[2:]) print("Item 1 to -1 is", shoplist[1:-1]) print("Item start to end is", shoplist[:]) # Slicing on a string name = "ABCDefghijk" print("characters 1 to 3 in string 'swaroop' is", name[1:3]) print("characters 2 to end in string 'swaroop' is", name[2:]) print("characters 1 to -1 in string 'swaroop' is", name[1:-1]) print("characters start to end in string 'swaroop' is", name[:]) ############### Testing the method of application of reference and copy(i.e. ref and copy) print("Simple Assignment") shoplist = ["apple", "mango", "carrot", "banana"] mylist = shoplist # mylist is just another name pointing to the same object! del shoplist[0] print("shoplist is", shoplist) print("mylist is", mylist) # notice that both shoplist and mylist both print(the same list without # the 'apple' confirming that they point to the same object print("Copy by making a full slice") mylist = shoplist[:] # make a copy by doing a full slice del mylist[0] # remove first item print("shoplist is", shoplist) print("mylist is", mylist) ############### Testing the method of application of string (deeper study especially the fucntions) name = "Swaroop" # This is a string object if name.startswith("Swa"): print('Yes, the string starts with "Swa"') if "a" in name: print('Yes, it contains the string "a"') if name.find("war") != -1: print('Yes, it contains the string "war"') delimiter = "_*_" mylist = ["Brazil", "Russia", "India", "China"] print(delimiter.join(mylist)) delimiter = " " mylistStr = delimiter.join(mylist) mylist2 = mylistStr.split(" ") print(mylist2) str = "www...google.com" print(str) str_split = str.split(".", 500) # To split the primt stirng 2 times, i.e. create two sub-segment print(str_split) print(" -- A B C-de F -- ".strip(), "End")
def main(): i = 5 print(i) i = i + 1 print('value of i is', i) ############### Testing the method of application of string output s = '''This is a multi-line string. This is the second line.''' print(s) s = 'This is a string. \ This continues the string.' print(s) i = 10**10 print('i = 10**10 = ', i) i = 134 j = 50 k = i // j print(' i =', i, ' j =', j, ' k = i//j =', k) k = i % j print(' i =', i, ' j =', j, ' k = i%j =', k) ############### Testing the method of application of for-loop for i in (10, 12, 33, 14, 57): if ~i % 2: print(i, 'is an even number.') else: print(i, 'is an odd number.') for i in range(0, 3): print(i) else: print('The for loop is over with outputting range(0,3)') for i in range(0, 300, 98): print(i) else: print('The for loop is over with outputting range(0, 300, 98)') ## ############### Testing the method of application of while-if ## number = 23 ## guess = 10 ## while(guess!=number): ## guess = int(input('Enter an integer to guess: ')) ## if guess == number: ## print('Congratulations, you guessed it.') # New block starts here ## print("(but you do not win any prizes!)") # New block ends here ## elif guess < number: ## print('No, it is a little lower than that') # Another block ## # You can do whatever you want in a block ... ## else: ## print('No, it is a little higher than that') ## # you must have guess > number to reach here ## else: ## print('The while loop is over.') ## # Do anything else you want to do here ## print('Done') ## ############### Testing the method of application of break-clause ## while True: ## s = input('Enter something until with quit: ') ## if s == 'quit': ## break ## elif len(s) < 3: ## print('input string is too short to quit') ## continue ## print('Length of the string is', len(s)) ## print('Done') ############### Testing the method of application of call-funtion sayHello() printMax(100, 321) print('maximum(123,142) is', maximum(123, 142)) printMaxDoc(123, 142) print(printMaxDoc.__doc__) help(printMaxDoc) help(printMax) ############### Testing the method of application of modules print('The command line arguments are:') for i in sys.argv: print(i) print('\n\nThe PYTHONPATH is', sys.path, '\n') mymodule.sayhi() print('mymodule.version is', mymodule.version) #Fcn001.main() # the same behavior with the time import first time #print('Fcn001.version is',Fcn001.version) print('math.sqrt(10.2) =', math.sqrt(10.2)) print() print('multiply(10,21) is', mymodule.multiply(10, 21)) print('divide(10,21) is', mymodule.divide(10, 21)) print() ############### Testing the method of application of intrinsic constant if __name__ == '__main__': print('This program is being run by itself') else: print('I am being imported from another module') #print(__path__) #print(__line__) print('current file path is', __file__) ############### Testing the method of application of dir() fcn. zzz = 99 newInt = 100 print('Show the attribute-list of current module as following:') print(dir()) yy = 78 newString = 'ABC' print('Show the attribute-list of current module as following:') print(dir()) del yy print('Show the attribute-list of current module as following:') print(dir()) print('Show the attribute-list of sys module as following:') #print(dir(sys)) ############### Testing the method of application of list-data-stucture shoplist = ['apple', 'mango', 'carrot', 'banana'] print('I have', len(shoplist), 'items to purchase.') print('These items are:') # Notice the comma at end of the line print('All the items :') for item in shoplist: print(item, ' ', ' ', sep='->', end='') else: print() shoplist.append('added001') shoplist.append('added002') shoplist.append('added001') shoplist.append(123123) shoplist.append(0.003782) sublist = [12, 32.132, 'ABC', "zyx", 31, 1323.1231] shoplist.append(sublist) print('All the items :') for item in shoplist: print(item, ' ', ' ', sep='->', end='') else: print() print('Output the shoplist : ', shoplist) ############### Testing the method of application of tuple (diffrent from list) zoo = ('wolf', 'elephant', 'penguin') print('Number of animals in the zoo is', len(zoo)) new_zoo = ('monkey', 'dolphin', zoo) print('Number of animals in the new zoo is', len(new_zoo)) print('All animals in new zoo are', new_zoo) print('Animals brought from old zoo are', new_zoo[2]) print('Last animal brought from old zoo is', new_zoo[2][2]) age = 22 name = 'Swaroop' print('%s is %d years old' % (name, age)) # tuple mostly are used in print-clause print('Why is %s playing with that python?' % name) ############### Testing the method of application of key-value pair i.e. dictionary data structure ab = { 'Swaroop': '*****@*****.**', 'Larry': '*****@*****.**', 'Matsumoto': '*****@*****.**', 'Spammer': '*****@*****.**' } print() print("Swaroop's address is %s" % ab['Swaroop']) # Adding a key/value pair ab['Guido'] = '*****@*****.**' # Deleting a key/value pair del ab['Spammer'] print('\nThere are %d contacts in the address-book : \n' % len(ab)) for name, address in ab.items(): print('Contact %s at %s' % (name, address)) if 'Guido' in ab: # OR ab.has_key('Guido') print("\nGuido's address is %s" % ab['Guido']) ############### Testing the method of application of sequence shoplist = ['apple', 'mango', 'carrot', 'banana'] # Indexing or 'Subscription' operation print('Item 0 is', shoplist[0]) print('Item 1 is', shoplist[1]) print('Item 2 is', shoplist[2]) print('Item 3 is', shoplist[3]) print('Item -1 is', shoplist[-1]) print('Item -2 is', shoplist[-2]) print('Item -3 is', shoplist[-3]) print('Item -4 is', shoplist[-4]) # Slicing on a list print('Item 1 to 3 is', shoplist[1:3]) print('Item 2 to end is', shoplist[2:]) print('Item 1 to -1 is', shoplist[1:-1]) print('Item start to end is', shoplist[:]) # Slicing on a string name = 'ABCDefghijk' print('characters 1 to 3 in string \'swaroop\' is', name[1:3]) print('characters 2 to end in string \'swaroop\' is', name[2:]) print('characters 1 to -1 in string \'swaroop\' is', name[1:-1]) print('characters start to end in string \'swaroop\' is', name[:]) ############### Testing the method of application of reference and copy(i.e. ref and copy) print('Simple Assignment') shoplist = ['apple', 'mango', 'carrot', 'banana'] mylist = shoplist # mylist is just another name pointing to the same object! del shoplist[0] print('shoplist is', shoplist) print('mylist is', mylist) # notice that both shoplist and mylist both print(the same list without # the 'apple' confirming that they point to the same object print('Copy by making a full slice') mylist = shoplist[:] # make a copy by doing a full slice del mylist[0] # remove first item print('shoplist is', shoplist) print('mylist is', mylist) ############### Testing the method of application of string (deeper study especially the fucntions) name = 'Swaroop' # This is a string object if name.startswith('Swa'): print('Yes, the string starts with "Swa"') if 'a' in name: print('Yes, it contains the string "a"') if name.find('war') != -1: print('Yes, it contains the string "war"') delimiter = '_*_' mylist = ['Brazil', 'Russia', 'India', 'China'] print(delimiter.join(mylist)) delimiter = ' ' mylistStr = delimiter.join(mylist) mylist2 = mylistStr.split(' ') print(mylist2) str = ('www...google.com') print(str) str_split = str.split( '.', 500) # To split the primt stirng 2 times, i.e. create two sub-segment print(str_split) print(' -- A B C-de F -- '.strip(), 'End')
import mymodule print(mymodule.divide(100, 50)) import sys ### lists the paths where python would look for imports ##in the shell you could add paths with "export PYTHONPATH = /Users" print(sys.path) print(sys.modules)
import mymodule print(mymodule.divide(7, 2)) print("code.py", __name__)
def test_divide3(): with pytest.raises(ZeroDivisionError): mymodule.divide(1, 0)
from mymodule import divide print(divide(10, 2)) # -- __name__ -- print(__name__) # -- importing with names -- import mymodule print("code.py: ", __name__) # How does Python know where `mymodule` is? # Answer, it looks at the paths in sys.path in order: import sys print(sys.path) # The first path is the folder containing the file that you ran. # The second path is the environment variable PYTHONPATH, if it is set. # We won't cover environment variables in depth here, but they are variables you can set in your operating system. It can help Python find things to import when the folder structure is ambiguous. # -- circular imports -- # Make mymodule.py import code.py as well. # -- importing from a folder -- import mymodule
import mymodule2 connection = urllib.urlopen( "http://www.learnpython.org/en/Modules_and_Packages") #print "result = " + str(connection.info()) print "result code = " + str(connection.geturl()) # To make your own module, you just need to create a file with the module name # To import the module, just use import command and filename without the extension # To use the functions in the module, use <modulename>.<functionname> print "Magic number in the module: %d" % mymodule.magic_number print mymodule.add(3, 4) print mymodule.subtract(3, 4) print mymodule.divide(3, 4) print mymodule.multiply(3, 4) # You can import one module inside the other from mymodule2 import average # mymodule2 loads mymodule. But we'd expect that mymodule is loaded only once. # this should NOT print 2 print "Magic number in the module: %d" % mymodule.magic_number list = [1, 2, 5, 7, 8, 10, 15, -3] x = mymodule2.average(list) print x # Exercise
from mymodule import divide print(divide(15, 5)) print("code.py: ", __name__) # ======================================= import sys print(sys.path)
def test_divide1(): assert abs(mymodule.divide(2, 4) - 0.5) < TOL