Building on the last lecture when we talked about the options for importing libraries, today we give a little more detail on how to make your own multi-file programs. You can think of these as your own libraries! As your programs get bigger, you will write more functions, and at some point you will realize that your functions are useful for other programs too. Instead of keeping those functions in your programs, you can pull them out into their own files which can then be reused seamlessly across all your programs.
If after class you need more, read this for a walk-through of the __main__ variable.
This gets two positive integers from the user, and keeps asking if they are negative inputs. It then outputs the remainder of dividing the bigger integer by the smaller.
# Saved in file 'posnum.py'
def getposnum():
num = int(input("Please enter a positive integer: "))
while num < 0:
num = int(input("Please try again: "))
return num
if __name__ == '__main__':
num1 = getposnum()
num2 = getposnum()
if num1 > num2:
print('Remainder of', num1, '/', num2, 'is', str(num1%num2))
else:
print('Remainder of', num2, '/', num1, 'is', str(num2%num1))
Note that the above example is in a file posnum.py. The following should make sense to you now!
from posnum import getposnum
def gcd(a,b):
""" Returns the greatest common divisor between two ints """
r = a
while b != 0:
r = a % b
a = b
b = r
return a
if __name__ == '__main__':
num1 = getposnum()
num2 = getposnum()
div = gcd(num1, num2)
print("The greatest common divisor is", div)