2014年2月16日日曜日

Learn Python the Hard Way 19-23

Exercise 19: Functions and Variables

def cheese_and_crackers(cheese_count, boxes_of_crackers):
  print "You have %d cheeses!" % cheese_count
  print "You have %d boxes of crackers!" % boxes_of_crackers
  print "Man that's enough for a party!"
  print "Get a blanket \n"


print "We can just give the function numbers directly:"
cheese_and_crackers(20,30)


print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50

cheese_and_crackers(amount_of_cheese,amount_of_crackers)


print "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)

# note it is taking the amount from global variable on line 13,14
print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)

Exercise 20: Functions and Files

from sys import argv

script, input_file = argv

def print_all(f):
  print f.read()

def rewind(f):
  f.seek(0)

def print_a_line(line_count,f):
  print line_count,f.readline()

current_file = open(input_file)

print "First let's print the whole file:\n"

print_all(current_file)

print "Now let's rewind, kind of like a tape."

rewind(current_file)

print "Let's print three lines:"

current_line = 1
print_a_line(current_line,current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)


f is file
seek
f.seek(0) move to the start of the file
f.readline() read a line from the file
readline() function returns the \n and adds a blank line.
Add a , (comma) at the end of print so that it doesn't print its own \n.
seek() function is dealing in bytes, not lines.
x = x + y is the same as x += y


ファイル操作

ファイル出力

# ファイル出力
f = open( "test.txt", "w" )
try:
    # 文字列を出力
    f.write( "test" )
      #=> test
    # イテレータ尽付きのものはwritelinesでまとめて出力
    f.writelines( ["1", "2", "3", "4", "5"] )
      #=> test12345
finally:
    f.close()
# 追記モードで出力
f = open( "test.txt", "a" )
try:
    # 文字列を出力
    f.write( "test" )
      #=> test12345test
finally:
    f.close()
# 読み込みモードで実行するとエラーになる
f = open( "test.txt", "r" )
try:
    # 文字列を出力
    f.write( "test" )
      #=> IOError: not writable
finally:
    f.close()

ファイル読み込み

あらかじめ、同一階層に「test.txt」というファイルを用意し、中に以下の文字列が記載されているものとする。

abc
def
ghi
f = open( "test.txt", "r" )
try:
    # readは全読込み
    print( f.read() )
      #=> abc\ndef\nghi

    # ファイルポインタが最後まで行ってしまっているので、先頭に戻す
    f.seek( 0 )

    # readlinesは改行で区切ったlistを返す
    print( f.readlines() )
      #=> ['abc\n', 'def\n', 'ghi']

    # 3文字目にファイルポインタを移してreadしてみる
    f.seek( 2 )
    print( f.read() )
      #=> c\ndef\nghi

    # size指定しつつ少しずつ読み込む(5byteずつ読み込む例)
    # 読み終わると空文字を返すので、そこでbreak
    f.seek( 0 )
    while True:
        buf = f.read( 5 )
        if not buf:
            break
        print( buf + ", ", end="" )
          #=> abc\nd, ef\ngh, i,

    # readlineで一行ずつ読み込む
    # 最後の改行コードもlineに含まれます
    f.seek( 0 )
    while True:
        line = f.readline()
        if not line:
            break
        print( line + ", ", end="" )
          #=> abc\n, def\n, ghi,
finally:
    f.close()


ファイル操作時のモード

r : 読み込み
w : 書き込み
a : 追記
+ : 読み書き両方を指定したい場合に使用

t : テキストモード(デフォルト)
b : バイナリモード
# 追記モードでreadも可能な状態
f = open( "test.txt", "a+" )
try:
    # 書き込み可能
    f.write( "test" )
    # 読込んだものを即読込み可能
    print( f.read() )
      #=> test
finally:
    f.close()
# テキストモードで読んだ場合は、strクラスで取得出来る
f = open( "test.bmp", "rt" )
print( f.read().__class__ )
  #=> 
f.close
# バイナリモードで読んだ場合は、bytesクラスで取得出来る
f = open( "test.bmp", "rb" )
print( f.read().__class__ )
  #=> 
