Koodi kordamise vältimine kasutades funktsioone

Funktsioonid vähendavad koodi hulka. Soovime näiteks tervitada kõiki oma sõpru ühekaupa. Esialgu kirjutame naiivselt sellise koodi:

print("Hello Anni, and welcome to the Python world")
print("Hello Mark, and welcome to the Python world")
print("Hello Bill, and welcome to the Python world")
print("Hello Romeo, and welcome to the Python world")
print("Hello Julia, and welcome to the Python world")

Sellele koodile peale vaadates võib näha, et koodi ülesanne on üks ja sama - tervitada inimest antud nimega. Programmeerimisel tasub jälgida DRY-printsiipi (Don´t Repeat Yourself) ehk sarnase koodi kordamist tuleks vältida. See koodijupp on hea näide sellest, mida tuleks vältida.

Kirjutame nüüd koodi ümber kasutades funktsiooni:

names = ('Anni', 'Mark', 'Bill', 'Romeo', 'Julia')

def greet(name: str) -> str:
    return f"Hello {name}, and welcome to the Python world"

for name in names:
    print(greet(name))

Tulemus:

'Hello Anni, and welcome to the Python world'
'Hello Mark, and welcome to the Python world'
'Hello Bill, and welcome to the Python world'
'Hello Romeo, and welcome to the Python world'
'Hello Julia, and welcome to the Python world'

Lõime funktsiooni, millel on parameeter name ja vastavalt sellele muutub ka prinditava sõne sisu. Paneme kõik nimed ühte ennikusse (Ennik (tuple)) ja loome tsükli (For-tsükkel), mis kutsub välja meie loodud funktsiooni greet iga ennikus oleva nimega. Selle koodi haldamine on juba palju lihtsam.