Introduction to Python

davidbpython.com




Project Warmup Exercises, Session 9



Ex. 9.1 Write a function addme() that takes two arguments, adds them together and returns the two arguments added / concatenated. Call it thusly:
# your code here

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

y = addme('hey', 'you')
print(y)
Expected Output:
9
heyyou
 
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. Now in the same directory where you saved the module, create a python script. In the script have an import greet statement, and then call the function through the module: greet.hello() Save the file and then run it.

import yourname

yourname.hello()           # 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!

So your def hello function code will be modified to accept the name=text argument (i.e., def hello(name=False)), and then test to see if text has a value -- if it is True (i.e., if name: is True). If it is True, print it after 'hello, '. If it doesn't, print 'hello, world!'

import yourname

yourname.hello()                # hello, world!
yourname.hello(name='Python')   # hello, Python!
 
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.
# your code here

lines = getlines('student_db.txt')

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