def my_function():
value = 100
print(f"My value is: {value}")
my_function()
def my_function(my_argument):
print(f"The text is: {my_argument}")
my_function("my_ text")
def my_function(my_argument):
my_argument += 1
return my_argument
a docstring describes a function viz. they are the function's documentation
docstrings are displayed with calling help()
function.__doc__ #gives the docstring directly
def clean_string(text):
"""This functions cleans text inputs."""
no_spaces = text.replace(" ", "_")
clean_text = no_spaces.lower()
return clean_text
the data structure viz. value that is passed inside a function
separated by a comma
* #creates an arbitrary positional argument i.e. unlimited input quantity of arguments
def my_function(*args): #*args is the typical variable name for arbitrary positional argument
keyword = value
** #creates an arbitrary keyword argument i.e. unlimited input quantity of arguments
def my_function(**kwargs): #*kwargs is the typical variable name for arbitrary keyword argument
help(function) #gives the arguments of a function etc.
lambda #creates an anonymos function
use lambda only for a simple task that happens only once
lambda argument: expression #x is often use for a single argument
(lambda x: sum(x) / len(x))[3, 4, 5] #calculates the average of 3, 4, 5
(lambda x, y: x ** y)(3, 2) #caclulates 3²
average = lambda x: sum(x) / len(x) #stores the lambda funtions in a variable that can be called
upper_case = list(map(lambda x: x.upper(), name_list)) #turns name_list into upper cases
def clean_string(text):
no_spaces = text.replace(" ", "_")
clean_text = no_spaces.lower()
return clean_text
converted_text = clean_string("WronG CAsE iNpUt!")
print(converted_text)
def convert_data_structure(data, data_type="list"): #preset an argument
if data_type == "tuple":
data = tuple(data)
elif data_type == "set":
data = set(data)
else:
data = list(data)
return data
convert_data_structure({"a", 1, "b", 2, "c", 3}, data_type="set") #if no data type were give, it would ouput a list
def concat(*args):
result = ""
for arg in args:
result += " " + arg
return result
print(concat("My", "concatenated", "output!"))
def concat(**kwargs):
result = ""
for kwarg in kwargs.values():
result += " " + kwarg
return result
print(concat(start="Python", middle="is", end="great!"))