'Python'에 해당되는 글 2건

  1. 2014.10.10 Pythons #3 예외처리
  2. 2014.09.18 Python Test Code
2014. 10. 10. 10:13

파이썬의 기본 입력 메커니즘은 라인을 기반으로 합니다.

데이터를 텍스트 파일에서 프로그램으로 읽어 들이면 한 번에 한 라인씩 가져옵니다.

 

파이썬의 open()내장함수는 파일에 연결하기 위해 존재합니다. for문과 함께 사용하면 파일을 읽는 건 매우 간단합니다.

 

 

 

 

배우 역활 : 배우가 하는 대사

데이터를 자세히 살펴 보면 특정한 형식으로 되어있습니다. 이 형식을 잘 기억하고 계세요. 각각의 라인을 처리해서 필요에 따라 일부분만을 뽑아낼수 있습니다. split() 메서드를 활용하면 됩니다.

 

Man: Is this the right room for an argument?

each_line.split(" : ")

Man / Is this the fight room for an argument?

 

split()메서드는 문자열의 리스트를 반환하는데, 이스트가 대입 연산자 왼쪽의 타깃 식별자에 대입됩니다. 이것을 다중 대입이라고 합니다.

 

(role, line_spoken) = each_line.split(":")

 

여러분의 코드가 잘 돌다가 런타임 에러와 함께 크래시 되었습니다. 데이터 파일을 살펴봅시다. 위라인이 성공적으로 처리되고 난 뒤 어떤 데이터가 왔는지 알아보겠습니다.

 

Man: You most certainly did not 이라는 대사를 하고나서 데이터를 처리하다가 문제가 생겼습니다.

다음 대사에서 :콜론이 두개가 들어가있습니다. 한개아 아니라 두개 일때는 split()메서드는 라인을 세부분으로 나눕니다.

data = open('sketch.txt')

 

for each_line in data:

(role, line_spoken) = each_line.split(' :', 1)

print(role, end= '')

print(' said: ', end = '')

print(line_spoken, end= '')

data.close()

 

또 다른 ValueError가 나타났네요 이번에는 무엇이 잘못된 걸까요?

 

(pause) 라는 텍스트 파일이있네요 콜론이 없는 경우 는 어떻게 해야될까요 ?

 

두가지방법이있습니다. 하나는 논리를 추가하는것 하나는 에러가 생기도록 놔둔다음에 에러가 생기면 처리할 수있게한다.

 

첫번째로는 논리 추가하기 입니다.

>>>each_line = "I tell you, there's no such thing as a flying circus"

>>>each_line.find(":")

-1

>>>each_line = "I tell you: there's no such thing as a flying circus"

>>>each_line.find(':')

10

find()내장 함수를 사용하여 콜론이 있고 없고에 따라 인덱스 값을 반환합니다.

 

 

 

조건문을 이해하는데 몇초 걸릴수도 있지만, 이문장은 잘 작동합니다. not 키워드를 사용하면 조건을 반대로 만든다는 점에 유의하세요 !

 

이제 다른한가지방법은 오류가 나도록 납두다가 오류가 발생시 처리하는거입니다.

여기서는 try구문을 사용하게됩니다.

 

data = open('sketch.txt')

 

for each_line in data;

try:

(role, line_spoken) = each_line.split(':', 1)

print(role, end= '')

print(' said : ', end = '')

print(line_spoken, end='')

except

pass

data.close()

Try와 pass문을 함께 사용한 예입니다.

 

Try문은 모든 예외를 잡고나서 pass문을 이요해서 에러를 무시함으로써 예외를 처리하게 됩니다.

 

두가지 방법다 예외 처리할수 있습니다.

 

※참고사이트 : http://ji-ggu.tistory.com/entry/Python-3-예외처리

'Python' 카테고리의 다른 글

Python Test Code  (0) 2014.09.18
Posted by 아도니우스
2014. 9. 18. 21:43
1. Exponentiation

All that math can be done on a calculator, so why use Python? Because you can combine math with other data types (e.g. booleans) and commands to create useful programs. Calculators just stick to numbers.

Now let's work with exponents.

eight = 2 ** 3

In the above example, we create a new variable called eight and set it to 8, or the result of 2 to the power to 3 (2^3).

Notice that we use ** instead of * or the multiplication operator.

 

2. Bringing It All Together

Nice work! So far, you've learned about:

  • Variables, which store values for later use
  • Data types, such as numbers and booleans
  • Whitespace, which separates statements
  • Comments, which make your code easier to read
  • Arithmetic operations, including +, -, *, /, **, and %
Instructions

Let's put our knowledge to work.

  1. Write a single-line comment on line 1. It can be anything! (Make sure it starts with #)
  2. Set the variable monty equal to True.
  3. Set another variable python equal to 1.234.
  4. Set a third variable monty_python equal to python squared.
?
Stuck? Get a hint! Hint

You can use arithmetic operators directly on variables! Remember, python squared means python ** 2.

Note that the name of the variable monty_python has nothing to do with the name of the variables monty and python. We just decided to use these variable names because Python people love Monty Python's Flying Circus

'Python' 카테고리의 다른 글

Pythons #3 예외처리  (0) 2014.10.10
Posted by 아도니우스