A Byte of Python - Basics Python


Basics


hello world 만으로는 부족할 것이다. 더 많은 것을 배워보자. 입력을 받고 처리하고 출력을 해보자. 이 것은 상수와 변수를 사용해 처리한다. 이 챕터에서는 추가적인 개념도 알아본다.

주석

주석은 #뒤의 모든 텍스트를 의미한다. 프로그램 가독성을 위해 유용하다
예를 들어,
print('hello world') # Note that print is a function

또는
# Note that print is a functionprint('hello world')

Use as many useful comments as you can in your program to:

  • explain assumptions
  • explain important decisions
  • explain important details
  • explain problems you're trying to solve
  • explain problems you're trying to overcome in your program, etc.

Code tells you how, comments should tell you why.

This is useful for readers of your program so that they can easily understand what the program is doing. Remember, that person can be yourself after six months!

리터럴 상수

An example of a literal constant is a number like 51.23, or a string like 'This is a string' or "It's a string!".

It is called a literal because it is literal - you use its value literally. The number 2 always represents itself and nothing else - it is a constant because its value cannot be changed. Hence, all these are referred to as literal constants.


숫자값

Numbers are mainly of two types - integers and floats.

An example of an integer is 2 which is just a whole number.

Examples of floating point numbers (or floats for short) are 3.23 and 52.3E-4. The E notation indicates powers of 10. In this case, 52.3E-4 means 52.3 * 10^-4^.

Note for Experienced Programmers

There is no separate long type. The int type can be an integer of any size.


문자열

A string is a sequence of characters. Strings are basically just a bunch of words.

You will be using strings in almost every Python program that you write, so pay attention to the following part.

싱글 쿼트
싱글 쿼트를 사용해 문자열을 지정할 수 있다. 'Quote me on this'

All white space i.e. spaces and tabs, within the quotes, are preserved as-is.


더블 쿼트

Strings in double quotes work exactly the same way as strings in single quotes. An example is "What's your name?".


트리플 쿼트

