Reputation: 23
I'm sorry if this is a really stupid question; I'm an English major taking a COSC class for an elective (stupid decision, I know) and so none of this comes easily to me.
This is the problem I'm trying to solve:
Write a program that takes in a file that has a message. The message can be any length.
Your program will contain two functions. The first should have a function that processes the contents of the file. The second will take the output from the first function and will print the message in a box of asterisks.
The input file should just be a single-lined message (see attached input example). The output should take that message, split it between two lines, and center it in the box (see attached output example).
This is the code I currently have:
def func1(process_contents):
infile=open("october.txt", "r")
process_contents=print(infile.read())
return process_contents
def func2():
outfile=open("october_output.txt", "w")
print(func1(message), file=outfile)
outfile.close()
(I have not yet attempted to create the box of asterisks...I am simply trying to get the functions to work first). I understand that I cannot assign another variable (i.e. "message") to the formal parameter "process_contents" in func1, that I need to assign a VALUE as the acutal parameters...but as I'm not using numbers in this problem, what is the value I'm using??
Thank you so so much!!
Upvotes: 0
Views: 164
Reputation: 87
You don't necessarily need a formal parameter in func1()
.
def func1():
infile = open("october.txt", "r")
process_contents = infile.read()
return process_contents
def func2():
message = func1()
print("asterisks" + message + "box thingy")
Although, you can use the formal parameter to generalize the function like this:
FILENAME = "october.txt" # or rather something like sys.argv[1]
def func1(FILENAME):
infile = open(FILENAME, "r")
process_contents = infile.read()
return process_contents
def func2():
message = func1(FILENAME)
print("asterisks" + message + "box thingy")
Upvotes: 0
Reputation: 307
The print
function writes by default to stdout
, but does not return a value. Hence, you have to replace process_contents=print(infile.read())
with process_contents=infile.read()
. This will assign the value returned by infile.read()
to the process_contents
variable.
Further, I would recommend to use the with
statement for opening a file, like it is also used by the example given by the python manual.
Upvotes: 1