f.close
# バイナリモードで画像を読んで、別ファイルに書き込んでみる
f = open( "test.bmp", "rb" )
f2 = None
try:
    f2 = open( "test2.bmp", "wb" )
    f2.write( f.read() )
finally:
    f.close
    if f2:
        f2.close
# テキストモードの内容をバイナリモードに移そうとすると、エラー
f = open( "test.bmp", "r" )
f2 = open( "test2.bmp", "wb" )
f2.write( f.read() )
  #=> TypeError: must be bytes or buffer, not str

Exercise 21: Functions Can Return Something

def add(a,b):
  print "ADDING %d + %d" % (a,b)
  return a + b

def substract(a,b):
  print "SUBSTRACTING %d - % d" %(a,b)
  return a - b

def multiply(a,b):
  print "MULTIPLYING %d * %d" % (a,b)
  return a * b

def divide(a,b):
  print "DIVIDING %d / %d" %(a,b)
  return a / b

print "Let's do some math with just functions!"

age = add(30,5)
height = substract(78,4)
weight = multiply(90,2)
iq = divide(100,2)

print "Age:%d, Height: %d, Weight:%d, IQ:%d" % (age,height,weight, iq)

print "Here is a puzzle."

what = add(age,substract(height,multiply(weight,divide(iq,2))))

print "That becomes:", what, "Can you do it by hand?"

To put your own values, use int(raw_input()) or float(raw_input())


Exercise 22: What Do You Know So Far?

復習チャプター

Exercise 23: Read Some Code

Read some Python codes from the following sites:
GitHub, BitBucket, Gitorious,  Launchpad, SourceForge, FreeCode, etc.

GitHub (86,719 repository results with "Python"):
Python Guide - Hitchhiker's Guide to Python / Python Best Practices Guidebook, html version
Python Patterns - A collection of design patterns implemented in Python
Python docx - Docx creates, reads and writes Microsoft Office Word 2007 docx files.
PythonBooks - A showcase of the best free ebooks about Python. Website
Python Oauth2 - Python OAuth library
Requests: HTTP for Humans - Requests is an Apache2 Licensed HTTP library, written in Python.
Tornado Web Server - Tornado is a Python web framework and asynchronous networking library.
Bayesian Methods for Hackers - An introduction to Bayesian methods + probabilistic programming.
Mega Project List - A list of practical projects that anyone can solve in any programming language
Scrapy - A fast high-level screen scraping and web crawling framework for Python.
scikit-learn - A Python module for machine learning built on top of SciPy.
pandas - Python data analysis toolkit. Website
Pyquery - A jquery-like library for python

BitBucket (8,901 results for “python”)
PyPy - Implementation of the Python, and compiler framework for dynamic language implementations. Website
Whoosh - Full-text indexing and searching library implemented in pure Python.
Pygments - A Pythonic syntax highlighter for over 200 languages and text formats.
CherryPy - A pythonic, object-oriented HTTP framework.
Looks like many of the projects on BitBucket moved to GitHub...

SourceForge (79 search results for: python)
MySQL for Python - MySQL database connector for Python. GitHub
Numerical Python - Adds a fast and sophisticated array facility to Python. Website
Python IRC client library - Event-driven IRC client framework written in Python Website BitBucket
Python megawidgets - A toolkit for building high-level compound widgets in Python using the Tkinter module. Website
Python parsing module - A general parsing module for Python. Website
Raspberry-gpio-python - A Python module to control the GPIO on a Raspberry Pi.

Gitorious (1,991 search results with keyword "python")
Launchpad (1,030,000 pages matching "python")
FreeCode (1,908 search results for: python)


過去ログ:

SF Python Hack Night / Learn Python the Hard Way 1-6
Learn Python the Hard Way 続き 7-10
Learn Python the Hard Way 続き 11-15
PyLadies South Bay and Learn Python the Hard Way 続き 16-18

Disclaimer このブログは山崎富美の個人的なものです。ここで述べられていることは私の個人的な意見に基づくものであり、私の雇用者には一切の関係はありません。