You can specify multi-line strings using triple quotes - (""" or '''). You can use single quotes and double quotes freely within the triple quotes. An example is:

'''This is a multi-line string. This is the first line.This is the second line."What's your name?," I asked.He said "Bond, James Bond."'''
문자열은 이뮤터블

한번 문자열로 생성하면 변경할 수 없다. 안좋은 것이라 생각할 수도 있지만 실제로는 그렇지 않다. 다양한 프로그램에서 이 것이 왜 제약이 아닌지 살펴볼 것이다.

C/C++프로그래머를 위한 일러두기
파이썬에서는 구별된 char 형식이 없다. 실제적으로 필요치 않기때문이다.

Perl/PHP프로그래머를 위한 일러두기
싱글 쿼트, 더블 쿼트 간의 차이가 없음을 기억하자.

포맷 메소드

간혹 다른 정보로 부터 문자열을 만들어야 할 때가 있다. 이럴때 format() 메소드가 유용하다.
다음 라인을 str_format.py로 저장하자

age = 28
name = "Swaroop"
print("{0} as {1} years old when he wrote this book".format(name, age))
print("Why is {0} playing with that python?".format(name))

Output:

$ python str_format.pySwaroop was 20 years old when he wrote this bookWhy is Swaroop playing with that python?

이 것이 어떻게 작동하는가

문자열은 특정 사양으로 사용될 수 있는데 format 메소드는 이들 사양을 연관된 매개변수로 치환한다.

{0}이 사용되는 곳에는 name 이 쓰였으며 {1} 이 사용되는 곳엔 age가 사용되었다. 파이썬은 0부터 시작한다.

Notice that we could have achieved the same using string concatenation:

name + ' is ' + str(age) + ' years old'

but that is much uglier and error-prone. Second, the conversion to string would be done automatically by the format method instead of the explicit conversion to strings needed in this case. Third, when using the format method, we can change the message without having to deal with the variables used and vice-versa.


숫자는 선택적으로 다음과 같이 쓸 수 있다.
age = 20name = 'Swaroop'print('{} was {} years old when he wrote this book'.format(name, age))print('Why is {} playing with that python?'.format(name))

which will give the same exact output as the previous program.

파라미터 이름을 쓸 수도 있다.

age = 20name = 'Swaroop'print('{name} was {age} years old when he wrote this book'.format(name=name, age=age))print('Why is {name} playing with that python?'.format(name=name))

which will give the same exact output as the previous program.


파이썬 3.6에서는 더 단순한 방법으로 "f-strings"를 지원한다.

Python 3.6 introduced a shorter way to do named parameters, called "f-strings":

age = 20name = 'Swaroop'print(f'{name} was {age} years old when he wrote this book')  # notice the 'f' before the stringprint(f'Why is {name} playing with that python?')  # notice the 'f' before the string

which will give the same exact output as the previous program.


format 메소드에서 파이썬이 하는 것은 각 매개변수으로 대치하는 것이다. 다음과 같은 세부적인 사양이들어갈 수 있다.

What Python does in the format method is that it substitutes each argument value into the place of the specification. There can be more detailed specifications such as:

# decimal (.) precision of 3 for float '0.333'print('{0:.3f}'.format(1.0/3))# fill with underscores (_) with the text centered# (^) to 11 width '___hello___'print('{0:_^11}'.format('hello'))# keyword-based 'Swaroop wrote A Byte of Python'print('{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python'))

Output:

0.333___hello___Swaroop wrote A Byte of Python

Since we are discussing formatting, note that print always ends with an invisible "new line" character (\n) so that repeated calls to print will all print on a separate line each. To prevent this newline character from being printed, you can specify that it should end with a blank:

print('a', end='')print('b', end='')

Output is:

ab

Or you can end with a space:

print('a', end=' ')print('b', end=' ')print('c')

Output is:

a b c

Escape Sequences

Suppose, you want to have a string which contains a single quote ('), how will you specify this string? For example, the string is "What's your name?". You cannot specify 'What's your name?' because Python will be confused as to where the string starts and ends. So, you will have to specify that this single quote does not indicate the end of the string. This can be done with the help of what is called an escape sequence. You specify the single quote as \' : notice the backslash. Now, you can specify the string as 'What\'s your name?'.

Another way of specifying this specific string would be "What's your name?" i.e. using double quotes. Similarly, you have to use an escape sequence for using a double quote itself in a double quoted string. Also, you have to indicate the backslash itself using the escape sequence \\.

What if you wanted to specify a two-line string? One way is to use a triple-quoted string as shown previously or you can use an escape sequence for the newline character - \n to indicate the start of a new line. An example is:

'This is the first line\nThis is the second line'

Another useful escape sequence to know is the tab: \t. There are many more escape sequences but I have mentioned only the most useful ones here.

One thing to note is that in a string, a single backslash at the end of the line indicates that the string is continued in the next line, but no newline is added. For example:

"This is the first sentence. \This is the second sentence."

is equivalent to

"This is the first sentence. This is the second sentence."
로스트링

이스케이프 시퀀스와 같은 특별한 처리가 필요하지 않은 문자열을 지정하고 싶을 때 r또는 R을 사용한다
r"Newlines are indicated by \n"

정규식 사용자를 위한 일러두기
정규식을 사용할 때는 항상 로스트링을 사용한다. Otherwise, a lot of backwhacking may be required. For example, backreferences can be referred to as '\\1' or r'\1'.

변수

Using just literal constants can soon become boring - we need some way of storing any information and manipulate them as well. This is where variables come into the picture. Variables are exactly what the name implies - their value can vary, i.e., you can store anything using a variable. Variables are just parts of your computer's memory where you store some information. Unlike literal constants, you need some method of accessing these variables and hence you give them names.

Identifier Naming

Variables are examples of identifiers. Identifiers are names given to identify something. There are some rules you have to follow for naming identifiers:

  • The first character of the identifier must be a letter of the alphabet (uppercase ASCII or lowercase ASCII or Unicode character) or an underscore (_).
  • The rest of the identifier name can consist of letters (uppercase ASCII or lowercase ASCII or Unicode character), underscores (_) or digits (0-9).
  • Identifier names are case-sensitive. For example, myname and myName are not the same. Note the lowercase n in the former and the uppercase N in the latter.
  • Examples of valid identifier names are iname_2_3. Examples of invalid identifier names are 2thingsthis is spaced outmy-name and >a1b2_c3.

Data Types

Variables can hold values of different types called data types. The basic types are numbers and strings, which we have already discussed. In later chapters, we will see how to create our own types using classes.


Object

Remember, Python refers to anything used in a program as an object. This is meant in the generic sense. Instead of saying "the something"', we say "the object".

Note for Object Oriented Programming users:

Python is strongly object-oriented in the sense that everything is an object including numbers, strings and functions.

We will now see how to use variables along with literal constants. Save the following example and run the program.

How to write Python programs

Henceforth, the standard procedure to save and run a Python program is as follows:

For PyCharm

  1. Open PyCharm.
  2. Create new file with the filename mentioned.
  3. Type the program code given in the example.
  4. Right-click and run the current file.

NOTE: Whenever you have to provide command line arguments, click on Run -> Edit Configurations and type the arguments in the Script parameters: section and click the OKbutton:

PyCharm command line arguments

For other editors

  1. Open your editor of choice.
  2. Type the program code given in the example.
  3. Save it as a file with the filename mentioned.
  4. Run the interpreter with the command python program.py to run the program.

Example: Using Variables And Literal Constants

Type and run the following program:

# Filename : var.pyi = 5print(i)i = i + 1print(i)s = '''This is a multi-line string.This is the second line.'''print(s)

Output:

56This is a multi-line string.This is the second line.

How It Works

Here's how this program works. First, we assign the literal constant value 5 to the variable i using the assignment operator (=). This line is called a statement because it states that something should be done and in this case, we connect the variable name i to the value 5. Next, we print the value of iusing the print statement which, unsurprisingly, just prints the value of the variable to the screen.

Then we add 1 to the value stored in i and store it back. We then print it and expectedly, we get the value 6.

Similarly, we assign the literal string to the variable s and then print it.

Note for static language programmers

Variables are used by just assigning them a value. No declaration or data type definition is needed/used.

Logical And Physical Line

A physical line is what you see when you write the program. A logical line is what Python sees as a single statement. Python implicitly assumes that each physical line corresponds to a logical line.

An example of a logical line is a statement like print 'hello world' - if this was on a line by itself (as you see it in an editor), then this also corresponds to a physical line.

Implicitly, Python encourages the use of a single statement per line which makes code more readable.

If you want to specify more than one logical line on a single physical line, then you have to explicitly specify this using a semicolon (;) which indicates the end of a logical line/statement. For example:

i = 5print(i)

is effectively same as

i = 5;print(i);

which is also same as

i = 5; print(i);

and same as

i = 5; print(i)

However, I strongly recommend that you stick to writing a maximum of a single logical line on each single physical line. The idea is that you should never use the semicolon. In fact, I have never used or even seen a semicolon in a Python program.

There is one kind of situation where this concept is really useful: if you have a long line of code, you can break it into multiple physical lines by using the backslash. This is referred to as explicit line joining:

s = 'This is a string. \This continues the string.'print(s)

Output:

This is a string. This continues the string.

Similarly,

i = \5

is the same as

i = 5

Sometimes, there is an implicit assumption where you don't need to use a backslash. This is the case where the logical line has a starting parentheses, starting square brackets or a starting curly braces but not an ending one. This is called implicit line joining. You can see this in action when we write programs using list in later chapters.

인덴테이션

공백은 파이썬에서 중요하다. 실제로, 라인의 시작에 공백은 중요하다. 이를 인덴테이션이라 부른다. 논리 라인의 시작점의 공백으로 문장의 그룹을 결정짓는데 사용한다.

이 의미는 함께 진행될 문장은 같은 인덴테이션을 가져야한다. 문장 집합을 블록이라하면 어떻게 블록을 사용하는지 보여준다.

알아야할 것은 인덴테이션이 잘못되면 에러가 발생한다는 점이다.
i = 5# Error below! Notice a single space at the start of the line print('Value is', i)print('I repeat, the value is', i)

When you run this, you get the following error:

  File "whitespace.py", line 3    print('Value is', i)    ^IndentationError: unexpected indent

Notice that there is a single space at the beginning of the second line. The error indicated by Python tells us that the syntax of the program is invalid i.e. the program was not properly written. What this means to you is that you cannot arbitrarily start new blocks of statements (except for the default main block which you have been using all along, of course). Cases where you can use new blocks will be detailed in later chapters such as the control flow.

How to indent

Use four spaces for indentation. This is the official Python language recommendation. Good editors will automatically do this for you. Make sure you use a consistent number of spaces for indentation, otherwise your program will not run or will have unexpected behavior.

Note to static language programmers

Python will always use indentation for blocks and will never use braces. Run from __future__ import braces to learn more.

Summary

Now that we have gone through many nitty-gritty details, we can move on to more interesting stuff such as control flow statements. Be sure to become comfortable with what you have read in this chapter.




덧글

댓글 입력 영역