The challenge
Define a method hello
that returns
“Hello, Name!” to a given name
, or says Hello, World! if name is not given (or passed as an empty String).
Assuming that name
is a String
and it checks for user typos to return a name with a first capital letter (Xxxx).
Examples:
hello "john" => "Hello, John!"
hello "aliCE" => "Hello, Alice!"
hello => "Hello, World!" <em># name not given</em>
hello "" => "Hello, World!" <em># name is an empty String</em>
The solution in Python code
Option 1:
def hello(name=''):
return f"Hello, {name.title() or 'World'}!"
Option 2:
def hello(name=''):
return "Hello, {}!".format(name.title() if name else 'World')
Option 3:
def hello(name = ""):
nameNow = ""
if name == "":
return "Hello, World!"
j = 0
for i in name:
if j == 0:
temp1 = i.upper()
nameNow = nameNow + temp1
j += 1
pass
else:
temp1 = i.lower()
nameNow = nameNow + temp1
pass
pass
return "Hello, " + nameNow + "!"
pass
Test cases to validate our solution
import test
from solution import hello
@test.describe("Fixed Tests")
def fixed_tests():
@test.it('Basic Test Cases')
def basic_test_cases():
tests = (
("John", "Hello, John!"),
("aLIce", "Hello, Alice!"),
("", "Hello, World!"),
)
for inp, exp in tests:
test.assert_equals(hello(inp), exp)
test.assert_equals(hello(), "Hello, World!")
@test.describe("Random Tests")
def random_tests():
from random import randint, choice
NAMES = [
"James", "Christopher", "Ronald", "Mary", "Lisa", "Michelle",
"John", "Daniel", "Anthony", "Patricia", "Nancy", "Laura",
"Robert", "Paul", "Kevin", "Linda", "Karen", "Sarah", "Michael",
"Mark", "Jason", "Barbara", "Betty", "Kimberly", "William", "Donald",
"Jeff", "Elizabeth", "Helen", "Deborah", "David", "George", "Jennifer",
"Sandra", "Richard", "Kenneth", "Maria", "Donna", "Charles", "Steven",
"Susan", "Carol", "Joseph", "Edward", "Margaret", "Ruth", "Thomas",
"Brian", "Dorothy", "Sharon", ""
]
def create_test_case():
return "".join(c.lower() if randint(0, 200) % 3 else c.upper() for c in choice(NAMES))
reference = lambda n='', d='World': "Hello, %s!" % (n or d).title()
for _ in range(100):
test_case = create_test_case()
@test.it(f"testing for hello({test_case})")
def test_case():
test.assert_equals(hello(test_case), reference(test_case))