2010. 2. 27. 01:20

파이썬으로 공부하는 과학자처럼 생각하기 2판 - 1장 프로그램의 길


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

1. The way of the program
1. 프로그램의 길

The goal of this book is to teach you to think like a computer scientist. This way of thinking combines some of the best features of mathematics, engineering, and natural science. Like mathematicians, computer scientists use formal languages to denote ideas (specifically computations). Like engineers, they design things, assembling components into systems and evaluating tradeoffs among alternatives. Like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions.

이 책의 목표는 당신이 컴퓨터 과학자처럼 생각하는 것을 가르쳐 주는것입니다. 이 생각하는 방법은 수학, 공학과 자연과학에서 볼수 있는 특징들을 합쳐놓은 것과 같습니다. 수학자 분들처럼 컴퓨터 과학자들은 생각 (특히 계산) 을 형식 언어를 써서 표현합니다. 공학자 분들처럼, 컴퓨터 과학자들은 무언가를 설계하고, 구성요소들을 결합해서 시스템으로 만들고, 대체할 수 있는 것들과 균형(손익계산, 장단점)을 계산하여 판단합니다. 과학자 분들처럼, 컴퓨터 과학자들은 복잡한 시스템의 움직임을 관찰하고, 가설을 세우며, 예측을 시험합니다.

The single most important skill for a computer scientist is problem solving. Problem solving means the ability to formulate problems, think creatively about solutions, and express a solution clearly and accurately. As it turns out, the process of learning to program is an excellent opportunity to practice problem-solving skills. That’s why this chapter is called, The way of the program.

컴퓨터 과학자에게 있어서 가장 중요한 단 한가지의 기술은 문제 해결입니다. 문제 해결은 문제를 표현하고, 창의적으로 해결책을 생각하며, 해답을 명확하고 정확하게 표현하는 것을 의미합니다. 곧 알려지겠지만, 프로그램을 배운다는 것은 문제-해결 기술을 연습하는 훌륭한 방법입니다. 이것이 이 단원이 프로그램의 방법이라 불릴수 있는 이유입니다.

On one level, you will be learning to program, a useful skill by itself. On another level, you will use programming as a means to an end. As we go along, that end will become clearer.

첫 단계에서, 당신은 그 자체만으로도 유용한 기술인 프로그램을 배울 것이며, 다른 단계에서는, 끝내기 위한 방법으로 프로그래밍을 배울것인데, 진행할수록, 그 끝이 점점 분명해질 것입니다. 

1.1. The Python programming language
1.1 파이썬 프로그래밍 언어

The programming language you will be learning is Python. Python is an example of a high-level language; other high-level languages you might have heard of are C++, PHP, and Java.

당신이 배우게될 프로그래밍 언어는 파이썬이 될 것입니다. 파이썬은 상위-수준 언어의 한 예입니다; 다른 상위-수준의 언어로는 아마 C++, PHP 와 자바를 들어보신 적이 있었을 겁니다.

As you might infer from the name high-level language, there are also low-level languages, sometimes referred to as machine languages or assembly languages. Loosely speaking, computers can only execute programs written in low-level languages. Thus, programs written in a high-level language have to be processed before they can run. This extra processing takes some time, which is a small disadvantage of high-level languages.

상위-언어라는 이름에서 추측하시겠지만, 하위-수준 언어라는 것도 있는데, 보통 기계어나 어셈블리 언어를 가리킵니다. 대략적으로 말하자면, 컴퓨터는 단지 하위-수준 언어로 작성된 프로그램만 실행할 수 있습니다. 따라서 상위-수준 언어로 작성된 프로그램들은 그들이 실행되기 위해 약간의 과정을 거쳐야 합니다. 이러한 추가적인 작업에 시간이 소요되는데, 이는 상위-수준 언어가 가지는 작은 단점이 되고 있습니다.

But the advantages are enormous. First, it is much easier to program in a high-level language. Programs written in a high-level language take less time to write, they are shorter and easier to read, and they are more likely to be correct. Second, high-level languages are portable, meaning that they can run on different kinds of computers with few or no modifications. Low-level programs can run on only one kind of computer and have to be rewritten to run on another.

하지만, 장점은 어마어마 합니다. 먼저, 상위-수준 언어로 작성된 프로그램은 훨씬 쉽습니다. 상위-수준 언어로 작성된 프로그램은 작성하는데 소요된 시간이 훨씬 적고, 읽기도 쉬워서 더 잘 수정되는 경향이 있습니다. 두번째로 상위-수준 언어는 이식성을 가지고 있습니다. 다시 말해, 별다른 수정 없이도 다른 종류의 컴퓨터들에서도 작동할 수 있다는 것을 의미합니다. 저급-수준 프로그램은 작성된 종류의 컴퓨터에서만 동작이 되며 다른 종류의 컴퓨터에서 작동되기 위해서는 다시 쓰여져야 할 필요가 있습니다.

Due to these advantages, almost all programs are written in high-level languages. Low-level languages are used only for a few specialized applications.

이러한 이익들 때문에, 대부분의 모든 프로그램들은 상위-수준 언어로 작성되며, 하위-수준 언어들은 몇몇 특성화된 응용프로그램을 위해서만 사용됩니다.

Two kinds of programs process high-level languages into low-level languages: interpreters and compilers. An interpreter reads a high-level program and executes it, meaning that it does what the program says. It processes the program a little at a time, alternately reading lines and performing computations.

