You will be an engineer in 100 days --Day 32 --Python --Basics of the Python language 7

This time too, it's a continuation of the basics of Python.

Click here for the last time [You will become an engineer in 100 days --Day 31 --Python --Python Exercise 2] (https://qiita.com/otupy/items/8b7436e4df68c6c94fb1)

function

I'm sorry if it doesn't appear

I did about built-in functions a while ago, but this time it's about functions.

The built-in function is a built-in feature of the Python language, You can define the function yourself.

** How to define a function **

def function name(argument):
return Return value

The term is related to functions, but first there is a argument. You can write it inside the () parentheses of the function. Arguments are used when passing data that can be used in the function.

Next is the return value, but the result calculated in the function It is used to return to the outside of the function.

Let's define a function immediately.

#Function definition
def abc(aaa=0):
    print(aaa)
    return 1

#Function execution
print(abc())
print(abc(2))

0 1 2 1

If you assign a value by adding = equal after the variable name of the argument, If the argument is not specified, it will be the value used as the initial value.

Since the return value is the result of executing the function You can also store it in a variable.

#The execution result of the function is stored in a variable
a = abc(3)
print(a)

3 1

Return value and argument can be defined as a function without setting

def defg():
    print('dd')

defg()

dd

Unless you need to return the value It is okay to eliminate the return value without the return.

If you want to use the result of the function for the next processing Add return to return the value.

You can have as many arguments as you like, If it is too much, it will be a problem when using it.

So I think it's better to put it in about 5-6 pieces. If it becomes more than that, it is better to revise the process.

If you define the argument when you define the function, When using it, it is necessary to specify only the argument, Depending on the function, there is also a need to change the processing with the argument.

In such a case, add ** to the argument You can receive arguments as tuple type or dictionary type.

def aaa1(**karg):
    print(karg)

#Pass dictionary type as function argument
aaa1(aws=[1,2])

{'aws': [1, 2]}

You can pass data to multiple arguments at once.

def aaa2(arg1, arg2, arg3):
    print(arg1)
    print(arg2)
    print(arg3)
    
lis = ['one', 'two', 'three']
#Pass the list as a tuple to execute the function.
aaa2(*lis)

one two three

However, in this case it must match the number of arguments. If the numbers do not match, an error will occur.

lis2 = ['one', 'two', 'three','four']
#If the number of arguments and the number passed do not match, an error will occur.
aaa2(*lis2)

TypeError: aaa2() takes 3 positional arguments but 4 were given

As a usage of function, processing that spans multiple lines If it is done more than 2 times, it is better to make it a function The code is neat and easy to see, and maintenance is easy.

If you write the same process twice, review the whole thing With the feeling of rewriting the parts that can be simplified and labor saving I think it is better to create a function.

The specific function is also read as the method by another name. Be sure to keep this in mind as it is an essential concept in programming.

global variables and scope

I'm sorry if it doesn't appear

Whenever you use a function etc., the concept of scope comes with it. This is a concept that indicates the usable range of the declared variable.

There are two types of scope, global and local.

Roughly speaking, the outermost one is global The inside of the function block is local.

Let's see the difference. First, prepare variables that can be used in global.

global_var = 'global'

Next, define a function and prepare variables that can be used in it.

def local_def():
    #Variables for local
    local_var = 'local'
    return local_var

Let's call both variables. Calling a global variable

print(global_var)

global

Calling a local variable

print(local_var)

NameError Traceback (most recent call last) in () ----> 1 print(local_var) NameError: name 'local_var' is not defined

If the variable is not defined, you will get an error.

What is defined in local is This is because it can only be used inside the block of the local.

So this local variable can be used Only in the defined function.

Next, let's play with the function and read the global variable in the function.

def local_def():
    #Global variable reference
    print(global_var)

local_def()

global

The variable declared in global can be used anywhere.

What was declared in local How can I use it in global?

If it is a function, as a return value You can reuse it by returning to the global side.

def local_def():
    local_var = 'local'
    #Returns locally defined variables
    return local_var

g2 = local_def()
print(g2)

local

Let's also look at the for statement.

global_var = 'g'

for i in range(5):
    j = global_var*i
    
#Print local variables as they are
print(i,j)```
4 gggg

 The result will only reflect the final assigned result.

 The `variable` etc. used in the block of the` for` statement
 I think there may be cases where you reuse it without noticing it,
 Depending on the value stored in the `variable`, the result of the program will be greatly affected.

 Finally, what if the variable names are overlaid on `global` and` local`?

```python
sp = 'global'

def local_def():
    sp = 'local'
    print(sp)

local_def()
print(sp)

local global

Once defined in local with the same variable name When you call a function, use the variable name defined in that function. Since it will be overwritten, the value assigned by local will be displayed.

Then when calling the global variable The mechanism is that the original value is displayed.

With the reserved word global, You can manipulate this global variable on the local side.

sp = 'global'

def local_def():
    #Defined locally as a global variable
    global sp 
    sp= 'local'
    print(sp)

local_def()
print(sp)

local local

Declare the variable with global in front of it in local You can then assign it to a variable to manipulate the global variable.

If you use the same variable for global and local, It is easy to cause accidental bugs.

So until you get used to it, you shouldn't cover the variable name as much as possible. It is recommended to use the name.

Anonymous function

I'm sorry if it doesn't appear

So far, I've been teaching about functions, This time we are talking about a anonymous function.

I touched a little on the sort times lambda About lambda. Also called a lambda expression, you can create a unnamed function.

** How to write a lambda expression **

lambda argument: processing

If you write a normal function

def add (a,b):
    return a+b
print(add(2,3))

5

It looks like this If it is a anonymous function using lambda

add = lambda a,b : a+b
print(add(2,3))

5

The variable written after lambda is received and the processing after: is executed.

Assign a function to the variable ʻadd with a lambda expression` It is a mechanism that the function is executed when the variable is used.

There is almost no difference from a normal function, and it is safer to define the function.

The lambda expression is effective at times such as sort.

This lambda expression came out when sorting with a dictionary type value.

dct ={ 3:7 , 5:6 ,1:3 }
#Sort dictionary types by value in ascending order.
print(sorted(dct.items(), key=lambda x:x[1]))

[(1, 3), (5, 6), (3, 7)]

After key = is a lambda expression. The argument key of the sorted function receives the function.

The lambda expression is useful for complex sorting.

lis1 = [2,3,4,5,7]
#When sorting elements by the remainder divided by 3
print(sorted(lis1 , key=lambda x:x%3))

[3, 4, 7, 2, 5]

In the case of dictionary type, key and value are returned as tuple type.

dct ={ 3:7 , 5:6 ,1:3 }
print(sorted(dct.items(), key=lambda x:x[1]))

[(1, 3), (5, 6), (3, 7)]

In the index part of key = lambda x: x [1] [0] is the key and [1] is the value.

If you want to sort by value, In a lambda expression, it is the second index, that is, 1. You would specify key = lambda x: x [1].

This is useful for sorting complex data, etc.

#Define multiple lists
complex_list = [[1,2,3],[3,5,2],[2,6,8]]
print(complex_list)

[[1, 2, 3], [3, 5, 2], [2, 6, 8]]

#Sort by the first value in the list
print(sorted(complex_list,key=lambda x : x[0]))

#Sort by the second value in the list
print(sorted(complex_list,key=lambda x : x[1]))

#Sort by the third value in the list
print(sorted(complex_list,key=lambda x : x[2]))

[[1, 2, 3], [2, 6, 8], [3, 5, 2]] [[1, 2, 3], [3, 5, 2], [2, 6, 8]] [[3, 5, 2], [1, 2, 3], [2, 6, 8]]

The key to sort the list that exists as an element of the large list It can be defined for each item in the list.

By doing this, it will be possible to handle any form of data. The lambda expression is very useful.

It is suitable for small processing that does not require defining a function. Remember how to use it in functions and sorts.

Summary

Functions are a very useful feature for simplifying and organizing your work.

How to define functions and how to handle variables in scope Keep track of how it works and try not to cause bugs.

68 days until you become an engineer

Author information

Otsu py's HP: http://www.otupy.net/

Youtube: https://www.youtube.com/channel/UCaT7xpeq8n1G_HcJKKSOXMw

Twitter: https://twitter.com/otupython

Recommended Posts

You will be an engineer in 100 days --Day 33 --Python --Basics of the Python language 8
You will be an engineer in 100 days --Day 26 --Python --Basics of the Python language 3
You will be an engineer in 100 days --Day 32 --Python --Basics of the Python language 7
You will be an engineer in 100 days --Day 28 --Python --Basics of the Python language 4
You will be an engineer in 100 days ――Day 24 ―― Python ―― Basics of Python language 1
You will be an engineer in 100 days ――Day 30 ―― Python ―― Basics of Python language 6
You will be an engineer in 100 days ――Day 25 ―― Python ―― Basics of Python language 2
You will be an engineer in 100 days --Day 27 --Python --Python Exercise 1
You will be an engineer in 100 days --Day 34 --Python --Python Exercise 3
You will be an engineer in 100 days --Day 31 --Python --Python Exercise 2
You will be an engineer in 100 days --Day 63 --Programming --Probability 1
You will be an engineer in 100 days --Day 65 --Programming --Probability 3
You will be an engineer in 100 days --Day 64 --Programming --Probability 2
You will be an engineer in 100 days --Day 35 --Python --What you can do with Python
You will be an engineer in 100 days --Day 86 --Database --About Hadoop
You will be an engineer in 100 days ――Day 71 ――Programming ――About scraping 2
You will be an engineer in 100 days ――Day 61 ――Programming ――About exploration
You will be an engineer in 100 days ――Day 74 ――Programming ――About scraping 5
You will be an engineer in 100 days ――Day 73 ――Programming ――About scraping 4
You will be an engineer in 100 days ――Day 75 ――Programming ――About scraping 6
You will be an engineer in 100 days --Day 68 --Programming --About TF-IDF
You will be an engineer in 100 days ――Day 70 ――Programming ――About scraping
You will be an engineer in 100 days ――Day 81 ――Programming ――About machine learning 6
You will be an engineer in 100 days ――Day 82 ――Programming ――About machine learning 7
You will be an engineer in 100 days ――Day 79 ――Programming ――About machine learning 4
You will be an engineer in 100 days ――Day 80 ――Programming ――About machine learning 5
You will be an engineer in 100 days ――Day 78 ――Programming ――About machine learning 3
You will be an engineer in 100 days ――Day 84 ――Programming ――About machine learning 9
You will be an engineer in 100 days ――Day 83 ――Programming ――About machine learning 8
You will be an engineer in 100 days ――Day 77 ――Programming ――About machine learning 2
You will be an engineer in 100 days ――Day 85 ――Programming ――About machine learning 10
You will be an engineer in 100 days ――Day 60 ――Programming ――About data structure and sorting algorithm
You become an engineer in 100 days ――Day 66 ――Programming ――About natural language processing
The basics of running NoxPlayer in Python
You become an engineer in 100 days ――Day 67 ――Programming ――About morphological analysis
How much do you know the basics of Python?
What beginners learned from the basics of variables in python
Review of the basics of Python (FizzBuzz)
About the basics list of Python basics
Learn the basics of Python ① Beginners
Will the day come when Python can have an except expression?
For Python beginners. You may be confused if you don't know the general term of the programming language Collection.
[Fundamental Information Technology Engineer Examination] I wrote an algorithm for the maximum value of an array in Python.
If you want a singleton in python, think of the module as a singleton
The story of an error in PyOCR
The story of making Python an exe
Python Note: When you want to know the attributes of an object
Become an AI engineer soon! Comprehensive learning of Python / AI / machine learning / deep learning / statistical analysis in a few days!
I didn't know the basics of Python
The result of installing python in Anaconda
Open an Excel file in Python and color the map of Japan
In search of the fastest FizzBuzz in Python
Get a datetime instance at any time of the day in Python
An example of the answer to the reference question of the study session. In python.
[Python3] Understand the basics of file operations
An engineer who has noticed the emo of cryptography is trying to implement it in Python and defeat it
[Python3] Code that can be used when you want to change the extension of an image at once
If you add sudo on ubuntu, it will be called the default python.
[Fundamental Information Technology Engineer Examination] I wrote the algorithm of Euclidean algorithm in Python.
You can call the method of the class directly in Python3 without adding @staticmethod
If you write the View decorator in urls.py in Django, the list will be higher.