Introduction to Python

davidbpython.com




Project Warmup Exercise Solutions, Session 9



Ex. 9.1 Write a function addme() that takes two arguments, adds them together and returns the two arguments added / concatenated.
def addme(arg1, arg2):
    adx = arg1 + arg2
    return adx

x = addme(4, 5)
print(x)

y = addme('hey', 'you')
print(y)
 
Ex. 9.2 Create a module file named yourname.py where yourname is your first name.

Create a def hello: function (that prints hello, world!) inside the yourname.py module.

In a file called yourname.py
def hello():
    print('hello, world!')
 
Ex. 9.3 Modify the above function to include an optional argument. If name=[something], print hello, [something]! instead of hello, world! But if the name= parameter is not passed, revert to saying hello, world!
def hello(name=None):
    if not name:
        name = 'world'

    print(f'hello, {name}!')

## even more succinct -- put the default value in the arg list:

def hello(name='world'):

    print(f'hello, {name}!')

hello(name='Joe')       # hello, Joe!
hello()                 # hello, world!
 
Ex. 9.4 Create a function getlines(filename) that takes a filename, opens the file for that filename, copies the lines of the file (i.e., from the file method .readlines()) to a list variable, and then returns the list. In the calling code, call the function with a known filename, and assign the return value of the call to a variable. Loop through the variable (of course it is a list) and print out each line in the file.
def getlines(filename):
    fh = open(filename)
    lines = fh.readlines()
    return lines

lines = getlines('../student_db.txt')

for line in lines:
  print(line)             # prints each line in file

fh.close()
 
[pr]