상위-수준 언어를 하위-수준으로 변환하는데 두 종류의 프로그램 처리과정이 존재합니다: 인터프리터(해석기)와 컴파일러(편집자). 인터프리터는 상위-수준 프로그램을 읽고 실행합니다. 이는(인터프리터가) 프로그램에 쓰여져 있는 것대로 수행한다는 것을 의미합니다. 

A compiler reads the program and translates it completely before the program starts running. In this case, the high-level program is called the source code, and the translated program is called the object code or the executable. Once a program is compiled, you can execute it repeatedly without further translation.

컴파일러는 프로그램이 작동하기 전에 완전하게 읽어서 번역합니다. 이럴 경우 상위-수준 프로그램은 소스 코드(우너시 코드),라 하고 번역된 프로그램을 목적 코드(오브젝트 코드) 는 실행 파일(익스큐터블) 이라고 부릅니다.일단 프로그램이 컴파일이 되면, 사용자는 이후의 번역작업 없이도 이 번역된 것을 반복적으로 수행할 수 있습니다.

 

Many modern languages use both processes. They are first compiled into a lower level language, called byte code, and then interpreted by a program called a virtual machine. Python uses both processes, but because of the way programmers interact with it, it is usually considered an interpreted language.

많은 현대 언어들이 이 두가지 작업을 동시에 사용합니다. 그들은 일단 하위 수준 언어로 컴파일을 하는데, 이를 바이트 코드로 부르고, 그 이후에 프로그램에 의해 해석되는데 이를 가상 머신(버추얼 머신) 이라고 불립니다. 파이썬은 두가지 작업을 모두 사용하지만, 프로그래머들이 파이썬과의 접근하는 방식 때문에, 보통 인터프리터 언어라고 합니다.

There are two ways to use the Python interpreter: shell mode and script mode. In shell mode, you type Python statements into the Python shell and the interpreter immediately prints the result:

파이썬 인터프리터를 사용하는 방식에는 두가지가 있습니다: 쉘 방식(모드)과 스크립트 방식. 쉘 방식에서는, 파이썬 구문들이 파이썬 쉘이라는 곳을 거치면서 인터프리터가 즉각 그 결과를 출력합니다.

$ python
Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 1 + 1
2

The first line of this example is the command that starts the Python interpreter at a Unix command prompt. The next three lines are messages from the interpreter. The fourth line starts with >>>, which is the Python prompt. The interpreter uses the prompt to indicate that it is ready for instructions. We typed print 1 + 1, and the interpreter replied 2.


이 예제에서 첫 번째 줄이 의미하는 것은 이 파이썬 인터프리터가 유닉스 명령어 길잡이(커맨드 프롬프트)에서 수행되고 있다는 것을 나타냅니다. 다음 세문장은 인터프리터에서 전달하는 메시지 입니다. 네번째 줄에>>>> 이라는 글자로 시작하는데, 이것은 파이썬 길잡이(파이썬 프롬프트) 입니다. 인터프리터가 명령을 받을 준비가 되었다는 것을 타내며 이 프롬프트를 사용합니다. 우리는  print 1 + 1 을 입력했고, 인터프리터는 2 를 응답했습니다.

Alternatively, you can write a program in a file and use the interpreter to execute the contents of the file. Such a file is called a script. For example, we used a text editor to create a file named firstprogram.py with the following contents:

다른방법으로, 사용자는 프로그램을 파일로 작성하여 인터프리터를 그 파일의 내용을 실행하는데 사용할 수 있습니다.러한 파일을 스크립트라고 부릅니다. 예를 들면 문서 편집기를 사용해 다음의 내용을 입력한 뒤 firstprogram.py 이란 이름으로 저장하여 파일을 생성합니다.

print 1 + 1

By convention, files that contain Python programs have names that end with .py.

To execute the program, we have to tell the interpreter the name of the script:

편의상, 파이썬의 내용이 포함되어 있는 프로그램 이름의 끝에는 .py 가 있습니다. 프로그램을 실행하기 위해서는 인터프리터에게 그 스크립트의 이름만 가르쳐주면 됩니다.

$ python firstprogram.py2

These examples show Python being run from a Unix command line. In other development environments, the details of executing programs may differ. Also, most programs are more interesting than this one.

이러한 예제들은 파이썬이 유닉스 명령어 줄에서 실행되고 있음을 보여주고 있습니다. 다른 개발 환경에서는 프로그램을 수행하는 상세 내용이 다를 수 있습니다. 또한 대부분의 프로그램들이 이 예제보다 더 재미있습니다. (흥미로운 화면을 볼 것입니다.)

The examples in this book use both the Python interpreter and scripts. You will be able to tell which is intended since shell mode examples will always start with the Python prompt.

이 책에 있는 예제들은 파이썬 인터프리터와 스크립트 모두를 사용합니다. 사용자는 쉘 모드 예제들이 항상 파이썬 프롬프트를 통해 시작하기 때문에, 요구하는 실행방식이 무엇인지 말할 수 있을 것입니다.

Working in shell mode is convenient for testing short bits of code because you get immediate feedback. Think of it as scratch paper used to help you work out problems. Anything longer than a few lines should be put into a script.

작은 양의 코드를 실험하는데 쉘 모드로 작업하는 것이 즉각적인 반응을 얻을 수 있어서 편리할 것입니다. 문제 푸는데 도움이 되게 막쓰는 종이에다가 쓰는 것을 생각해보세요. 어떤거라도 몇 줄 이상 길어지면, 스크립트로 만들어야 합니다. 

