Friday, 1 September 2017

Python programs


1) Function Arguments:
def wrapper(func, *args):
    func(*args)

def func1(x):
    print(x)

def func2(x, y, z):
    print x+y+z

wrapper(func1, 1)
wrapper(func2, 1, 2, 3)

2) OS library import

import os

# prints out the paths files within that  directory
def print_directory_contents(sPath):
      for sChild in os.listdir(sPath):
        sChildPath = os.path.join(sPath, sChild)
        if os.path.isdir(sChildPath):
            print_directory_contents(sChildPath)
        else:
            print(sChildPath)

print_directory_contents("/home/osboxes/python")
3) break and continue
#print only 0,1,2,3,4
count = 0
while True:
    print(count)
    count += 1
    if count >= 5:
        break

# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
    # Check if x is even
    if x % 2 == 0:
        continue
    print(x)

4) functions can return more than one value

def list_benefits():
    return "More organized code", "More readable code", "Easier code reuse",
               "Allowing programmers to share and connect code together"

def build_sentence(benefit):
    return "%s is a benefit of functions!" % benefit


def name_the_benefits_of_functions():
    list_of_benefits = list_benefits()
    for benefit  in  list_of_benefits:
         print(build_sentence(benefit))

name_the_benefits_of_functions()
Output:
More organized code is a benefit of functions!
    More readable code is a benefit of functions!
    Easier code reuse is a benefit of functions!
    Allowing programmers to share and connect code together is a benefit of functions!

5)Accessing Modules from Another Directory
One option is to invoke the path of the module via the programming files that use that module.This should be considered more of a temporary solution.
import sys
sys.path.append('/usr/sammy/')

import hello
A second option that you have is to add the module to the path where Python checks for modules and packages.
python
Next, import the sys module:
  • import sys
Then have Python print out the system path:
  • print(sys.path)
Output
'/usr/sammy/my_env/lib/python3.5/site-packages'
Now you can move your hello.py file into that directory. Once that is complete, you can import the hello module as usual:
 
 

No comments:

Post a Comment