일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- Github
- AS
- Else
- polynomial regression
- Text Analytics
- For loops
- MySQL
- data distribution
- pie charts
- self parameter
- matplotlib
- Default X points
- PROJECT
- variables
- line color
- iterates
- multiple lines
- error
- train/test
- break
- machine learning
- Text mining
- __init__
- line width
- Python
- SQL
- PANDAS
- matplotlib.pyplot
- continue
- start exercise
- Today
- Total
Data Science Explorer
[Basic Grammar] Python Functions 본문
- Creating a Function
We can use def keyword to define a function.
Example
def my_function():
print("Hello World")
** Do not forget ":" when you define a function! **
- Calling a Function
Example
def my_function():
print ("Hello World")
my_function()
- Parameters vs Arguments
Let's differentiate parameters and agruments with the following code.
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
In this case, the arguments are the values you pass to the 'my_function'. The arguments are the names "Emil," "Tobias," and "Linus.". These names are passed to the 'fname' which is the parameter defined in the 'my_function' function.
- Number of Arguments
By default, a function must be called with the correct number of arguments. In other words, if your function expects 2 arguments, you have to call the function with 2 arguments not more and not less.
Example
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Grace", "Kim")
In this case, you can see that 2 arguments are expected.
Let's see the code that gives you an error.
def my_function(fname, lname):
print(fname + " " + lname)
my_function("David")
In this case, the error occurred because 2 arguments were expected but in fact, only 1 result was given.
- Arbitary Arguments, *args
If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.
Example
def my_function(*names):
print("The smartest girl is " + kids[2])
my_function("Pearl", "Tom", "Sara")
In this case, kids[2] can be confusing. It shows the index number.
- Keyword Arguments
You can also send arguments with the key = value.
Example
def my_function(brand1, brand2, brand3):
print("The most popular brand in Europe is " + brand3)
my_function(brand1 = "Zara", brand2 = "H&M", brand3 = "Gucci")
Check out the argument part, you will see key = value format which leads to key arguments.
- Arbitrary Keyword Arguments, **kwargs
If you do not know how many keyword arguments that will be passsed into your function, use two asterisk: **, right in front of the parameter.
Example
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "John", lname = "Cherif")
Default Parameter Value
Let's check out the following example to see the default parameter value.
def my_function(food = "pasta"):
print("My favorite food is " + food)
my_function("sushi")
my_function(curry")
my_function()
Answer
My favorite food is sushi
My favorite food is curry
My favorite food is pasta
Let's check out the last line of the answer. You will see pasta is added for the answer. This is because "pasta" is a default value.
- Passing a List as an Argument
You can send any data types of arguments to a function and it will be treated as the same data type inside the function.
For instance, if you send a list as an arugment, it will still be a list.
Example
def my_function(fruits):
for x in fruits:
print(x)
food = ["pizza", "udon", "ramen"]
my_function(food)
** At first, I got confused, but print(x) is all you have to focus, the code below are just conditions that are given. **
- Return Values
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Exercises
1. Write a Python function find_oldest that accepts a variable number of arguments (the names of children) and prints "The oldest child is " followed by the name of the oldest child. Use the function to find and print the name of the oldest child among "Alice," "Bob," "Charlie," and "David."
def find_oldest (*kids):
oldest = max(kids, key = len)
print ("The oldest child is " + oldest)
find_oldest("Alice", "Bob", "Charlie", "David")
2. Write a Python function display_info that accepts keyword arguments for "first_name" and "last_name" and prints "His first name is " followed by the first name and "His last name is " followed by the last name. Use the function to display the first name "John" and last name "Smith."
def display_info(**info):
print("His first name is " + info["first_name"])
print("His last name is " + info["last_name"])
display_info(first_name="John", last_name="Smith")
3. Define a Python function calculate_area that takes one argument, side_length, and returns the area of a square with that side length. Then, call the function with different side lengths (e.g., 4, 6, and 8) to calculate and print their respective areas.
def calculate_area(side_length):
return side_length * side_length
print(calculate_area(4))
print(calculate_area(6))
print(calculate_area(8))
'Python' 카테고리의 다른 글
[Basic Grammar] Python Arrays (0) | 2023.10.21 |
---|---|
[Basic Grammar] Python Lambda (1) | 2023.10.21 |
[Basic Grammar] Python For Loops (1) | 2023.10.21 |
[Basic Grammar] Python While Loops (0) | 2023.10.20 |
[Basic Grammar] Python If ... Else (0) | 2023.10.20 |