COMP1531

2.4 - Python - Importing & Paths

 

importing and modules

  • In python you're able to write code in one file, and import it into another file (just like C).

importing and modules

calmath.py

def daysIntoYear(month, day):
    total = day
    if month > 0:
        total += 31
    if month > 1:
        total += 28
    if month > 2:
        total += 31
    if month > 3:
        total += 30
    if month > 4:
        total += 31
    if month > 5:
        total += 30
    if month > 6:
        total += 31
    if month > 7:
        total += 30
    if month > 8:
        total += 31
    if month > 9:
        total += 30
    if month > 10:
        total += 31
    return total

def quickTest():
    print(f"month 0, day 0 = {daysIntoYear(0,0)}")
    print(f"month 11, day 31 = {daysIntoYear(11,31)}")

#if __name__ == '__main__':
#    quickTest()

quickTest()
import sys

import calmath

if len(sys.argv) != 3:
    print("Usage: importto.py month dayofmonth")
else:
    print(calmath.daysIntoYear(int(sys.argv[1]), \ 
                               int(sys.argv[2])))

importto.py

What is this for?? (Live Demo)

Ways to import

use.py

import * from lib

# To do

from lib import one, two, three

# To do
 
import lib

# To do
def one():
    return 1

def two():
    return 2

def three():
    return 3

lib.py

Which ways do we prefer and why?

COMP1531 21T1 - 2.4 - Python - Importing & Paths

By haydensmith

COMP1531 21T1 - 2.4 - Python - Importing & Paths

  • 422