python基礎学習ノート(六)

16402 ワード


ここまで勉強するのはもううんざりしています.前のデータ構造などはよく見えますが、実際のことはできません.
 
基本文の使い方
 
カンマで出力
>>> print 'age:',25

age: 25

テキストと変数の値を同時に出力したいのに文字列フォーマットを使用したくない場合は、このプロパティが便利です.
>>> name = 'chongshi'

>>> salutation = 'Mr'

>>> greeting = 'Hello.'

>>> print greeting,salutation,name

Hello. Mr chongshi

 
 
モジュールインポート関数
モジュールから関数をインポートする場合は、
import somemodule
または
form somemodule immport  somefunction
または
from somemodule import somefunction.anotherfunction.yetanotherfunction
または
from somemodule import *  
最後のバージョンでは、指定したモジュールからすべての機能をインポートしたいと判断しただけです.
両方のモジュールにopen関数がある場合は、次のように関数を使用します.
module.open(...)
module.open(...)
もちろん、文の末尾にas句を追加し、その句の後に名前を付けることもできます.
>>> import math as foobar   #         

>>> foobar.sqrt(4)

2.0

>>> from math import sqrt as foobar  #       

>>> foobar(4)

2.0

 
わりあてぶん
シーケンシャルパケット解除
>>> x,y,z = 1,2,3

>>> print x,y,z

1 2 3

>>> x,y=y,x

>>> print x,y,z

2 1 3

辞書の任意のキー値ペアを取得または削除できます.popitem方程式を使用できます.
>>> scoundrel ={'name':'robin','girlfriend':'marion'}

>>> key,value = scoundrel.popitem()

>>> key

'name'

>>> value

'robin'

チェーン割り当て
チェーン割り当ては、同じ値を複数の変数に割り当てる近道です.
>>> x = y = 42

#

>>> y = 42

>>> x = y

>>> x

42

ぞうりわりあて
>>> x = 2

>>> x += 1  #(x=x+1)

>>> x *= 2  #(x=x*2)

>>> x

6

 
 
せいぎょぶん
if文:
name = raw_input('what is your name?')

if name.endswith('chongshi'):

    print 'hello.mr.chongshi'

#  

>>> 

what is your name?chongshi  #

#  

hello.mr.chongshi

 
else句
name = raw_input('what is your name?')

if name.endswith('chongshi'):

    print 'hello.mr.chongshi'

else:

  print 'hello,strager'

#  

>>> 

what is your name?hh  #      

#  

hello,strager

 
Elif句
「else if」の略です
num = input('enter a numer:')

if num > 0:

    print 'the numer is positive'

elif num < 0:

    print 'the number is negative'

else:

  print 'the nuber is zero'

#  

>>> 

enter a numer:-1

#  

the number is negative

 
ネスト
ifネストの例を見てみましょう(pythonは改行をインデントで表しています)
name = raw_input('what is your name?')

if name.endswith('zhangsan'):

    if name.startswith('mr.'):

        print 'hello.mr.zhangsan'

    elif name.startswith('mrs.'):

        print 'hello.mrs.zhangsan'

    else:

        print 'hello.zhangsan'

else:

    print 'hello.stranger'

「mr.zhangsan」と入力した場合、最初のprintの内容が出力されます.mrs.zhangshanを入力し、2番目のprintの内容を出力します.「zhangsan」と入力すると、3番目のprintの内容が出力されます.他の名前を入力すると、最後の結果が出力されます(hello.stranger)
 
断言する
プログラムが正常に動作するには、プログラム内の条件が必ず真であることを確認する必要がある場合は、assert文はプログラムにチェックポイントを設定できます.
>>> age = 10

>>> assert 0 < age < 100

>>> age = -1

>>> assert 0 < age < 100 , 'the age must be realistic'



Traceback (most recent call last):

  File "<pyshell#8>", line 1, in <module>

    assert 0 < age < 100 , 'the age must be realistic'

AssertionError: the age must be realistic

 
 
ループステートメント
印刷1~100の数(whileサイクル)
x= 1

while x <= 100:

    print x

  x += 1

#  

1

2

3

4

.

.

100

次の例(whileループ)を見て、ユーザー名の入力を1サイクルで保証します.
name = ''

while not name:

    name = raw_input('please enter your name:')

print 'hello.%s!' %name

#  

>>> 

please enter your name:huhu

#  

hello.huhu!

印刷1~100の数(forサイクル)
for number in range(1,101):

  print number

#  

1

2

3

4

.

.

100

whileサイクルよりも簡潔ではないでしょうか.しかし、私たちが以前他の言語を勉強した経験によると、whileの例は理解しやすいです.
 
簡単なfor文で辞書のすべてのキーをループできます.
d = {'x':1,'y':2,'z':3}

for key in d:

  print key,'corresponds to',d[key]

#  

>>> 

y corresponds to 2

x corresponds to 1

z corresponds to 3

 
break文
breakはループを終了するために使用され、100以内の最大平方数を探すと、プログラムは100から0まで反復することができ、ステップ長は-1である.
from math import sqrt

for n in range(99,0,-1):

    root = sqrt(n)

    if root == int(root):

        print n

        break

#  

>>> 

81

 
continue文
continueは現在の反復を終了し、次のループにジャンプして実行します.
while True:

    s=raw_input('enter something:')

    if s == 'quit':

        break

    if len(s) < 3:

        continue

  print 'Input is of sufficient length'

#  

>>> 

enter something:huzhiheng  #      3,    

Input is of sufficient length

enter something:ha        #      3,    

enter something:hah       #      3,    

Input is of sufficient length

enter something:quit       #      quit,