A function is a named block of code. You define it once and run it as many times as you want.
def greet():
print("Hello")
print("Welcome aboard")
def starts the definition. greet is the function's name. The parentheses and colon are required. Every indented line below the def line belongs to the function — this indented block is the function's body.
Defining a function does not run it. To run it, call it by writing its name followed by parentheses:
def greet():
print("Hello")
print("Welcome aboard")
greet()
greet()
Output:
Hello
Welcome aboard
Hello
Welcome aboard
The body ran twice — once per call. A function must be defined before the line that calls it.
say_hello that prints exactly one line:Hello!
Run your code to see the output, then press Submit.
import io
import unittest
from contextlib import redirect_stdout
class TestShowWelcome(unittest.TestCase):
def test_say_hello_prints_hello(self):
captured = io.StringIO()
with redirect_stdout(captured):
say_hello()
self.assertEqual(captured.getvalue(), "Hello!\n")
def say_hello():
print("Hello!")
say_hello()
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.