1.2. What is a program?
1.2. 프로그램은 무엇입니까?

A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of equations or finding the roots of a polynomial, but it can also be a symbolic computation, such as searching and replacing text in a document or (strangely enough) compiling a program.

프로그램은 어떻게 계산을 수행하는지 명시한 명령문들의 순서입니다. 계산은 수학처럼 식의 체계를 푼다거나 다항식의 근(답)을 찾는 것이 될수도 있지만, 문서내에 있는 글자들을 찾고 바꾸는 거나 (이상하게 들리시겠지만) 프로그램 컴파일하는 것과 같은 기호 연산이 될 수도 있습니다.

The details look different in different languages, but a few basic instructions appear in just about every language:

언어들 마다 상세한 사항들이 다르겠지만, 모든 언어들마다 기본적인 명령어들이 어느정도 존재합니다.

input
입력
Get data from the keyboard, a file, or some other device.
키보드, 파일 또는 다른 기기들로 자료를 받는 행위
output
출력
Display data on the screen or send data to a file or other device.
화면, 파일 또는 다른 기기로 자료를 표시하는 행위
math
수학
Perform basic mathematical operations like addition and multiplication.
덧셈과 곱셈과 같은 기본적인 수학적 연산을 수행
conditional execution
조건문 수행
Check for certain conditions and execute the appropriate sequence of statements.
특정 조건을 검사하고, 적절한 명령문들의 순서를 수행
repetition
반복
Perform some action repeatedly, usually with some variation.
몇가지 행동들을 약간의 변형을 가하여 반복적으로 수행

Believe it or not, that’s pretty much all there is to it. Every program you’ve ever used, no matter how complicated, is made up of instructions that look more or less like these. Thus, we can describe programming as the process of breaking a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of these basic instructions.

믿으시던지 안 믿으시던지 상관없습니다만, 위에 언급된 것들이 거의 다입니다. 사용자가 사용하는 모든 프로그램들이 얼마나 어렵던 그와 상관없이 저런 비슷한 명령문들을 더 또는 덜 사용해서 만들어집니다. 따라서, 우리는 프로그래밍을 거대한 부분을 나누고, 복잡한 작업을 작고 작은 소작업으로 나눠 위에 언급된 기본적인 명령문들만으로 수행될 만큼 충분하게 나누는 과정으로 설명할 수 있습니다.

That may be a little vague, but we will come back to this topic later when we talk about algorithms.
위 말이 약간 막연해 보일수 있지만, 나중에 알고리즘을 설명할 때 이 주제를 다시 다루도록 하겠습니다.

1.3. What is debugging?
1.3 디버깅은 무엇인가요?

Programming is a complex process, and because it is done by human beings, it often leads to errors. For whimsical reasons, programming errors are called bugs and the process of tracking them down and correcting them is called debugging.

프로그래밍은 복잡한 과정이고, 사람에 의해서 만들어지기 때문에, 종종 오류를 일으킵니다. 재미있는 이유가 있어서, 프로그래밍 오류를 버그(벌레)라 부르고, 그들을 추적해서 교정하는 과정을 디버깅(벌레잡기)라 부릅니다.

Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors. It is useful to distinguish between them in order to track them down more quickly.

프로그램에 발생할수 있는 오류들이 3종류가 있습니다.: 문법 오류(신텍스 에러), 런타임 오류(런타임-실행중 에러), 논리 오류(시멘틱 에러). 이들 오류를 빠르게 추적하기 위해서는 이들을 구분하는 것이 유용합니다.

1.4. Syntax errors
1.4. 문법 오류

Python can only execute a program if the program is syntactically correct; otherwise, the process fails and returns an error message. syntax refers to the structure of a program and the rules about that structure. For example, in English, a sentence must begin with a capital letter and end with a period. this sentence contains a syntax error. So does this one

파이썬은 프로그램이 구문상 맞을때에만 프로그램이 실행 합니다; 그렇지 않으면, 실행하는 그 과정은 실패하고, 오류 메시지를 돌려줍니다. 문법(신텍스) 은 프로그램 구조와 구조에 관한 규칙들을 참조합니다. 예를 들어, 영어에서 문장은 대문자 글자로 시작하고 점(.) 으로 끝나야 합니다. ㅇㅣ 문장은 문법 오류를 가지고 있습니다(원문을 보시면 첫자가 소문자여서 문법오류라 칭하고 있습니다.). 파이썬도 마찬가지입니다.

For most readers, a few syntax errors are not a significant problem, which is why we can read the poetry of e. e. cummings without spewing error messages. Python is not so forgiving. If there is a single syntax error anywhere in your program, Python will print an error message and quit, and you will not be able to run your program. During the first few weeks of your programming career, you will probably spend a lot of time tracking down syntax errors. As you gain experience, though, you will make fewer errors and find them faster.

대부분의 독자들은 약간의 문법 오류는 우리가 e.e 커밍스의 시를 읽고 오류가 있다고 말하지 않는 이유처럼, 큰 문제가 아니라고 생각합니다. (하지만) 파이썬은 그다지 관대하지 않습니다. 만약에 사용자가 만든 프로그램 그 어딘가에 하나라도 문법 오류가 있다면, 파이썬은 오류 메시지를 출력하고 중단하게 되므로, 사용자는 자신의 프로그램을 실행할 수 없게 될 것입니다. 당신의 프로그래밍 경력의 첫 몇주 동안은, 아마 문법 오류를 쫓아 다닌다고 시간을 많이 소비할 것입니다. 여전히 문법 오류가 있겠지만, 경험이 늘수록, 오류를 더 적게 내고 더 빨리 찾을 것입니다.

