Writing code in Python is quite simple, but we need to make it re-useable if we apply the same code over and over again during our project. We do so by wrapping our code into functions.
This about this transformation that you want to apply to a string:
start_string = "12-12-XXBC"
You want to extract the first two letters of this code, here “XX”, and put them in lowercase.
start_string = start_string[6:8] start_string = start_string.lower()
Now, you need to repeat that 5 times. Writing this code 5 times for 5 different variable names would be cumbersome. You can wrap it in a function using the keyword
def extract_code(x): return x[6:8].lower()
This function has a name:
extract_code that I chose arbitrarly. It takes one input, here
x. This input name does not point to any variable, it’s simply here to say that we’ll later apply this function on some input. And for this given
x, it extracts the right part, puts it into lowercase and returns this value.
You can then call this function and specifiy the input we want:
string_1 = extract_code("12-12-XXBC") string_1
You can apply whatever transformation you want with a function, on whatever input data type. You can also sum two integers easily:
def add_integers(a, b): return a + b
The inputs can take a default value, and if its value is not specified by the user when we calls the function, it will use this default value in the function:
def add_integers(a, b=1): return a + b
“a” takes the value 2, which is specified by the user, while “b” is not specified and therefore takes the value 1 by default.
If you found the article useful or see ways in which it could be improved, please leave a comment :)
Like it? Buy me a coffee