하루에 하나씩

Python basic - Function & Method 본문

Python

Python basic - Function & Method

JY SHIN 2023. 8. 14. 23:13

Function & Custom function


Creating function

- def : creating function 

- For executing a function, have those open and close parentheses (). 

Adding parameters to a function

- function을 실행시킬 때, ()안에  argument를 넣지 않으면 error가 발생함

  오류 내용 : name에 parameter와 짝지어지는 posintional argment 누락 

* Positional argument란, 인자를 정의된 매개변수의 순서대로 전달하는 방법 
 def add_and_dev(a,b,c)
  print(f"인자 전달 순서 : {a}, {b}, {c}")
  result = (a+b)/c
  return print(f"결과값:{Result}")
 
 add_and_dev(5, 10, 15) 

 * 반대로 Keyword argument는 매개변수를 지정하여 인자를 전달하는 방법 (헷갈리지 않고 원하는 결과를 유도 할 수 있음) 

 add_and_dev(c=15, a= 5, b= 10)

 

 

Default argument

- default parameter 또는 default argment 값을 지정하고 싶다면, fuction을 생성할 때 ()안에 equal(=) to '값' 지정함

- 이 경우 argument를 누락하게 되어도  error가 발생하지 않고, 미리 지정해둔 default 인자가 배정됨 

더보기

Quick Tip 
Docstring(주석) 생성: Three '  or Three "

주속 보기: shift + tab  

 

print vs return 

print: just displays the actual value

returns: save the actual object 

 

- return keyword can save this as a variable 
  (Run result it returns the value that was saved before)

  result값에 square(2) 실행한 값을 저장만하고 출력하지 않음. 그러나 사후에 result를 실행하면 result에 저장된 sqaure(2) 결과 즉, 4 값을 출력시킨다


- the print keyword only prints out the value (save x)  

  result = square(2)를 실행하면 4 값을 출력하지만 result를 실행하면 아무 값도 나오지 않음 

The way I can do the assignment to a new variable is by using the return keyword 

 


Lamda Expression


Lambda expression (=can quickly type in anonymous function)

If you only plan on using a function one time, and maybe you don't want to rewrite the entire- Lambda  keyword/ input/ colon/ output

- How to convert the function to Lambda
1) take away the name 
2) take away def keyword and replace it with lambda
3) take away parentheses
4) take away return keyword

def keyword를 사용해 함수를 정의하는 방법 

Lamda식으로 함수를 쓰는 방법 


Methods on strings


 

Upper, Lower

Split

- Split the string into a list based on the white space.

- Split on a particular string value → tweet.split('#')

  * now the hash tag is no longer in this list because that is what was split on. 

- 응용: list Negative -1으로 hash tag가 달린 마지막 string만 출력하는 법 



keys and items of a dictionary


 

 

 

.keys() / .items() 

Grab the keys and items of a dictionary 

Dictionaries do not retain any order.

.pop()
How you can pop something off of a list or check if something is inside of a list

 

사용법 :

If I want to grab and remove the last item in a list  
(missing the last item of the list -> save it the valuable last so that they can remove an item from a list) 

.pop(index number)

You can just pass that into pop if you want to remove an item at a specific index.

Inner operator

-  in [ , , ] / in list_name

If I want to check if an item is inside of a list, I can just use the inner operator. 

Comments