1.5. Runtime errors
1.5. 런타임 오류

The second type of error is a runtime error, so called because the error does not appear until you run the program. These errors are also called exceptions because they usually indicate that something exceptional (and bad) has happened.

두번째 오류의 종류로 런타임(실행중) 오류가 있는데, 이렇게 불리는 이유는 프로그램을 실행하기 전까지는 안 나타난다는데 있습니다. 이들 오류들을 예외라고 불리는데, 이는 보통 예외적으로 (그리고 안좋게) 뭔가가 나타났기 때문입니다.

Runtime errors are rare in the simple programs you will see in the first few chapters, so it might be a while before you encounter one.

런타임 오류들은 앞으로 볼 처음 몇단원들에 있는 간단한 프로그램들에는 보기 드물어서, 이 오류를 마추치는데는 시간이 좀 걸릴지도 모릅니다.

1.6. Semantic errors
1.6. 논리 오류

The third type of error is the semantic error. If there is a semantic error in your program, it will run successfully, in the sense that the computer will not generate any error messages, but it will not do the right thing. It will do something else. Specifically, it will do what you told it to do.

세번째 오류 종류는 논리 오류입니다. 만약 프로그램 상에 논리 오류가 존재한다면, 프로그램은 성공적으로 실행은 됩니다. 그 말은 컴퓨터는 어떠한 오류 메시지를 만들지 않는다는 것을 의미합니다. 하지만, 이 프로그램은 올바르게 작동하지 않습니다. 당신이 그렇게 하라고 시켰던 거와는 뭔가 다르게 움직일 것입니다.

The problem is that the program you wrote is not the program you wanted to write. The meaning of the program (its semantics) is wrong. Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing.

이 문제는 사용자가 작성한 프로그램이 사용자가 원한것을 쓰지 않기 때문에 발생합니다. 프로그램의 의미 (그 논리들) 가 잘못 되었습니다. 논리 오류를 구분하는 것은 프로그램의 출력하는 것을 보면서 작업을 반대 방향으로 진행하고, 이 출력값이 무엇을 시도한 결과로 나온건지 파악해야 하므로 어려울 수 있습니다.

1.7. Experimental debugging
1.7. 실험적 디버깅

One of the most important skills you will acquire is debugging. Although it can be frustrating, debugging is one of the most intellectually rich, challenging, and interesting parts of programming.

사용자가 획득해야 하는 가장 중요한 기술들 중에 하나는 디버깅입니다. 약간 불만이거나 좌절이될 수 있지만, 디버깅은 프로그래밍에서 가장 지적으로 풍부하고 도전적이며 흥미로운 부분에 속합니다.

In some ways, debugging is like detective work. You are confronted with clues, and you have to infer the processes and events that led to the results you see.

몇가지 방법들에서, 디버깅은 탐정 놀이와 비슷합니다. 사용자는 단서들을 접하고, 그 과정과 앞으로 일어날 결과를 이끄는 사건(이벤트)들을 추측해야합니다.

Debugging is also like an experimental science. Once you have an idea what is going wrong, you modify your program and try again. If your hypothesis was correct, then you can predict the result of the modification, and you take a step closer to a working program. If your hypothesis was wrong, you have to come up with a new one. As Sherlock Holmes pointed out, When you have eliminated the impossible, whatever remains, however improbable, must be the truth. (A. Conan Doyle, The Sign of Four)

디버깅은 또한 실험적 과학과 비슷합니다. 뭐가 잘못되어 가는지 알수 있다면, 사용자는 프로그램을 수정하여 다시 시도합니다. 만약에 사용자가 세운 가정이 맞다면, 그러면 그 변경의 결과를 예측 할 수 있으며, 제대로 작동이 되는 프로그램으로 한걸음 더 나아갈 수 있습니다. 만약 가정이 틀리다면, 새로운 가정을 들어 다시 다가가야 합니다. 셜록 홈즈가 지적했듯이, 당신이 만약 불가능을 제가 했을때, 뭐가 남던, 얼마나 말이 안되던 간에 진실만이 남게 될것입니다. (A. 코난 도일, 네개의 서명)

For some people, programming and debugging are the same thing. That is, programming is the process of gradually debugging a program until it does what you want. The idea is that you should start with a program that does something and make small modifications, debugging them as you go, so that you always have a working program.

몇몇 어느 분들에게는 프로그래밍과 디버깅이 똑같습니다. 그 말은, 프로그래밍은 점차적으로 원하는 데로 프로그래밍이 움직일때 까지 디버깅하는 과정이라는 뜻입니다. 이 생각은 당신이 뭔가하는 프로그램을 시작으로 작은 변경들을 거치면서 진행함에 따라 항상 제대로 작동되는 프로그램을 만들기 위해서 디버깅을 해야 합니다.

For example, Linux is an operating system kernel that contains millions of lines of code, but it started out as a simple program Linus Torvalds used to explore the Intel 80386 chip. According to Larry Greenfield, one of Linus’s earlier projects was a program that would switch between printing AAAA and BBBB. This later evolved to Linux (The Linux Users’ Guide Beta Version 1).

