Movatterモバイル変換


[0]ホーム

URL:


Functions

In [1]:
defmy_first_function():print("Hello world!")print(f"type:{type(my_first_function)}")my_first_function()# Calling a function
type: <class 'function'>Hello world!

Arguments

In [2]:
defgreet_us(name1,name2):print(f"Hello{name1} and{name2}!")greet_us("John Doe","Superman")
Hello John Doe and Superman!
In [3]:
# Function with return valuedefstrip_and_lowercase(original):modified=original.strip().lower()returnmodifieduggly_string="  MixED CaSe "pretty=strip_and_lowercase(uggly_string)print(f"pretty:{pretty}")
pretty: mixed case

Keyword arguments

In [4]:
defmy_fancy_calculation(first,second,third):returnfirst+second-thirdprint(my_fancy_calculation(3,2,1))print(my_fancy_calculation(first=3,second=2,third=1))# With keyword arguments you can mix the orderprint(my_fancy_calculation(third=1,first=3,second=2))# You can mix arguments and keyword arguments but you have to start with argumentsprint(my_fancy_calculation(3,third=1,second=2))
4444

Default arguments

In [5]:
defcreate_person_info(name,age,job=None,salary=300):info={"name":name,"age":age,"salary":salary}# Add 'job' key only if it's provided as parameterifjob:info.update(dict(job=job))returninfoperson1=create_person_info("John Doe",82)# use default values for job and salaryperson2=create_person_info("Lisa Doe",22,"hacker",10000)print(person1)print(person2)
{'name': 'John Doe', 'age': 82, 'salary': 300}{'name': 'Lisa Doe', 'age': 22, 'salary': 10000, 'job': 'hacker'}

Don't use mutable objects as default arguments!

In [6]:
defappend_if_multiple_of_five(number,magical_list=[]):ifnumber%5==0:magical_list.append(number)returnmagical_listprint(append_if_multiple_of_five(100))print(append_if_multiple_of_five(105))print(append_if_multiple_of_five(123))print(append_if_multiple_of_five(123,[]))print(append_if_multiple_of_five(123))
[100][100, 105][100, 105][][100, 105]

Here's how you can achieve desired behavior:

In [7]:
defappend_if_multiple_of_five(number,magical_list=None):ifnotmagical_list:magical_list=[]ifnumber%5==0:magical_list.append(number)returnmagical_listprint(append_if_multiple_of_five(100))print(append_if_multiple_of_five(105))print(append_if_multiple_of_five(123))print(append_if_multiple_of_five(123,[]))print(append_if_multiple_of_five(123))
[100][105][][][]

Docstrings

Strings for documenting your functions, methods, modules and variables.

In [8]:
defprint_sum(val1,val2):"""Function which prints the sum of given arguments."""print(f"sum:{val1+val2}")print(help(print_sum))
Help on function print_sum in module __main__:print_sum(val1, val2)    Function which prints the sum of given arguments.None
In [9]:
defcalculate_sum(val1,val2):"""This is a longer docstring defining also the args and the return value.    Args:        val1: The first parameter.        val2: The second parameter.    Returns:        The sum of val1 and val2.    """returnval1+val2print(help(calculate_sum))
Help on function calculate_sum in module __main__:calculate_sum(val1, val2)    This is a longer docstring defining also the args and the return value.        Args:        val1: The first parameter.        val2: The second parameter.        Returns:        The sum of val1 and val2.None

pass statement

pass is a statement which does nothing when it's executed. It can be used e.g. a as placeholder to make the code syntatically correct while sketching the functions and/or classes of your application. For example, the following is valid Python.

In [10]:
defmy_function(some_argument):passdefmy_other_function():pass

[8]ページ先頭

©2009-2025 Movatter.jp