2010. 3. 10. 20:36

파이썬으로 공부하는 과학자처럼 생각하기 2판 - 2장 변수, 표현문, 명령문


원문 주소: http://openbookproject.net/thinkCSpy/ch02.html

2. Variables, expressions and statements
2. 변수, 표현문 그리고 명령문

2.1. Values and types
2.1. 값들과 형식들

A value is one of the fundamental things — like a letter or a number — that a program manipulates. The values we have seen so far are 2 (the result when we added 1 + 1), and "Hello, World!".

은 아주 기본적인 것들 중에 하나입니다 - 글자 하나나 숫자 하나처럼 말이죠 - 이것은 프로그램을 조작합니다. 이 값들은 이제껏 봐왔던 것들로 치면 2 (1+1 을 더했을 때의 결과입니다.) 와 "Hello, world!" 입니다.


These values belong to different types2 is an integer, and "Hello, World!" is a string, so-called because it contains a string of letters. You (and the interpreter) can identify strings because they are enclosed in quotation marks.

이러한 값들은 다른 형식들에 속하고 있습니다: 2 는 정수형(integer) 이고 "Hello, world!" 는 문자열(string) 인데, 이렇게 불리는 이유는 글자들로 된 문자열을 포함하고 있기 때문이니다. 사용자(그리고 인터프리터)는 이러한 문장이 큰따옴표로 묶여져 있기 때문에 구별할 수가 있습니다.

The print statement also works for integers.

print 명령문은 또한 정수형들에서도 작동이 됩니다.

>>> print 44

If you are not sure what type a value has, the interpreter can tell you.

만약에 정확한 값의 형식을 확인할 수 없다면, 인터프리터가 가르쳐 줄 것입니다.

>>> type("Hello, World!")
<type 'str'>
>>> type(17)
<type 'int'>

Not surprisingly, strings belong to the type str and integers belong to the type int. Less obviously, numbers with a decimal point belong to a type called float, because these numbers are represented in a format called floating-point.

놀라울게 없는 것이, 문자열 값들은 str 형식에 속해 있으며, 정수형 값들은 int 형식에 속해 있습니다. 덜 분명한 것은 십진소수형으로 되어 있는 숫자들은 float 라는 형식에 속해 있는데, 이는 이러한 숫자들일 부동-소숫점(floating-point)이라고 불리는 형식으로 표현되기 때문입니다.

>>> type(3.2)<type 'float'>

What about values like "17" and "3.2"? They look like numbers, but they are in quotation marks like strings.

"17""3.2" 와 같은 값들은 어떤가요? 숫자로 보이겠지만, 문자열처럼 큰따옴표들로 묶여져 있습니다.

>>> type("17")<type 'str'>
>>> type("3.2")<type 'str'>

They’re strings.

이들은 문자열입니다.

Strings in Python can be enclosed in either single quotes (‘) or double quotes (“):

