[codecademy] 4. FUNCTIONS

Posted by 알 수 없는 사용자
2015. 9. 5. 16:49 프로그래밍/Python


FUNCTIONS ( 1 ~ 19 )

1. What Good are Functions? 


샘플코드에서 보면 tax와 tip을 계산하는 함수 두가지를 정의해 놓은것을 볼수 있다.

함수를 정의하고 사용하는 방법을 이제부터 설명할 것이다.


문제없음.


2. Function Junction

i . 함수 헤더는 def 함수이름(): 으로 시작한다. 그리고 필요에 따라 함수이름 뒤 괄호안에 파라미터값을 받을수 있다.

ii. 좋은 함수는 함수에대한 설명도 포함되어야 한다. 설명은 주석(""" ~~ """)을 사용한다.

iii.  함수의 몸통( 내용 )의 절차에 따라 함수가 실행된다. 조건문처럼 들여쓰기 된다. 

문제

Go ahead and create a function, spam, that prints the string "Eggs!" to the console. 

Don't forget to include a comment of your own choosing (enclose it in triple quotes!).


3. Call and Response

함수를 정의한 후에, 정의된 함수를 호출하는 방법이다.

ex> def spam(): 과같이 함수를 정의했다면 spam()과 같이 함수를 호출해주면 된다.


문제

We've set up a function, square. 

Call it on the number 10 (by putting 10 between the parentheses of square()) on line 9!


4. Parameters and Arguments

샘플코드에서 n은 square 함수의 매개변수이다. 매개변수는 인수를 전달할 변수의 이름 역할을 한다.


문제

Check out the function in the editor, power.

It should take two arguments, a base and an exponent, and raise the first to the power of the second.

It's currently broken, however, because its parameters are missing.

Replace the ___s with the parameters base and exponent and call power on a base of 37 and a power of 4.


5. Functions Calling Functions

/

샘플코드와 같이 함수안에서 다른 함수를 호출할 수 있다.


문제

Let's look at the two functions in the editor: one_good_turn (which adds 1 to the number it takes in as an argument) 

and deserves_another (which adds 2).

Change the body of deserves_another so that it always adds 2 to the output of one_good_turn.

6. Practice Makes Perfect


함수만드는 연습을 해보자


문제

1.First, def a function called cube that takes an argument called number. Don't forget the parentheses and the colon!


2.Make that function return the cube of that number (i.e. that number multiplied by itself and multiplied by itself once again).


3.Define a second function called by_three that takes an argument called number.


4.if that number is divisible by 3, by_three should call cube(number) and return its result. Otherwise, by_three should return False.


Don't forget that if and else statements need a : at the end of that line!


7. I Know Kung Fu


모듈을 import 하는 방법을 설명할것이다. 

여기서 모듈은 변수와 함수를 포함한 파일로 한번 import 하게되면 모듈에 포함된 함수와 변수를 사용할수있다.


문제

Before we try any fancy importing, let's see what Python already knows about square roots. 

On line 3 in the editor, ask Python to

which we would expect to equal five.


8. Generic Imports

7번의 문제에서 에러메시지를 보면 sqrt라는 이름이 정의되지 않았다고 에러가 발생했다 .

파이썬은 아직 제곱근을 알지 못한다는것이다.


파이썬 모듈중에 math라는 모듈이 있는데, 이모듈은 유용한 변수,함수, 그리고 다양한 함수들중 sqrt() 함수를 포함한다.

math 모듈에 접근하기 위해서는 import라는 키워드를 이용하면 된다.


문제

You'll need to do two things here:


1. Type import math on line 2 in the editor.

2. Insert math. before sqrt() so that it has the form math.sqrt(). 

   This tells Python not only to import math, but to get the sqrt() function from within math.


Then hit Save & Submit to see what Python now knows.


9. Function Imports

math 모듈을 import 하여 sqrt함수를 사용하는 법을 알았다. 

하지만 오직 sqrt 함수만 필요할 경우에 매번 math.sqrt() 라고 타이핑하는것이 번거로울 때가 있다

샘플코드와 같이 하게되면 모듈 중에서도 특정함수만 import 할수있다.


문제

Let's import only the sqrt function from math this time.

(You don't need the () after sqrt in the from math import sqrt bit.)


10. Universal Imports

만약 우리가 모듈안의 모든 함수와 변수가 필요하다고 할때, 매번 math.XXX 라고 타이핑 해야 할까?

Universal Import 가 이런문제를 해결해준다.


문제

Use the power of from module import * to import everything from the math module on line 3 of the editor.


11. Here Be Dragons

Universal Imports가 표면적으로는 좋아보일수 있다.

하지만, 사용하다보면 이름이 같지만 기능이 다른 두개의 함수가 존재하는 문제가 발생할 수 있다.

만약 자신이 정의한 함수들이 모듈에서 import한 함수들의 이름과 충돌하지 않는다고 해도,

여러 모듈에서 Universal Imports를 한다면 변수나 함수들이 어느 모듈에서 가져온것인지 알 수 없게 된다.

이런 이유로 , module.name을 사용하거나 모듈내에서 필요한 것들만 가져다가 사용하는것이 가장 좋은방법이다.


문제

The code in the editor will show you everything available in the math module.


Click Save & Submit Code to check it out (you'll see sqrt, along with some other useful things like pi, factorial, and trigonometric functions).


12. On Beyond Strings

문자열과 관련된 내장함수들 ( .upper(), .lower(), str(), len() ) 을 이미 알고있고 이 함수들을 가지고 많은 것들을 할수 있다.

이거외에 조금더 분석적인 것들을 알아보자.


문제없음


13. max()

max() 함수는 입력된 숫자들 중 형태에 관계없이 비교하여 가장 큰수를 반환해준다.

ex> max(1,2,3) = 3


문제

Try out the max() function on line 3 of the editor.

You can provide any number of integer or float arguments to max().


14. min()

min은 max()와 반대로 가장 작은수를 반환한다.


문제

Go ahead and set minimum equal to the min() of any set of integers or floats you'd like.



15. abs()

abs() 는 절대값을 반환해준다.

ex>  abs(-3) = abs(3) = 3


문제

Set absolute equal to the absolute value of -42 on line 2


16. type()

마지막으로 type()은 데이터의 형태( 자료형 ) 을 반환해준다.

셈플코드의 출력은 아래와 같다.


문제

Have Python print out the type of an int, a float, and a str string in the editor. 

You can pick any values on which to call type(), so long as they produce one of each.


17. Review : Functions

샘플 코드를 보면서 복습해보자.


문제

1. First, def a function, shut_down, that takes one argument s. Don't forget the parentheses or the colon!

2. Then, if the shut_down function receives an s equal to "yes", it should return "Shutting down"

3. Alternatively, elif s is equal to "no", then the function should return "Shutdown aborted".

4. Finally, if shut_down gets anything other than those inputs, the function should return "Sorry"


18. Review: Modules

Importing modules를 복습해보자


문제

Import the math module in whatever way you prefer. 

Call its sqrt function on the number 13689 and print that value to the console.


19. Review: Built-In Functions

내장함수 사용하는것을 복습해보자.


문제

1. First, def a function called distance_from_zero, with one argument (choose any argument name you like).

2. If the type of the argument is either int or float, the function should return the absolute value of the function input.

3. Otherwise, the function should return "Nope"



Taking a Vacation ( 1 ~ 7 )


1. Before We Begin

파이썬의 함수들을 간단하게 복습해보자.

i. bigger라는 이름을 가지고 first,second 라는 이름의 두개의 인수를 받는 함수를 정의하였다.

ii. 이함수는 내장함수인 max() 함수를 이용하여 큰수를 출력한다.

iii. 마지막으로 bigger 함수는 True값을 반환한다.


문제

Write a function called answer that takes no arguments and returns the value 42.


Even without arguments, you will still need parentheses.


Don't forget the colon at the end of the function definition!


2. Planning Your Trip

여행시 시간당 지출을 계산하는 함수이다.


문제

Define a function called hotel_cost with one argument nights as input.

The hotel costs $140 per night. So, the function hotel_cost should return 140 * nights.


3. Getting There

샘플코드는 과일이름을 인수로 받고 해당과일의 색을 반환해주는 함수이다.


문제

1. Below your existing code, define a function called plane_ride_cost that takes a string, city, as input.

2. The function should return a different price depending on the location, similar to the code example above. Below are the valid destinations 

   and their corresponding round-trip prices.


"Charlotte": 183

"Tampa": 220

"Pittsburgh": 222

"Los Angeles": 475


4. Transportation

설명생략.


문제

1. Below your existing code, define a function called rental_car_cost with an argument called days.

2. Calculate the cost of renting the car:

3. Every day you rent the car costs $40.

4. if you rent the car for 7 or more days, you get $50 off your total.

5. Alternatively (elif), if you rent the car for 3 or more days, you get $20 off your total.

6. You cannot get both of the above discounts.

7. Return that cost.


Just like in the example above, this check becomes simpler if you make the 7-day check an if statement and the 3-day check an elif statement.


5. Pull it Together

설명생략


문제

1. Below your existing code, define a function called trip_cost that takes two arguments, city and days.

2. Like the example above, have your function return the sum of calling the rental_car_cost(days), hotel_cost(days), and plane_ride_cost(city) 

    functions.

It is completely valid to call the hotel_cost(nights) function with the variable days. Just like the example above where we call double(n) with the

 variable a, we pass the value of days to the new function in the argument nights.


6. Hey, You Never Know !


문제

1. Modify your trip_cost function definition. Add a third argument, spending_money.

2. Modify what the trip_cost function does. Add the variable spending_money to the sum that it returns.


7. Plan Your Trip!


문제

After your previous code, print out the trip_cost( to "Los Angeles" for 5 days with an extra 600 dollars of spending money.


Don't forget the closing ) after passing in the 3 previous values!