Sharing notes from my ongoing learning journey — what I build, break and understand along the way.
Python Basics – Part 8: Functions, Parameters, Floating-Point Math, and Built-in Keywords
Python Basics – Part 8: Functions, Parameters, Floating-Point Math, and Built-in Keywords
This week, we’re continuing our Python fundamentals series with a deep dive into one of the most important topics in programming — functions.
We’ll explore how functions work, how to use parameters, default arguments, and return values, as well as how to deal with floating-point numbers, rounding, and Python’s built-in functions and keywords.
Functions in Python
Functions allow us to group related instructions and reuse code efficiently.
def my_first_function():
print("Hello, World!")
Call the function as many times as you need:
my_first_function()
my_first_function()
A function definition always starts with the keyword def, followed by the function name and parentheses ().
Inside the parentheses, you can define parameters, which act like local variables.
Parameters and Arguments
Parameters are placeholders defined in the function.
Arguments are the actual values passed when calling it.
def show_text(text):
print(text)
show_text("Hello World")
show_text("Hallo Welt")
You can define functions with multiple parameters:
def add(a, b):
result = a + b
print(result)
add(3, 4) # 7
add(5000, 1) # 5001
The number of arguments and parameters must match.
Returning Values
Use the return keyword to send a result back to the caller:
def add(a, b):
return a + b
sum_result = add(3, 4)
print(sum_result) # 7
Now you can reuse that result elsewhere.
Another example:
def full_name(first_name, last_name):
return first_name + " " + last_name
name = full_name("Peter", "Wellert")
print(name)
Docstrings and Type Hints
Modern Python code uses docstrings (for documentation) and type hints (for clarity):
def add(a: int, b: int) -> int:
"""Return the sum of two integers."""
return a + b
Default Parameters
A parameter can have a default value, which is used if no argument is given.
def add(a, b=1):
return a + b
print(add(3, 4)) # 7
print(add(8)) # 9
You can define multiple default parameters:
def multiply(a, b=1, c=1):
return a * b * c
print(multiply(2, 3, 4)) # 24
print(multiply(2, 3)) # 6
print(multiply(2)) # 2
Default parameters must always come after non-default parameters.
Avoid Mutable Defaults
Never use a mutable object (like a list or dict) as a default value — it can cause unexpected behavior.
Wrong:
def add_item(item, items=[]):
items.append(item)
return items
Correct:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
Keyword Arguments
You can specify arguments by name:
def multiply(a, b=1, c=1):
return a * b * c
print(multiply(3, c=7)) # 21
Example with default text:
def greet(first_name, last_name="Müller", text="Hello"):
return f"{text} {first_name} {last_name}!"
print(greet("Peter", "Wellert", "Hey")) # Hey Peter Wellert!
print(greet("Peter")) # Hello Peter Müller!
print(greet("Peter", text="Hi")) # Hi Peter Müller!
Exponential Notation and Floating-Point Errors
In Python, very large or small numbers can be written in exponential notation:
print(2e6) # 2000000.0
print(321e-6) # 0.000321
But beware of rounding issues due to binary representation:
print(1.1 + 2.2) # 3.3000000000000003
print(round(1.1 + 2.2, 1)) # 3.3
print(f"{0.1 * 3 - 0.3:.6f}") # 0.000000
For financial or precise decimal calculations, use the decimal module:
from decimal import Decimal
print(Decimal("0.1") * 3 - Decimal("0.3")) # 0.0
Rounding Numbers
Python provides multiple rounding functions:
print(round(4.49)) # 4
print(round(4.49, 0)) # 4.0
print(round(4.2349, 2)) # 4.23
Old-school rounding:
print(round(4.2349 * 100) / 100) # 4.23
Python uses banker’s rounding:
print(round(1.5)) # 2
print(round(2.5)) # 2
Using math.ceil() and math.floor()
import math
print(math.ceil(9.1)) # 10 (always rounds up)
print(math.floor(9.9)) # 9 (always rounds down)
Python Built-in Functions
Python includes many built-in functions that are available without imports.
print(len([1, 2, 3])) # 3
print(sum([1, 2, 3])) # 6
print(min([4, 2, 1, 7])) # 1
print(max([4, 2, 1, 7])) # 7
sorted()
Unlike the list method .sort(), the built-in sorted() returns a new list.
nums = [7, 2, 9, 4, 3]
print(sorted(nums)) # [2, 3, 4, 7, 9]
print(sorted(nums, reverse=True)) # [9, 7, 4, 3, 2]
Using a key function:
names = ["anna", "Bob", "christian"]
print(sorted(names, key=str.lower)) # ['anna', 'Bob', 'christian']
Python Keywords and Special Values
del
Deletes a variable or element from a list:
nums = [7, 2, 9, 4, 3]
del nums[2]
print(nums) # [7, 2, 4, 3]
pass
Used as a placeholder when a statement is syntactically required but no action is needed:
def todo():
pass
None
Represents the absence of a value.
def say_hello():
print("Hello")
result = say_hello() # prints Hello
print(result) # None
Compare with is, not ==:
x = None
if x is None:
print("x has no value")
Exploring Built-ins
You can see all built-in functions using:
print(dir(__builtins__))
Count them:
c = sum(1 for i in dir(__builtins__) if i[0].islower())
print("Count:", c) # may vary by Python version
And get documentation with:
help(len)
Summary
In this part, we covered:
- Writing and calling functions
- Using parameters, default values, and keyword arguments
- Understanding floating-point math and rounding
- Exploring Python’s built-in functions and keywords