파이썬에서 문자열은 작은따옴표(')나 큰따옴표로(")  둘중하나로 묶여질 수 있습니다.

>>> type('This is a string.')<type 'str'>>>> type("And so is this.")<type 'str'>

Double quoted strings can contain single quotes inside them, as in "Bruce's beard", and single quoted strings can have double quotes inside them, as in 'The knights who say "Ni!"'.

큰따옴표 문장은 "Bruce's beard" 처럼, 문장 내에 작은따옴표가 들어갈 수 있습니다. 작은따옴표 문장도 'The knights who say "Ni!"' 처럼 큰따옴표를 문장내에 가질 수 있습니다.

When you type a large integer, you might be tempted to use commas between groups of three digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:

당신은 큰 정수를 입력할때, 1,000,000 처럼 3개의 숫자단위를 묶는데 사용되는 쉼표를 넣는 유혹에 빠질수 있습니다. 파이썬에서 맞지않는 정수형이나, 문법은 맞습니다:

>>> print 1,000,000
1 0 0

Well, that’s not what we expected at all! Python interprets 1,000,000 as a list of three items to be printed. So remember not to put commas in your integers.

음, 이건 우리가 전혀 예상하지 못했던건데요! 파이썬은 1,000,000 이라는 구문을 출력될 세개의 항목의 목록(1 과 000 과 000 이니 1 과 0 과 0 이 출력됩니다.) 이라고 해석합니다. 그러니 당신의 정수형 자료에는 중간에 쉼표를 넣지 않는다는 것을 기억하세요.

2.2. Variables
2.2 변수

One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value.

프로그래밍 언어에서 가장 강력한 특징들중 하나는 변수를 조작할 수 있다는 것입니다. 변수는 값을 참조하는 이름입니다.

The assignment statement creates new variables and gives them values:

할당 구문은 새 변수를 만들고 다음과 같은 값을 부여해서 만듭니다.

>>> message = "What's up, Doc?"
>>> n = 17
>>> pi = 3.14159

This example makes three assignments. The first assigns the string "What's up, Doc?" to a new variable named message. The second gives the integer 17 to n, and the third gives the floating-point number 3.14159 to pi.

이 예제는 세개의 할당 연산을 보여줍니다. 첫번째는 message 라는 이름의 새 변수에 "What's up, Doc?" 라는 문자열을 할당합니다. 두번째는 n 이라는 새 변수에 정수 17을 부여합니다. 그리고 세번째는 pi 라는 새 변수에 3.14159 라는 부동-소숫점 수를 부여합니다.

The assignment operator, =, should not be confused with an equals sign (even though it uses the same character). Assignment operators link a name, on the left hand side of the operator, with a value, on the right hand side. This is why you will get an error if you enter:

할당 연산자 = 는 등호 연산자와 (비록, 같은 문자를 사용하지만) 혼동되어서는 안됩니다. 할당 연산자는 좌변에 name (변수명) 과 우변에 value (값)을 서로 연결합니다. 이것이 왜 당신이 다음과 같이 입력하면 오류가 된다는 것을 보여주는 이유가 될 것입니다.

>>> 17 = n

A common way to represent variables on paper is to write the name with an arrow pointing to the variable’s value. This kind of figure is called a state diagram because it shows what state each of the variables is in (think of it as the variable’s state of mind). This diagram shows the result of the assignment statements:

일반적으로 종이에 변수를 표현하기로는 변수 이름을 쓰고 변수의 값을 화살표로 가리켜 나타냅니다. 이러한 종류의 형태를 전체 상태도(스테이트 다이어그램)이라고 하는데, 그 이유는 변수 내부의 상태를 보여주기 때문입니다. (변수의 생각 상태라고 생각해보세요.)

The print statement also works with variables.

또한 print 명령문은 변수들과 함께 작동됩니다.

>>> print message
What's up, Doc?
>>> print n
17
>>> print pi
3.14159

In each case the result is the value of the variable. Variables also have types; again, we can ask the interpreter what they are.

각 명령문의 수행결과 변수의 값을 출력합니다. 변수들은 또한 형식을 가집니다; 우리는 인터프리터에게 그들이 뭔지 다시한번 더 물어 볼 수 있습니다.

>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>

The type of a variable is the type of the value it refers to.

변수의 형식은 그 값이 참조하는 값의 형식입니다.

2.3. Variable names and keywords
2.3. 변수명과 키워드

Programmers generally choose names for their variables that are meaningful — they document what the variable is used for.

프로그래머들은 변수들이 의미를 가질수 있게끔 일반적으로 이름을 선정합니다. - 그들은 그 변수가 뭐에 사용되는지 문서화 합니다.

Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. Although it is legal to use uppercase letters, by convention we don’t. If you do, remember that case matters. Bruce and bruce are different variables.

변수명은 임의의 길이를 가질 수 있습니다. 그들은 글자와 숫자를 동시에 포함할 수 있지만, 이름은 글자로 시작해야 합니다. 대문자로 사용하는게 합당하긴하나, 편의상 우리를 그러지 않습니다. 만약에 쓰신다면, 대소문자를 고려하셔야합니다. Brucebruce 는 서로 다른 변수명 입니다.

The underscore character ( _) can appear in a name. It is often used in names with multiple words, such as my_name or price_of_tea_in_china.

밑줄문자(_) 는 이름에 나타날 수 있습니다. my_name 이나 price_of_tea_in_china 처럼, 보통 다수의 단어들과 함께 사용되는 이름에 사용됩니다.

If you give a variable an illegal name, you get a syntax error:

만약 규칙에 맞지 않는 변수 이름을 지정한다면, 문법 오류가 발생합니다.

>>> 76trombones = "big parade"
SyntaxError: invalid syntax
>>> more$ = 1000000
SyntaxError: invalid syntax
>>> class = "Computer Science 101"
SyntaxError: invalid syntax

76trombones is illegal because it does not begin with a letter. more$ is illegal because it contains an illegal character, the dollar sign. But what’s wrong with class?

76trombones 는 시작할때 글자가 아니여서 규칙에 어긋납니다. more$ 는 규칙에 맞지 않는 문자인 달러($) 표시가 있어서 규칙에 어긋납니다. 하지만 class 는 무슨 문제가 있을까요?

It turns out that class is one of the Python keywords. Keywords define the language’s rules and structure, and they cannot be used as variable names.

class 는 파이썬의 키워드(핵심어)들 중에 하나입니다. 키워드들은 언어의 규칙과 구조를 정의하고, 변수의 이름으로 지정될 수 없습니다.

Python has thirty-one keywords:
파이썬에는 31가지 키워드가 있습니다:

and as assert break class continue
def del elif else except exec
finally for from global if import
in is lambda not or pass
print raise return try while with
yield          

You might want to keep this list handy. If the interpreter complains about one of your variable names and you don’t know why, see if it is on this list.

아마 이 목록을 보기 쉽게 유지하는걸 원할 것입니다. 만약 인터프리터가 당신이 이름을 정한 변수들 중에 하나에 관해 불평하는데, 그 이유를 모른다면, 그것이 이 목록에 있는지를 한번 보세요.

2.4. Statements
2.4. 명령문

A statement is an instruction that the Python interpreter can execute. We have seen two kinds of statements: print and assignment.


명령문(선언문)은 파이썬이 수행할 수 있는 명령문 입니다. 우리는 두종류의 구문을 봐왔습니다: 출력과 할당.

When you type a statement on the command line, Python executes it and displays the result, if there is one. The result of a print statement is a value. Assignment statements don’t produce a result.

명령줄 상에 명령문을 입력할 때, 만약 파이썬은 이를 실행하고 결과를 표시합니다. 출력 구문의 실행 결과는 값입니다. 할당 구문은 결과를 출력하지 않습니다.

A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the statements execute.

스크립트는 보통 명령문들을 포함하고 있습니다. 만약 하나 이상의 명령문이 있을때, 결과값은 명령문들이 실행되는 동안 한번엔 나타납니다.

For example, the script

예를 들면, 이 스크립트

print 1
x = 2
print x

produces the output:

는 다음의 출력을 보여줍니다.

1
2

Again, the assignment statement produces no output.

다시 말하지만, 할당 구문은 출력 부분이 없습니다.

2.5. Evaluating expressions
2.5. 식을 계산하기

An expression is a combination of values, variables, and operators. If you type an expression on the command line, the interpreter evaluates it and displays the result:

(expression)은 값, 변수, 연산자의 조합으로 되어 있습니다. 명령줄에 식을 입력하면, 인터프리터는 이를 계산하여 결과값을 보여줍니다.

>>> 1 + 12

The evaluation of an expression produces a value, which is why expressions can appear on the right hand side of assignment statements. A value all by itself is a simple expression, and so is a variable.

식의 계산은 값을 출력하는데, 이는 왜 식이 할당구문의 우항(오른쪽 부분 - 계산된 값은 변수가 없습니다.)에 위치해야 하는지의 이유를 보여줍니다. 값은 그 자체로 간단한 식이므로, 변수도 마찬가지 입니다.

>>> 17
17
>>> x
2

Confusingly, evaluating an expression is not quite the same thing as printing a value.

혼동스럽게도, 식을 계산하는 것은 값을 출력하는 것과 똑같지는 않습니다.

>>> message = "What's up, Doc?"
>>> message
"What's up, Doc?"
>>> print message
What's up, Doc?

When the Python shell displays the value of an expression, it uses the same format you would use to enter a value. In the case of strings, that means that it includes the quotation marks. But the print statement prints the value of the expression, which in this case is the contents of the string.

파이썬 쉘이 식의 값을 출력할때, 값을 입력했었을 때와 동일한 형식을 사용합니다. 문자열의 경우, 이것은 따옴표를 포함한다는 의미를 가집니다. 하지만, 식의 값을 출력하는 print 명령문을 썼을 때, 이 경우에는 문자열의 내용만 보여 줍니다.

In a script, an expression all by itself is a legal statement, but it doesn’t do anything. The script

스크립트에서는 식내에서의 모두가 규칙에 맞습니다만, 아무것도 하지 않습니다. 다음의 스크립트들은

17
3.2
"Hello, World!"
1 + 1

produces no output at all. How would you change the script to display the values of these four expressions?

아무런 출력을 하지 않습니다. 위 4가지 식의 값들을 표시할려면 스크립트를 어떻게 변경해야 할까요?

2.6. Operators and operands
2.6. 연산자와 피연산자

Operators are special symbols that represent computations like addition and multiplication. The values the operator uses are called operands.

연산자(operators, 오퍼레이터) 들은 덧셈과 곱셈과 같은 계산을 대표하는 특수 기호입니다. 연산자가 사용하는 값들을 피연산자(operands, 오퍼랜드) 들이라 부릅니다.

The following are all legal Python expressions whose meaning is more or less clear:

다음의 의미가 더 분명하거나 덜하는 파이썬식들은 맞는 구문들입니다:

20+32   hour-1   hour*60+minute   minute/60   5**2   (5+9)*(15-7)

The symbols +, -, and /, and the use of parenthesis for grouping, mean in Python what they mean in mathematics. The asterisk (*) is the symbol for multiplication, and ** is the symbol for exponentiation.

파이썬에서 기호 +, -/ 그리고 묶기(그루핑) 위한 괄호들은 수학에서 쓰는 것과 같은 의미를 가집니다. * (asterisk, 아스크리스크, 별표) 는 곱셈을, ** 는 지수 (exponentiation, 누승, 거듭제곱) 의 기호를 나타합니다.

When a variable name appears in the place of an operand, it is replaced with its value before the operation is performed.

변수명이 피연산자의 자리에 있을 때에는, 계산이 이뤄지기 전에 분수명이 값으로 교체됩니다.

Addition, subtraction, multiplication, and exponentiation all do what you expect, but you might be surprised by division. The following operation has an unexpected result:

덧셈, 뺄셈, 곱셈과 누승은 당신이 원했던대로 작동이 되지만, 나눗셈에서는 조금 놀랄 것입니다. 다음의 연산은 예상하지 않은 결과를 보여주고 있습니다.

>>> minute = 59
>>> minute/60
0

The value of minute is 59, and 59 divided by 60 is 0.98333, not 0. The reason for the

discrepancy
discrepancy is that Python is performing integer division.

minute 라는 변수의 값은 59 이고, 59 나누기 60은 0.98333 이지, 0 이 아닙니다. 이런 모순의 원인은 파이썬이 정수 나눗셈을 하는데에 있습니다.

When both of the operands are integers, the result must also be an integer, and by convention, integer division always rounds down, even in cases like this where the next integer is very close.

두 피연산자가 정수일 때, 결과값도 정수여야 합니다. 그리고 편의상 정수 나눗셈은 항상 소숫점 버림 연산을 수행하며 심지어 다음 정수에 아주 근접할 때에도 마찬가지로 작동합니다.

A possible solution to this problem is to calculate a percentage rather than a fraction:

이 문제를 푸는 가능한 하나의 해결책으로 소숫점 보다는 백분율로 계산하는 것입니다.

>>> minute*100/60
98

Again the result is rounded down, but at least now the answer is approximately correct. Another alternative is to use floating-point division. We’ll see in the chapter 4 how to convert integer values and variables to floating-point values.

다시, 결과값 소숫점 버림 연산을 하나, 적어도 이제는 대략적으로 맞아졌습니다. 다른 대안법으로 부동-소숫점 나눗셈 연산을 사용합니다. 우리는 이를 4장에서 볼수 있을 것입니다.

2.7. Order of operations
2.7. 연산의 순서

When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. Python follows the same precedence rules for its mathematical operators that mathematics does. The acronym PEMDAS is a useful way to remember the order of operations:

하나 이상의 연산자를 사용할 때, 계산의 순서는 우선의 법칙(Rules of Precedence) 에 따릅니다. 파이썬은 수학에서 사용하는 우선의 법칙과 동일한 우선 규칙들을 따릅니다. 약어 PEMDAS는 는 연산의 순서를 기억하는데 유용한 방법들 중에 하나입니다.

(참고: PEMDAS - Please Excuse MDear 

A
unt Sally / 내 사랑하는 셀리 이모를 용서해 주세요. 각각 Parentheses, Exponent, Multiplication, Division, Addition, Subtraction 를 의미합니다.

  1. Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even though it doesn’t change the result.

    호는 가장 높은 우선순위를 가지고 있으며, 사용자가 원하는 계산 식에서의 우선순서를 강제로 주기 위해 사용될 수 있습니다. 우선적으로 괄호 내의 식들이 계산되므로, 2 * (3 - 1) 은 4 가 되고 (1+1)**(5-2) 는 8이 됩니다. 예를 들어 (minute * 100) / 60 과 같이 비록 결과값은 변화지 않아도, 괄호를 사용해서 더 쉽게 읽을 수 있게 할 수 있습니다.

  2. Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3 and not 27.

    승은 다음으로 가장 높은 우선순위를 가지고 있습니다. 그래서 2**1+1 은 3 이지 4가 아니며, 3*1**3 은 3이지 27이 아닙니다.

  3. Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So 2*3-1 yields 5 rather than 4, and 2/3-1 is -1, not 1 (remember that in integer division, 2/3=0).

    셈과 눗셈은 같은 우선순위를 가지고 있으며, 동일한 우선순위를 가지고 있는 셈과 셈보다 높은 우선순위를 가지고 있습니다. 2*3-1 은 4 가 아니고 5를 나타냅니다. 그리고 2/3-1 은 -1 이지 1 이 아닙니다.

  4. Operators with the same precedence are evaluated from left to right. So in the expression minute*100/60, the multiplication happens first, yielding 5900/60, which in turn yields 98. If the operations had been evaluated from right to left, the result would have been 59*1, which is 59, which is wrong.

    연산자의 우선순위가 동일하다면, 계산은 왼쪽에서 오른쪽으로 진행됩니다. 그래서 minute*100/60 에서는 곱샘이 먼저 일어나서 5900/60 이 되고, 그 다음에 98 로 됩니다. 만약에 계산이 오른쪽에서 왼쪽으로 되었다면, 그 결과는 59*1 이 되어 59가 될 것이고, 틀린 결과값이 됩니다.

2.8. Operations on strings
2.8. 문자열들에 대한 연산

In general, you cannot perform mathematical operations on strings, even if the strings look like numbers. The following are illegal (assuming that message has type string):

일반적으로, 숫자들처럼 보이더라도, 문자열을 대상으로는 수학연산을 수행할 수 없습니다. 다음의 구문들은 규칙에 어긋납니다 (message 는 문자열 형식이라 가정합니다.)

message-1   "Hello"/123   message*"Hello"   "15"+2

Interestingly, the + operator does work with strings, although it does not do exactly what you might expect. For strings, the + operator represents concatenation, which means joining the two operands by linking them end-to-end. For example:

흥미롭게도, + 연산자는 당신이 예측한 것과는 정확하지는 않지만, 문자열과 작동이 됩니다. 문자열에 대해서는 + 연산자가 접합(concatenation, 콘캐탠네이션)을 나타내는데, 이는 두개의 피연산자들의 끝과 끝사이를 연결해주는 의미를 가집니다.

fruit = "banana"baked_good = " nut bread"print fruit + baked_good

The output of this program is banana nut bread. The space before the word nut is part of the string, and is necessary to produce the space between the concatenated strings.

이 프로그램의 출력값은 banana nut bread 입니다. nut 이전에 붙는 공백은 문자열의 일부이고, 접합된 문자열들 사이에 필요한 공백을 출력하는데 필요합니다.

The * operator also works on strings; it performs repetition. For example, 'Fun'*3 is 'FunFunFun'. One of the operands has to be a string; the other has to be an integer.

* 연산자 또한 문자열과 작동이 됩니다; 이 연산자는 반복  수행을 나타냅니다. 예를 들어 'Fun'*3'FunFunFun' 입니다. 피연산자들 중에 하나가 문자열이면, 다른 하나는 정수형이여야 합니다.

On one hand, this interpretation of + and * makes sense by

analogy
analogy with addition and multiplication. Just as 4*3 is equivalent to 4+4+4, we expect "Fun"*3 to be the same as "Fun"+"Fun"+"Fun", and it is. On the other hand, there is a significant way in which string concatenation and repetition are different from integer addition and multiplication. Can you think of a property that addition and multiplication have that string concatenation and repetition do not?

다른 한편으로 +* 연산자의 해석은 덧셈과 곱셈 연산의 유추를 통해 이해할 수 있습니다. 단순히 4*34+4+4 와 같듯이 우리는 "Fun"*3"Fun"+"Fun"+"Fun" 과 동일하다고 예상하고, 실제로 그렇습니다. 다른한편으로, 문자열 접합과 반복하는 방법이 정수 덧셈과 곱셈과는 확연이 차이가 납니다. 문자열 접합과 반복이 없는 덧셈과 곱셈의 성질을 생각 할 수 있습니까?

2.9. Input
2.9. 입력

There are two built-in functions in Python for getting keyboard input:

파이썬에서는 키보드 입력을 받기 위한 두가지 내장-된 기능들이 있습니다.

n = raw_input("Please enter your name: ")
print n
n = input("Enter a numerical expression: ")
print n

A sample run of this script would look something like this:

이 스크립 수행을 예제로 돌린결과는 다음과 같이 보여집니다:

$ python tryinput.py
Please enter your name: Arthur, King of the Britons
Arthur, King of the Britons
Enter a numerical expression: 7 * 3
21

Each of these functions allows a prompt to be given to the function between the parentheses.

각 함수들은 괄호들 사이의 함수에게 주어지는 프롬프트(prompt) 사용을 허용합니다.

2.10. Composition
2.10. 조합

So far, we have looked at the elements of a program — variables, expressions, and statements — in isolation, without talking about how to combine them.

지금까지 우리는 프로그램의 요소들을 어떻게 조합하지 않고 독자적으로만 보아왔습니다. - 변수, 표현문 그리고 명령문 -

One of the most useful features of programming languages is their ability to take small building blocks and compose them. For example, we know how to add numbers and we know how to print; it turns out we can do both at the same time:

프로그램 언어의 가장 유용한 기능들중 하나는 작은 건물 블럭처럼 만들어서 그들을 조합하는 것입니다. 예를 들어 우리는 숫자를 더하고, 이들을 출력하는 방법을 알고 있습니다; 우리는 이들을 동시에 할 수 있는 게 이미 알려져 있습니다.

>>>  print 17 + 320

In reality, the addition has to happen before the printing, so the actions aren’t actually happening at the same time. The point is that any expression involving numbers, strings, and variables can be used inside a print statement. You’ve already seen an example of this:

실제로는 인쇄하기 전에 덧샘이 수행되어져야 하기 때문에, 이런 행동들이 동시에 일어나지는 않습니다. 숫자와 문자열, 변수와 관련된 모든 표현문들은 print 명령문 내에서 사용될 수 있다는게 요점입니다. 이미 이거와 같은 예제를 보신적이 있으실 겁니다.

print "Number of minutes since midnight: ", hour*60+minute

You can also put arbitrary expressions on the right-hand side of an assignment statement:

사용자는 또한 할당 명령문의 우항 부분에 임의의 표현식을 입력할 수 있습니다.

percentage = (minute * 100) / 60

This ability may not seem impressive now, but you will see other examples where composition makes it possible to express complex computations neatly and concisely.

이런 기능은 지금은 그다지 인상적이지 않아 보일수 있지만, 나중에 다른 예제들을 보면, 이러한 조합들이 복잡한 계산을 깔끔하고 정확하게 표현하는 것이 가능하다는 것을 알 수 있을 것입니다.

Warning: There are limits on where you can use certain expressions. For example, the left-hand side of an assignment statement has to be a variable name, not an expression. So, the following is illegal: minute+1 = hour.

경고: 특정 계산식을 사용할 때에는 제한이 있습니다. 예를 들어 할당 연산에서 좌항에는 변수 이름만이 들어가야하고, 표현식이 들어가서는 안됩니다. 따라서 다음의 문장은 맞지 않습니다: minute+1 = hour

2.11. Comments
2.11. 주석문

As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why.

프로그램이 커지고 점점 복잡해짐에 따라, 이들을 읽어내기가 점점 더 힘들어 집니다. 형식 언어들이 조밀해지면, 보통은 코드의 일부분을 읽어서 어떻게 동작하고 왜 그렇게 되는지 알아내기가 어렵습니다.

For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments, and they are marked with the # symbol:

이러한 이유로 인해, 이 프로그램이 무엇을 하는지 자연언어로 프로그램에다가 첨부하는 것은 좋은 생각입니다. 이런 표시문들을 주석문으로 불리우며, # 부호로 표시되어 집니다.

# compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60

In this case, the comment appears on a line by itself. You can also put comments at the end of a line:

이럴 경우, 한줄 자체가 주석문으로 보여집니다. 줄 끝에다가도 주석을 달 수 있습니다.

percentage = (minute * 100) / 60     # caution: integer division

Everything from the # to the end of the line is ignored — it has no effect on the program. The message is intended for the programmer or for future programmers who might use this code. In this case, it reminds the reader about the ever-surprising behavior of integer division.

줄 끝에 있는 # 에서 끝까지는 무시되어 집니다 - 프로그램에는 아무런 영향을 주지 않습니다. 이 메시지는 프로그래머나 이 코드를 볼 미래의 프로그래머들을 위합니다. 위의 예제인 경우, 정수 나눗셈 성향에 관한 놀라움을 알려줍니다.

2.12. Glossary
2.12. 용어

value
A number or string (or other thing to be named later) that can be stored in a variable or computed in an expression.

표현식에 담겨져 있거나 변수에 저장되어 있는 숫자나 문장 (또는 이후에 이름 붙여지는 다른 것들)
type
형식
A set of values. The type of a value determines how it can be used in expressions. So far, the types you have seen are integers (type int), floating-point numbers (type float), and strings (type string).

값들의 집합. 값의 형식는 표현식에서 사용되는 방식을 결정합니다. 지금까지 당신은 정수(int 형식), 부동-소숫점(float 형식) 그리고 문자열(string 형식) 형식을 봐 왔습니다.
int
int (정수)
A Python data type that holds positive and negative whole numbers.

양수와 음수의 숫자들을 가질 수 있는 파이썬 자료 형식
str
str (문자열)
A Python data type that holds a string of characters.

글자들로된 문자열을 가질수 있는 파이썬 자료 형식
float
float (부동소숫점)

A Python data type which stores floating-point numbers. Floating-point numbers are stored internally in two parts: a base and an exponent. When printed in the standard format, they look like decimal numbers. Beware of rounding errors when you use floats, and remember that they are only approximate values.

부동-소숫점 숫자를 담는 파이썬 자료 형식. 부동-소숫점 숫자들은 내부적으로 두부분으로 저장합니다. 밑(base) 과 지수 (exponent). 표준 형태로 출력이 될때, 이들은 십진 숫자들처럼 보입니다. float 형식을 사용할 때, 반올림오차를 주의하시고, 이들은 단지 근사값이라는 것을 기억하시기 바랍니다.
variable
변수
A name that refers to a value.

값을 가리키는 이름
assignment statement
할당 명령문

A statement that assigns a value to a name (variable). To the left of the assignment operator, =, is a name. To the right of the assignment operator is an expression which is evaluated by the Python interpreter and then assigned to the name. The difference between the left and right hand sides of the assignment statement is often confusing to new programmers. In the following assignment:

값을 하나의 이름 (변수) 에 지정하는 명령문. 할당 연산자 = 의 왼쪽 부분은 이름이 됩니다. 할당 연산자의 오른쪽 부분은 파이썬에 의해서 계산이 되는 표현식입니다. 할당 명령문에서 좌항과 우항의 차이는 새로운 프로그래머들에게는 보통 혼란을 줍니다. 다음 할당문에서:

n = n + 1

n plays a very different role on each side of the =. On the right it is a value and makes up part of the expression which will be evaluated by the Python interpreter before assigning it to the name on the left.

n= 의 방향에 따라 아주 다른 역할을 합니다. 오른쪽 부분의 것은 이고, 왼쪽에 이름에 할당되기 이전에 파이썬 인터프리터에 의해서 계산되어질 의 일부를 구성합니다.

assignment operator
할당 연산자
= is Python’s assignment operator, which should not be confused with the mathematical comparison operator using the same symbol.

= 는 파이썬의 할당 연산자로써, 동일한 부호를 사용하는 수학 비교연산자와 혼란이 되어서는 안됩니다.
state diagram
전체 상태도(스테이트 다이어그램)
A graphical representation of a set of variables and the values to which they refer.

변수들의 묶음과 그들이 의미하는 값을 나타내는 시각적인 표현
variable name
변수명
A name given to a variable. Variable names in Python consist of a sequence of letters (a..z, A..Z, and _) and digits (0..9) that begins with a letter. In best programming practice, variable names should be chosen so that they describe their use in the program, making the program self documenting.

변수에게 주어지는 이름입니다. 파이썬에서의 변수명은 문자(a .. z, A .. Z 와 _)들의 조합과 문자로 시작하는 숫자들의 조합(0 .. 9)으로 되어 있습니다. 최고의 프로그래밍 방식에서 변수명은 프로그램이 자체 문서화될 수 있게끔, 프로그램 내에 사용되는 것을 설명하기 위해 선택되어집니다.
keyword
키워드
A reserved word that is used by the compiler to parse program; you cannot use keywords like if, def, and while as variable names.

컴파일러가 프로그램을 해석하는 데 사용되는 예약어입니다; 사용자는 다음의 if, def, while 와 같은 키워드들을 변수명에 사용할 수 없습니다.
statement
명령문
An instruction that the Python interpreter can execute. Examples of statements include the assignment statement and the print statement.

파이썬 인터프리터가 실행될 수 있는 선언문. 명령문의 예들은 할당 명령문과 출력 명령문을 포함합니다.
expression
표현식
A combination of variables, operators, and values that represents a single result value.

단일 결과값을 나타내는 변수, 연산자, 값들의 조합
evaluate
계산
To simplify an expression by performing the operations in order to yield a single value.

단일 값으로 만들어내기 위해 연산들을 수행하여 표현식을 간단하게 만드는 행위
operator
연산자
A special symbol that represents a simple computation like addition, multiplication, or string concatenation.

덧셈, 곱셈과 문자열 결합과 같은 단순한 계산을 나타내는 특별 부호
operand
피연산자
One of the values on which an operator operates.

연산자가 계산되는데 사용되는 대상값들
integer division
정수 나눗셈
An operation that divides one integer by another and yields an integer. Integer division yields only the whole number of times that the numerator is divisible by the denominator and discards any remainder.

정수를 다른 정수로 나눴을 때, 결과가 정수로 나오는 연산. 정수 나눗셈은 분자 값이 분모 의해 나눠지는 횟수만을 계산하고, 나머지는 버립니다.
rules of precedence
우선순위 규칙

The set of rules governing the order in which expressions involving multiple operators and operands are evaluated.

다수의 연산자와 피연산자가 계산 되어질 때에 관련되어 연산규칙을 관리하는 규칙들의 묶음
concatenate
결합
To join two operands end-to-end.

두개의 피연산자의 끝과 끝사이를 이어줌
composition
조합

The ability to combine simple expressions and statements into compound statements and expressions in order to represent complex computations concisely.

복잡한 계산식을 정확하게 표현하기 위해, 단순 표현식과 명령문들을 조합하여 합성 명령문과 표현식을 표현하는 능력
comment
주석
Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program.

프로그램 내에서 다른 프로그래머들에게 의미있는 정보들 (또는 소스 코드를 읽는 사람들), 그리고 프로그램 수행에는 어떠한 영향을 주지 않습니다.

2.13. Exercises
2.13. 연습

  1. Record what happens when you print an assignment statement:
    다음 할당문을 출력할 때 결과를 기록하세요.

    >>> print n = 7

    How about this?
    이건 어떻까요?

    >>> print 7 + 5

    Or this?
    아니면 이건요?

    >>> print 5.2, "this", 4 - 2, "that", 5/2.0

    Can you think a general rule for what can follow the print statement? What does the print statement return?
    print 명령문을 따르는 일반적인 규칙들을 생각할 수 있습니까? print 명령문이 수행하고 되돌려지는 것은 무엇을 할까요?

  2. Take the sentence: All work and no play makes Jack a dull boy. Store each word in a separate variable, then print out the sentence on one line using print.
    문장을 잡으세요: 공부만 시키고 놀게 하지 않으면 아이는 바보가 된다. 각각의 단어들을 별도의 변수들로 저장해서 print 를 사용해 하나의 문장으로 출력하게 해보세요.

  3. Add parenthesis to the expression 6 * 1 - 2 to change its value from 4 to -6.
    표현식 6 * 1 - 2 에서 괄호를 추가해서 4 를 -6 으로 바꾸게 해보세요.

  4. Place a comment before a line of code that previously worked, and record what happens when you rerun the program.
    이전에 작동이 되었던 코드에 주석문을 추가해보시고, 다시 프로그램을 실행하여 그 결과가 어떻게 되었는지 기록해보세요.

  5. The difference between input and raw_input is that input evaluates the input string and raw_input does not. Try the following in the interpreter and record what happens:
    inputraw_input 의 차이점은 input 은 문장을 계산하지만, raw_input 은 그렇지 않다는 것입니다. 다음의 문장들을 인터프리터에게 입력하여, 결과를 기록해보세요.

    >>> x = input()
    3.14
    >>> type(x)
    >>> x = raw_input()
    3.14
    >>> type(x)
    >>> x = input()
    'The knights who say "ni!"'
    >>> x

    What happens if you try the example above without the quotation marks?
    위 예제에서 따옴표를 제거해서 시도하면 어떤 결과가 나올까요?

    >>> x = input()
    The knights who say "ni!"
    >>> x
    >>> x = raw_input()
    'The knights who say "ni!"'
    >>> x

    Describe and explain each result.
    각각의 결과를 설명하고 왜 그런지 표현해 보세요.

  6. Start the Python interpreter and enter bruce + 4 at the prompt. This will give you an error:
    파이썬 인터프리터를 시작해서 bruce + 4 를 프롬프트 상에서 입력해보세요. 그리고 다음의 오류를 보게 될 것입니다.

    NameError: name 'bruce' is not defined

    Assign a value to bruce so that bruce + 4 evaluates to 10.

    bruce 에 값을 부여해서 bruce + 4 가 10을 계산할 수 있게 해보세요.

  7. Write a program (Python script) named madlib.py, which asks the user to enter a series of nouns, verbs, adjectives, adverbs, plural nouns, past tense verbs, etc., and then generates a paragraph which is syntactically correct but semantically ridiculous (see http://madlibs.org for examples).

    사용자에게 명사, 동사, 형용사, 부사, 복수형의 명사, 과거형 동사, 등등을 입력해서 말(구문상)은 맞지만 의미적으로 우수은 문단을 생성하는 madlib.py 라고 불려진 (파이썬 스크립트) 프로그램을 작성해보세요. (http://madlibs.org 에서 그 예를 보시기 바랍니다.)


탐색
1장 | 3장 | 차례
 
Copyright Notice
Copyright (C) Jeffrey Elkner, Allen B. Downey and Chris Meyers. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with Invariant Sections being Forward, Preface, and Contributor List, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled “GNU Free Documentation License”.
저작권 알림
저작권자 (C) 제프리 엘크너, 앨런 B. 다운웨이와 크리스 메이여스. GNU 자유 소프트웨어 제단이 발표한 GNU 자유 문서 라이선스 버전 1.3 또는 그 이후의 조건 하에 이 문서의 분배 또는/그리고 복사가 가능합니다; 변경불가 부분 : 추천사, 서문, 앞-표지문 없음, 뒷-표지문 없음. 이 라이선스의 사본은 "GNU 자유 문서 라이선스" 라는 항목으로 포함되어 있습니다.