Split a program
greetings.py defines greet. main.py imports it and calls it. The check runs greetings.py. main.py stays as the lesson wrote it, so you can read the import while you write the function.
A file name here is one segment, such as greetings.py. Do not write a slash or .. in the name.
Two jobs, two files
A program grows clearer when each file has one job.
greetings.pydefines the function. It does not need to print.main.pyuses the function. It imports the name and prints the result.
The second file does not copy the function. It loads the name with from greetings import greet. The word before import is the module: the file name without .py. The word after import is the name defined in that file. The modules tutorial describes this form.
If greet returns "Hello, " + name, that call prints Hello, Ada.
A worked example
Suppose the greeting should be the word Hello, a comma, a space, and the name. Build that string with +.
- Open
greetings.py. - Define
greetwith one parameter,name. - Return
"Hello, " + name. The space after the comma is part of the string. - Leave
main.pyas it is. It already importsgreetand callsgreet("Ada").
Trace that definition with the call from main.py. The parameter name is "Ada". The return value is "Hello, Ada". print shows that string. Nothing in the function deletes a file. An import reads a module.
This program cannot be stepped through.
The comma and the space both belong inside the string, before the +.
What does from greetings import greet do?
Click the import line.
Put the lines in an order that defines greet and then prints Hello, Ada.
return "Hello, " + name
return name
print(greet("Ada"))def greet(name):
Exercise
Write greet in greetings.py. It takes a name and returns Hello, a space, and that name. Do not change main.py.
Write greet in greetings.py. It takes a name and returns Hello, a space, and that name.