예를 들면, 리눅스는 수백만 줄의 코드를 포함하고 있는 운영 시스템 커널입니다. 하지만, 시작은 리누스 토발즈라는 분이 80386 칩을 탐험하는데 사용했던 단순한 프로그램으로 출발했습니다. 레리 그린필드의 말에 따르면, 리누스의 초기 프로젝트들 중에 하나는 AAAA 와 BBBB 를 바꿔가며 출력하는 프로그램이였다고 했습니다. 이것이 이후 발전하면서 리눅스로 진화했습니다. (리눅스 사용자의 가이드 베타 버전 1)

Later chapters will make more suggestions about debugging and other programming practices.

이후 단원들에서는 디버깅과 다른 프로그램 작업들에 대한 제안들을 하겠습니다.

1.8. Formal and natural languages
1.8. 형식 언어와 자연 언어

Natural languages are the languages that people speak, such as English, Spanish, and French. They were not designed by people (although people try to impose some order on them); they evolved naturally.

자연 언어는 사람들이 말하는 영어와 스페인어, 프랑스어 (, 그리고 한국어) 와 같은 언어들을 말합니다. 그들 언어는 (비록 그 순서를 조금 바꿀려는 시도는 있지만) 사람들에 의해 설계되지 않았습니다; 그들은 자연스럽게 진화합니다.

Formal languages are languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Chemists use a formal language to represent the chemical structure of molecules. And most importantly:

형식 언어는 특정 응용분야(어플리케이션)에 맞게 사람에 의해 설계된 언어를 말합니다. 예를 들어, 수학자들이 쓰는 표기법은 숫자와 기호들 간의 관계를 의미하는데 특별하게 유용한 형식언어를 사용합니다.

Programming languages are formal languages that have been designed to express computations.

프로그램 언어들은 계산을 표현하는 목적으로 만들어진 형식 언어입니다.

Formal languages tend to have strict rules about syntax. For example, 3+3=6 is a syntactically correct mathematical statement, but 3=+6$ is not. H2O is a syntactically correct chemical name, but 2Zz is not.

형식 언어는 문법에 관해 엄격한 규칙이 있는 편입니다. 예를 들어 3+3=6 은 구문상으로 맞는 수학적 구문이나, 3=+6$ 은 그렇지 않습니다. H2O 는 구문상으로 맞는 화학식이나 2Zz 은 그러하지 않습니다.

Syntax rules come in two flavors, pertaining to tokens and structure. Tokens are the basic elements of the language, such as words, numbers, and chemical elements. One of the problems with 3=+6$ is that $ is not a legal token in mathematics (at least as far as we know). Similarly, 2Zz is not legal because there is no element with the abbreviation Zz.

문법 규칙들은 토큰(token)과 구조라는 두가지 특징이 딸려 나옵니다. 토큰은 단어, 숫자나 화학식과 같이, 언어의 기본적 요소입니다. 3=+6$ 에서 볼수 있는 문제점들중 하나로 $ 는 (적어도 우리가 아는 한에서는) 이 수식에서 볼수 있는 수학에 적합하지 않는 토큰입니다. 비슷하게 2Zz 도 Zz 의 약어와 관련된 어떠한 원소가 존재하지 않으므로 규칙에 어긋납니다.

The second type of syntax rule pertains to the structure of a statement— that is, the way the tokens are arranged. The statement 3=+6$ is structurally illegal because you can’t place a plus sign immediately after an equal sign. Similarly, molecular formulas have to have subscripts after the element name, not before.

두번째 문법 규칙은 구문의 구조입니다. 이는 토큰들이 배열되는 방법을 말합니다. 3=+6$ 는 구조적으로 더하기 기호 바로 뒤에 등호가 올수 없다는 이유로 맞지 않습니다. 비슷하게 분자 수식도 원자 이름 이후에 아랫첨자 값이 와야 하지 전에 있어서는 안됩니다.

When you read a sentence in English or a statement in a formal language, you have to figure out what the structure of the sentence is (although in a natural language you do this subconsciously). This process is called parsing.

영어 문장 또는 형식 언어에 있는 구문들을 읽게 될때, (자연 언어는 무의식적으로 구조를 이해하게 되지만) 당신은 문장의 구조가 무엇인지 알아야 할 필요가 있습니다. 이러한 과정을 파싱(어구 해부)이라고 부릅니다.

For example, when you hear the sentence, The other shoe fell, you understand that the other shoe is the subject and fell is the verb. Once you have parsed a sentence, you can figure out what it means, or the semantics of the sentence. Assuming that you know what a shoe is and what it means to fall, you will understand the general implication of this sentence.

예를 들어 당신이 '다른 신발 한 짝이 떨어집니다.' 라는 문장을 들었을때, '다른 신발'이 주어이고, '떨어진다'는 말은 동사로 이해합니다. 만약에 당신이 문장을 분석한다면, 그것이 무엇을 의미하는지, 또는 문장의 의미가 무엇인지 이해할 수 있습니다. 만약 당신이 신발이 무엇이고, 떨어진다는 의미가 무엇인지 알고 있다면, 당신은 이 문장의 일반적인 함축적(말하지 않아도 알수 있는) 의미를 이해할 것입니다.

Although formal and natural languages have many features in common — tokens, structure, syntax, and semantics — there are many differences:

- 토큰, 구조, 문법, 의미 - 에서 형식, 자연 언어들 둘다 공통적으로 가지는 특징들이 많지만  이들은 많은 차이점들을 가지고 있습니다.

