Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
Web Security TippsNew manual calculation setting in Google Sheets(21.09.2026 um 20:54 Uhr)
Videos & KonferenzenTechquickie: The Steam Frame Shouldn't Work - Here's Why It Does(21.09.2026 um 21:17 Uhr)
Sichere ProgrammierungHow to Build a Production-Ready iOS App With AI-Generated Code(21.09.2026 um 21:00 Uhr)
Sichere ProgrammierungAfriex Integrations: Sandbox, Idempotency, and Webhook Simulation(21.09.2026 um 21:50 Uhr)
Sichere ProgrammierungBridging Local and Cloud Databases for Centralized Data Management(21.09.2026 um 21:51 Uhr)
Web Security TippsNew manual calculation setting in Google Sheets(21.09.2026 um 20:54 Uhr)
Videos & KonferenzenTechquickie: The Steam Frame Shouldn't Work - Here's Why It Does(21.09.2026 um 21:17 Uhr)
Sichere ProgrammierungHow to Build a Production-Ready iOS App With AI-Generated Code(21.09.2026 um 21:00 Uhr)
Sichere ProgrammierungAfriex Integrations: Sandbox, Idempotency, and Webhook Simulation(21.09.2026 um 21:50 Uhr)
Sichere ProgrammierungBridging Local and Cloud Databases for Centralized Data Management(21.09.2026 um 21:51 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

Functions: Stop Writing the Same Code Twice

You have written the same print(f"Hello, {name}!") line three times in your code already. Not a big deal with one line. But what happens when the thing you keep repeating is 15 lines long? What happens when you find a bug in it and have…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

You have written the same print(f"Hello, {name}!") line three times in your code already.



Not a big deal with one line. But what happens when the thing you keep repeating is 15 lines long? What happens when you find a bug in it and have to fix it in six different places? What happens when you forget to fix one of them?



This is not a hypothetical. This is what happens in real codebases when people don't use functions. Code gets copied, pasted, modified slightly, and then something breaks and nobody knows which copy is the right one.



Functions solve this. Write the code once, use it anywhere.









The Simplest Function Possible






def greet():
print("Hello, welcome!")






def tells Python you're defining a function.



greet is the name you're giving it. You choose the name, same rules as variable names.



() is where parameters go. Empty for now.



: ends the line, same as if and for.



The indented block is the function body. The code that runs when you call the function.



But here's the thing. Running that code does nothing visible. You defined the function. You haven't used it yet.



To actually run the code inside, you call the function.




def greet():
print("Hello, welcome!")

greet()
greet()
greet()






Output:




Hello, welcome!
Hello, welcome!
Hello, welcome!






Three calls, three outputs. The function ran three times. You wrote the print statement once.









Parameters: Giving the Function Information



A function that always does the exact same thing is useful but limited. Parameters let you pass different information to the function each time you call it.




def greet(name):
print(f"Hello, {name}! Welcome.")






name inside the parentheses is a parameter. It's a variable that exists only inside the function and gets its value when you call the function.




greet("Alan")
greet("Priya")
greet("Sam")






Output:




Hello, Alan! Welcome.
Hello, Priya! Welcome.
Hello, Sam! Welcome.






Same function. Three different results. The parameter is what makes it flexible.



You can have multiple parameters. Separate them with commas.




def introduce(name, age, city):
print(f"My name is {name}. I am {age} years old and I live in {city}.")

introduce("Alan", 25, "Mumbai")
introduce("Priya", 30, "Delhi")






Output:




My name is Alan. I am 25 years old and I live in Mumbai.
My name is Priya. I am 30 years old and I live in Delhi.






Order matters here. When you call the function, Python matches your arguments to the parameters left to right. First argument goes to first parameter, second to second, and so on.









Return: Getting Something Back



So far every function just prints something. But often you want a function to calculate something and give you the result back, not just display it.



That's what return does.




def add(a, b):
result = a + b
return result









total = add(10, 5)
print(total)






Output:




15






The function takes two numbers, adds them, and returns the answer. You can store that answer in a variable, use it in another calculation, pass it to another function, anything.



Here's the key difference. print() inside a function just displays text. The value disappears after that. return sends the value back to whoever called the function so they can do something with it.




def add(a, b):
return a + b

def multiply(a, b):
return a * b

x = add(3, 4) # x is now 7
y = multiply(x, 2) # y is now 14

print(y)






Output:




14






The output of one function fed straight into another. This is how real programs are built. Small functions, chained together.









Default Parameters



Sometimes you want a parameter to have a default value if the caller doesn't provide one.




def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")

greet("Alan")
greet("Priya", "Good morning")
greet("Sam", "Hey")






Output:




Hello, Alan!
Good morning, Priya!
Hey, Sam!






When you call greet("Alan") without a second argument, greeting falls back to "Hello". When you provide one, that value is used instead.



Default parameters must always come after non-default ones. This doesn't work:




def greet(greeting="Hello", name):   # wrong






Python needs to know which argument is which. Put defaults last.









Variables Inside Functions Stay Inside



This one surprises people.




def calculate():
result = 100
print(f"Inside function: {result}")

calculate()
print(result) # this breaks






Output:




Inside function: 100
NameError: name 'result' is not defined






The variable result was created inside the function. It only exists while the function is running. Once the function finishes, result is gone. Code outside the function cannot see it.



This is called scope. Variables have a scope, which is the region of code where they exist.



The fix is to return the value.




def calculate():
result = 100
return result

answer = calculate()
print(answer)






Output:




100






Now result is returned and stored in answer. answer lives outside the function, so the outside code can use it.









A Function That Does Something Real



Let's write a function that calculates a grade based on a score. You built something similar with if/else in post 3. Now let's make it reusable.




def get_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"

scores = [95, 82, 67, 54, 71]

for score in scores:
grade = get_grade(score)
print(f"Score {score}: Grade {grade}")






Output:




Score 95: Grade A
Score 82: Grade B
Score 67: Grade D
Score 54: Grade F
Score 71: Grade C






Look at how clean this is. The grading logic lives in one place. The loop just calls the function for each score. If you ever need to change how grades are calculated, you change it in one function and it updates everywhere.



That's the real reason functions exist. Not just to avoid repetition. To keep related logic together so your code is easier to read, fix, and change.









Two Mistakes Everyone Makes



Mistake 1: Forgetting to return and wondering why you get None




def add(a, b):
result = a + b # calculated but never returned

total = add(5, 3)
print(total)






Output:




None






The function calculated 8. But it never sent that value back. Python functions that don't explicitly return something return None automatically. None means nothing. Not zero. Literally nothing.



Fix: add return result at the end.



Mistake 2: Calling before defining




greet("Alan")       # call happens first

def greet(name): # definition comes after
print(f"Hello, {name}")






Error:




NameError: name 'greet' is not defined






Python reads top to bottom. When it hits greet("Alan"), it hasn't seen the definition yet. Define functions before you call them.









Try This



Create a file called functions_practice.py.



Write three separate functions.



First one: takes a temperature in Celsius and returns it converted to Fahrenheit. The formula is (celsius * 9/5) + 32.



Second one: takes a person's name and birth year and prints a message like "Alan was born in 1999 and is 25 years old." Calculate the age inside the function. You'll need to hardcode the current year or store it in a variable.



Third one: takes a list of numbers and returns the largest one without using Python's built-in max() function. Think through how you'd find the largest number by going through the list one item at a time.



Then call each function at least twice with different inputs to make sure they work correctly.









What's Next



You now know how to organize code into reusable blocks. The next post is about lists, which are the most important data structure you'll use in Python. You've seen them briefly but now you'll learn everything: how to add to them, remove from them, search them, sort them, and loop through them in useful ways.

Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Functions: Stop Writing the Same Code Twice

Thematisch verwandte Begriffe: Functions, Stop, Writing, Same · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-94497 | jshERP through 3.6 fails to validate object ownership in by-id info, upd…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick