3.2. 프로그래밍을 향한 첫걸음
First Steps Towards Programming
Of course, we can use Python for more complicated tasks than adding two and two together. For instance, we can write an initial sub-sequence of the Fibonacci series as follows:
당연한 이야기지만, 우리는 파이썬을 2+2보다 복잡한 작업에도 사용할 수 있다. 예를 들면, '피보나치 시리즈의 초기 서브 순서 작성' 같은 작업 말이다.
>>> # Fibonacci series:
... # 두 값의 합이 다음 차례 값에 영향을 준다.
... a, b = 0, 1
>>> while b < 10: # b가 10보다 작을 때
... print(b) # b를 출력한다.(=답으로 내놓는다.)
... a, b = b, a+b # 맨 처음에 주어진 0, 1이 b, a+b로 바뀐다.
# b가 10보다 작지 않을 때까지 이 과정을 반복한다.
...
1 # 여기 나온 값들은 print(b)의 값이다.
1
2
3
5
8
This example introduces several new features.
이 예시는 새로운 기능을 여러가지 알려준다.
- The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.
- 첫번째 줄
a,b = 0,1은 여러 개의 값을 한 번에 설정할 수 있다는 것을 보여준다.a와b가 동시에 0과 1이라는 새로운 값을 얻었다. 마지막 줄의a, b = b, a+b를 통해a와b는 또다시 새로운 값을 가지게 된다. a와 b의 값이 새로 정해지기 전에 마지막 줄a, b = b, a+b의 오른쪽 부분b, a+b가 실행되어야 한다. 오른쪽 부분은 왼쪽에서 부터 차례대로 계산한다.
- 첫번째 줄
- The while loop executes as long as the condition (here: b < 10) remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as in C: < (less than), > (greater than), == (equal to), <= (less than or equal to), >= (greater than or equal to) and != (not equal to).
- while loop (while 반복 문법)은 조건이 맞는 동안 계속해서 실행된다. (위 예시에서 조건은 b<10 이다.)
- 파이썬에서 0이 아닌 정수의 값은 C에서와 마찬가지로 모두 참(True)이다. 0은 거짓(False)이다. 문자열이나 리스트 역시 조건으로 사용할 수 있다. 사실 어떤 시퀀스든 조건으로 사용할 수 있다. 단, 그 길이(글자의 수나 리스트의 내용물)가 0이 아니면 참(True)이고, 시퀀스가 비어있으면 거짓(False)이다. 표준 비교 연산기호는 C와 동일하다.
<(미만),>(초과),==(같음),<=(작거나 같다),>=(크거나 같다),!=(같지 않다).
- The body of the loop is indented: indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.
- loop의 몸체는 들여써야 한다:
- 들여쓰기는 파이썬이 문법에 해당하는 부분을 묶어주는 방식이다. 들여쓰는 줄마다 tab키나 space키를 사용하면 된다. 우리는 텍스트 에디터를 통해 더 복잡한 명령들을 작성하게 될텐데, 최근의 텍스트 에디터는 대부분 자동 들여쓰기 기능을 가지고 있다. 복합문법을 대화형으로 입력할 경우, 문법이 끝난 것을 알 수 있도록 마지막에 반드시 빈 줄이 와야 한다. 그렇지 않으면 parser(컴퓨터의 문장 구조 분석 및 오류 점검 프로그램)가 당신이 언제 마지막 문장을 작성한 것인지 구별할 수 없기 때문이다. 기본 블록 내의 각 줄은 같은 양 만큼 들여쓰는 것에 주의하자.
- The print() function writes the value of the argument(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple arguments, floating point quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:
- print()함수는 주어진 인수들의 값을 우리에게 보여준다. print()는 한 번에 여러가지 값을 다룰 수 있고, 그 값을 우리가 원하는 방식으로 보여줄 수 있다. ('파이썬을 계산기로 사용하는 방법'에서 살펴보았듯이) print()를 사용하면 문자열은 따옴표 없이 출력된다. 그리고 공백 한 칸이 각각의 값들 사이에 삽입된다. 이를 통해 우리는 다음 예시와 같은 멋진 형태를 만들 수 있다.
The keyword argument end can be used to avoid the newline after the output, or end the output with a different string:>>> i = 256*256 >>> print('The value of i is', i) The value of i is 65536
end는 출력값 뒤에 새로운 줄이 생기는 것을 막을 수 있다. 또는 다양한 문자열과 함께 출력을 마무리할 수 있다.>>> a, b = 0, 1 >>> while b < 1000: ... print(b, end=',') ... a, b = b, a+b ... 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
- print()함수는 주어진 인수들의 값을 우리에게 보여준다. print()는 한 번에 여러가지 값을 다룰 수 있고, 그 값을 우리가 원하는 방식으로 보여줄 수 있다. ('파이썬을 계산기로 사용하는 방법'에서 살펴보았듯이) print()를 사용하면 문자열은 따옴표 없이 출력된다. 그리고 공백 한 칸이 각각의 값들 사이에 삽입된다. 이를 통해 우리는 다음 예시와 같은 멋진 형태를 만들 수 있다.