ambiguity
모호성(여러가지 뜻을 가지는 성질)
Natural languages are full of ambiguity, which people deal with by using contextual clues and other information. Formal languages are designed to be nearly or completely unambiguous, which means that any statement has exactly one meaning, regardless of context.

자연 언어는 전후 문맥상의 단서나 다른 정보들을 사용하여 사람들이 사용하는데, 모호함으로 가득차여 있습니다. 형식 언어는 거의 또는 완전히 명확하여 문맥과 관계 없이 어느 구문이던지 정확히 하나만을 의미합니다.
redundancy
잉여성(쓸데없는 표현)
In order to make up for ambiguity and reduce misunderstandings, natural languages employ lots of redundancy. As a result, they are often verbose. Formal languages are less redundant and more concise.

모호성이나 오해의 소지를 줄이기 위해서는, 자연 언어는 다수의 잉여성을 가지고 있습니다. 그 결과, 그 언어는 종종 (수다를 떠는 듯) 장황해 집니다. 형식 언어는 덜 잉여스럽고 더 정확합니다.
literalness
글자대로
Natural languages are full of idiom and metaphor. If someone says, The other shoe fell, there is probably no shoe and nothing falling. Formal languages mean exactly what they say.

자연 언어는 관용구와 은유로 가득차 있습니다. 누군가 말하기를 '다른 신발이 떨어진다면, 거긴 아마도 신발이 없고 더 떨어뜨릴게 없다.' 형식 언어는 말하는 것을 정확하게 의미하고 있습니다.

People who grow up speaking a natural language—everyone—often have a hard time adjusting to formal languages. In some ways, the difference between formal and natural language is like the difference between poetry and prose, but more so:

자연 언어를 말하면서 성장한 사람들 - 모두 - 은 형식 언어로 맞추면서 어려운 시간을 보냅니다. 몇가지 방법들에서, 형식 언어와 자연언어들 사이의 차이는 시(운문)와 글(산문)의 차이와 비슷하지만, 실제로는 더 합니다.

Poetry
(운문)
Words are used for their sounds as well as for their meaning, and the whole poem together creates an effect or emotional response. Ambiguity is not only common but often deliberate.

단어들은 음과 의미를 나타내는데 사용되고, 전체의 시는 모여서 효과나 감정적 응답을 만들어냅니다. 모호성은 일상적일뿐만 아니라 의도적으로도 나타납니다.
Prose
(산문)

The literal meaning of words is more important, and the structure contributes more meaning. Prose is more amenable to analysis than poetry but still often ambiguous.

단어들의 문자적 의미들이 더 중요하고, 글의 구조도 또한 더욱 의미가 있습니다. 글은 시보다 더 분석할 수 있으나, 여전히 모호한 부분이 있습니다.
Programs
프로그램

The meaning of a computer program is unambiguous and literal, and can be understood entirely by analysis of the tokens and structure.

컴퓨터 프로그램의 의미는 모호하지 않으면서도 문자적이고, 토큰과 구조로 되어 있어 전체적으로 이해될 수 있습니다.

Here are some suggestions for reading programs (and other formal languages). First, remember that formal languages are much more dense than natural languages, so it takes longer to read them. Also, the structure is very important, so it is usually not a good idea to read from top to bottom, left to right. Instead, learn to parse the program in your head, identifying the tokens and interpreting the structure. Finally, the details matter. Little things like spelling errors and bad punctuation, which you can get away with in natural languages, can make a big difference in a formal language.

프로그램 (그리고 다른 형식 언어)을 읽는데 도움이 되는 제안을 하겠습니다. 첫째로, 형식 언어는 자연 언어보다 더욱 더 복잡하므로, 읽는데 더욱 시간을 들이셔야합니다. 또한 구조도 중요해서, 위에서 아래로, 혹은 왼쪽에서 오른쪽으로 읽는 방법은 보통 좋지 않은 방법입니다. 대신에 프로그램 전체를 머릿 속에서 이해할 수 있는 능력을 키우는데, 토큰들을 구분하고 구조를 해석하는 방법으로 진행합니다. 마지막으로, 상세 사항들이 중요합니다. 글자 오류 또는 나쁜 구두점(, .)들은 자연 언어에서는 쉽게 무시할 수 있지만, 형식 언어에는 상당히 중요한 차이를 만들어 낼수 있습니다.

1.9. The first program
1.9. 첫 프로그램

Traditionally, the first program written in a new language is called Hello, World! because all it does is display the words, Hello, World! In Python, it looks like this:

전통적으로 새로운 언어로 처음 만드는 프로그램을 'Hello, World!' 라고 부릅니다. 그 이유는 프로그램이 하는 행동이 'Hello World!' 라고 출력하는게 전부이기 때문입니다. 파이썬에서는 프로그램이 다음과 같습니다:

print "Hello, World!"

This is an example of a print statement, which doesn’t actually print anything on paper. It displays a value on the screen. In this case, the result is the words

이 예제는 print 구문 으로 실제로는 종이 위에는 어떤것도 출력하지 않습니다. 값을 화면에 출력합니다. 이 경우 결과값은 다음의 단어들입니다.

Hello, World!

The quotation marks in the program mark the beginning and end of the value; they don’t appear in the result.

따옴표(") 는 값의 시작과 끝을 표시합니다; 그들은 결과에 표시되지 않습니다.

Some people judge the quality of a programming language by the simplicity of the Hello, World! program. By this standard, Python does about as well as possible.

몇몇 사람들은 프로그램의 성능이 "Hello, World!" 를 출력하는 단순함에 따라 결정된다고 판단합니다. 이러한 표준에 따르면, 파이썬은 그러한 품질 기준에 잘 따르고 있습니다.

1.10. Glossary
1.10. 용어설명

algorithm
알고리즘
A general process for solving a category of problems.
특정 문제들의 부류를 해결하는 일반적인 처리과정
bug
버그
An error in a program.
프로그램 안에 존재하는 오류
byte code
바이트 코드
An intermediate language between source code and object code. Many modern languages first compile source code into byte code and then interpret the byte code with a program called a virtual machine.
소스 코드와 목적 코드 중간에 생성되는 언어. 많은 현대 언어들이 우선 소스 코드를 바이트코드로 변환하고 바이트 코드를 해석하는데 가상 머신이라고 불리는 프로그램이 그 해석을 수행합니다.
compile
컴파일
To translate a program written in a high-level language into a low-level language all at once, in preparation for later execution.
나중의 수행을 위해, 상위-수준 언어를 하위-수준 언어로 한번에 번역하는 프로그램
debugging
디버깅
The process of finding and removing any of the three kinds of programming errors.
3종류의 프로그래밍 오류를 찾고 제거하는 과정
exception
예외
Another name for a runtime error.
런타임 오류의 또다른 이름
executable
실행 파일
Another name for object code that is ready to be executed.
실행될 준비가 되어 있는 목적 코드를 부르는 다른 이름
formal language
형식 언어
Any one of the languages that people have designed for specific purposes, such as representing mathematical ideas or computer programs; all programming languages are formal languages.
수학적 생각이나 컴퓨터 프로그래밍과 같은 특정 목적을 위해 사람들이 만든 언어들 중에 하나; 모든 프로그래밍 언어는 형식 언어입니다.
high-level language
상위-수준 언어
A programming language like Python that is designed to be easy for humans to read and write.
파이썬과 같이 사람이 읽고 쓰기 쉽게 만들어진 프로그래밍 언어
interpret
해석(인터프리트)
To execute a program in a high-level language by translating it one line at a time.
한번에 한줄씩 상위-언어 프로그램을 번역하여 실행하는 프로그램
low-level language
하위-수준 언어
A programming language that is designed to be easy for a computer to execute; also called machine language or assembly language.
컴퓨터가 실행하기 쉽게 설계된 언어; 또한 기계어나 어셈블리 언어로 불립니다.
natural language
자연어
Any one of the languages that people speak that evolved naturally.
사람들이 자연스롭게 말하기 쉽게 변화된 언어들 중에 하나
object code
목적 코드
The output of the compiler after it translates the program.
컴파일러가 프로그램을 해석한 이후에 나온 출력물
parse
파스(구문 해석)
To examine a program and analyze the syntactic structure.
프로그램을 해석하고, 의미적 구조를 분석하기 위해 수행
portability
이식성
A property of a program that can run on more than one kind of computer.
두 종류 이상의 컴퓨터에서 동작할 수 있는 프로그램의 특성
print statement
print 구문
An instruction that causes the Python interpreter to display a value on the screen.
파이썬 인터프리터에게 화면에 값을 출력하게 만드는 명령어
problem solving
문제 해결
The process of formulating a problem, finding a solution, and expressing the solution.
문제를 수식화하고, 해답을 찾으며, 그 해답을 표현하는 과정
program
프로그램
a sequence of instructions that specifies to a computer actions and computations to be performed.
수행할 컴퓨터 활동과 계산을 명시하는 일련의 명령어들
Python shell
파이썬 쉘
An interactive user interface to the Python interpreter. The user of a Python shell types commands at the prompt (>>>), and presses the return key to send these commands immediately to the interpreter for processing.
파이썬 인터프리터에 대한 대화형 사용자 인터페이스(접속기). 파이썬 쉘의 사용자는 프롬프트(>>>) 상에서 명령어들을 입력하고, 리턴(엔터)키를 눌러 즉각 이러한 명령어들이 인터프리터에게 보낼 수 있습니다.
runtime error
런타임 오류
An error that does not occur until the program has started to execute but that prevents the program from continuing.
프로그램이 실행하기 전까지는 발생하지 않지만, 프로그램의 진행을 막는 오류
script
스크립트
A program stored in a file (usually one that will be interpreted).
파일에 저장되어 있는 프로그램 (보통 해석이 될 프로그램이 저장)
semantic error
의미상 오류
An error in a program that makes it do something other than what the programmer intended.
프로그램이 프로그래머가 의도하지 않은 다른 것을 생성하는 오류
semantics
의미
The meaning of a program.
프로그램의 의미
source code
소스 코드
A program in a high-level language before being compiled.
컴파일 되기 전의 상위-수준 언어로 된 프로그램
syntax
문법
The structure of a program.
프로그램의 구조
syntax error
문법 오류
An error in a program that makes it impossible to parse — and therefore impossible to interpret.
프로그램에 존재하는 인식이 불가능하게 만드는 오류 - 그러므로 해석이 불가능합니다.
token
토큰
One of the basic elements of the syntactic structure of a program, analogous to a word in a natural language.
프로그램의 의미적 구조상에 있는 가장 기본적인 요소들 중에 하나, 자연 언어에서 단어 하나와 동일한 의미

1.11. Exercises
1.11. 연습문제

  1. Write an English sentence with understandable semantics but incorrect syntax. Write another sentence which has correct syntax but has semantic errors.

    의미상으로는 이해가 되지만, 문법상에는 맞지 않는 영어 문장을 만들어보세요. 그리고 문법은 맞지만, 의미상으로 오류가 있는 문장을 써보세요.

  2. Start a Python shell. Type 1 + 2 and then hit return. Python evaluates this expression, prints the result, and then prints another prompt. * is the multiplication operator, and ** is the exponentiation operator. Experiment by entering different expressions and recording what is printed by the Python interpreter. What happens if you use the / operator? Are the results what you expect? Explain.

    파이썬 쉘을 실행하세요. 1+2 를 입력하고 엔터를 쳐봅니다. 파이썬은 이러한 표현을 계산할 껀데, 결과값을 출력합니다. 그리고 다른 프롬프트 상에서 (+ 연산자 대신에) 곱셈 연산자 * 와  , ** 지수승 연산자를 이용해서 다시 한번 출력해보세요. 다른 표현식들을 입력하는 실험을 통해, 파이썬 인터프리터가 출력하는 다른 결과물들을 기록합니다. 무슨 결과가 예상되십니까? 설명해보세요.


  3. Type 1 2 and then hit return. Python tries to evaluate the expression, but it can’t because the expression is not syntactically legal. Instead, it prints the error message:

    1 2 를 입력하고 엔터키를 쳐봅니다. 파이썬은 그 표현식을 계산할려고 하지만, 문법적으로 맞지 않기 때문에 다음과 같은 오류 메시지를 출력합니다:

      File "<stdin>", line 1    1 2      ^SyntaxError: invalid syntax

    In many cases, Python indicates where the syntax error occurred, but it is not always right, and it doesn’t give you much information about what is wrong.

    대부분의 경우, 파이썬은 문법 오류가 있는 곳을 가리키지만, 항상 맞지만은 않습니다. 그래서 뭐가 잘못되었는지 관해 사용자는 많은 정보를 받지 못합니다.

    So, for the most part, the burden is on you to learn the syntax rules.

    그래서, 대부분의 경우 문법적 규칙을 배우는 여러분들의 능력에 따라 그 부담이 결정 됩니다.

    In this case, Python is complaining because there is no operator between the numbers.

    이 경우, 파이썬은 숫자들 사이에 연산자가 없다고 파이썬이 불평하네요.

    Write down three more examples of strings that will produce error messages when you enter them at the Python prompt. Explain why each example is not valid Python syntax.

    파이썬 프롬프트에 입력할 때 발생되는 오류들 3가지를 더 써보시고, 파이썬 문법에 왜 안 맞는지 설명해보세요.

  4. Type print ‘hello’. Python executes this statement, which has the effect of printing the letters h-e-l-l-o. Notice that the quotation marks that you used to enclose the string are not part of the output. Now type "hello" and describe and explain your result.

    print 'hello' 를 입력하면. 파이썬은 이 구문을 실행하는데, 이는 h-e-l-l-o 라는 문자를 출력하는 효과를 가지고 있습니다. 구문들을 묶는데 사용되는 따옴표(")는  출력의 일부가 아님을 주목하세요. 이제 "hello" 라고 쳐보고, 그 결과에 대해 설명해 보세요. 

  5. Type print cheese without the quotation marks. The output will look something like this:

    따옴표 없이 print cheese 라고 입력합니다. 출력값은 다음과 같이 나타날 것입니다:

    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    NameError: name 'cheese' is not defined

    This is a run-time error; specifically, it is a NameError, and even more specifically, it is an error because the name cheese is not defined. If you don’t know what that means yet, you will soon.

    이는 런-타임 오류입니다; 더 나가서 설명하자면 NameError 인데, 이는 cheese 라는 이름이 따로 명시되지 않아서 발생하는 오류입니다. 지금 그 의미를 모르겠다면, 나중에 알게 될 것입니다. 


  6. Type 'This is a test...' at the Python prompt and hit enter. Record what happens.

    'This is a test...' 라고 파이썬 프롬프트에 입력하고 엔터키를 칩니다. 그 결과를 기록하세요. 

    Now create a python script named test1.py with the following contents (be sure to save it before you try to run it):

    이제 파이썬 스크립트를 만들어 test1.py저장하는데 다음의 내용을 넣습니다. (실행하기 전에 저장하는 것을 잊지 마시기 바랍니다.)

    'This is a test...'

    What happens when you run this script? Now change the contents to:

    이 스크립트를 실행했을때 무슨 오류가 발생할까요? 이제 파일 안의 내용을 다음과 같이 바꿉니다.

    print 'This is a test...'

    and run it again.

    그리고 다시 실행해 보세요.

    What happened this time?

    이번에는 무슨일이 일어났습니까?

    Whenever an expression is typed at the Python prompt, it is evaluated and the result is printed on the line below. 'This is a test...' is an expression, which evaluates to 'This is a test...' (just like the expression 42 evaluates to 42). In a script, however, evaluations of expressions are not sent to the program output, so it is necessary to explicitly print it.

    표현식이 파이썬 프롬프트에 입력될 때 마다, 그 식은 계산되고, 그 줄 다음에 출력됩니다. 'This is a test...' 는 하나의 표현식입니다. (42 표현식이 42로 계산되는 거와 같습니다.) 이  스크립트에서는 표현식의 계산이 프로그램의 출력되기 전에 전달이 되지 않습니다. 그렇기에 이를 명식적으로 출력할 필요가 있습니다.


탐색
 
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 자유 문서 라이선스" 라는 항목으로 포함되어 있습니다.