Python基礎チュートリアル入門シリーズ

24474 ワード

githubソースダウンロード
  • 1. import
  • 2. 入力
  • 3. 出力
  • 4. 割り当て、演算
  • 5. range使用:ファクトリ関数
  • 6. 条件文
  • 7.ループ文
  • 8. 比較動作
  • 9. 条件判断
  • 10. ループ判定
  • continueとbreak
  • 11. 内蔵コレクション:list[],tuple()(カッコまたはカッコなし)、dict{},set([])
  • 11.1リスト名[インデックスアドレス値]
  • 11.2多次元リスト
  • 11.3 tuple元祖不変
  • 11.4 dict、すなわち辞書
  • 11.5 set:自己重み付け属性
  • 12. 反復器
  • 13. ジェネレータ
  • 14. 関数の定義
  • 14.1デフォルトパラメータ
  • 14.2セルフコール
  • 14.3可変パラメータ
  • 14.4キーワードパラメータ
  • 15. グローバル変数
  • 16. ファイルアクション
  • 16.1 forサイクルの後にif判定を加えることもでき、偶数のみの二乗:
  • をスクリーニングすることができる.
  • 16.2オブジェクト向けプログラミング
  • 17. 異常処理
  • 18. ZIP関数
  • 19. map


  • 1. import
    # -*- coding: utf-8 -*-
    ##      
    import turtle
    import pickle  #     
    import tensorflow as tf # alias tf
    from time import time, localtime #        
    from time import *  #       
    ##       :   Mac   ,   python           site-packages,  ,                 ,              。
    
    
    """
    If the module doesn't exist, 
        pip install name_module  # for python2
        pip3 install name_module # for python3
    
        pip install name_module=verson_num  # for python install specific versions
        pip3 install name_module=version_num # for python3 specific versions
    
        pip install -U name_module # for update
        pip3 install -U name_module # for update
    """
    

    2.入力
    a_input = input('please input a number:')
    score = int(input('Please input your score: 
    '
    ))

    3.出力
    print("hello, world")
    
    ##    
    ## %d     
    ## %f      
    ## %s      
    ## %x         
    print('Age: %s. Gender: %s' % (25, True))
    
    # format     {}
    print('Hello, {0},       {1:.1f}%'.format('  ', 17.125))

    4.代入、演算
    ###   :      
    a, b, c = 1, 2, 3
    print(a, b, c)
    
    ##  , , , ,  ,  ,   
    ## + , -, * , /, %, // , **
    print(2**4)
    
    
    ##   
    ord(' ')  #          
    chr(12321)  #          
    
    'ABC'.encode('ascii')  #       bytes
    '  '.encode('utf-8')
    
    b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')  #        
    
    len('ABC')  #       
    len('\xe4\xb8\xad\xe6\x96\x87')

    5.range使用:工場関数
    range(1, 10)
    stop = 10
    range(stop=stop) ## it means range(0,10)
    step = 2
    range(1, stop=stop, step=step) # it means range from 1 to 10 step by 2

    6.条件文
    ## python         
    age = input("input your age
    ") if int(age) > 18: print("already ") elif int(age) > 30: print("30 more") else: print('<18') print('out of if else ') # A exercise # L = [ ['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'PHP'], ['Adam', 'Bart', 'Lisa'] ] print(L[0][0]) print(L[1][1]) print(L[2][2])

    7.ループ文
    for i in range(0, 7):
        print("hello world")
    
    # while a<10 and b<20
    t = turtle.Pen()
    for i in range(0, 4):
        t.forward(100)
        t.left(90)
    
    t = (1, 2)
    
    ## while   0-9    
    '''
    while True:
        print("always print True")
    '''
    conditions = 0
    while conditions < 10:
        print(conditions)
        conditions += 1

    8.比較操作
             :
              ()
                (<=)
                (>=)
               (==)
                (!=)
                 return True   False

    9.条件判断
    #       None,  ,   True
    # (list、 tuple 、dict   set )   ,       0 ,  False
    age = 20
    if age >= 18:
        print("your age is ", age)
        print('adult')
    elif age >= 6:
        print('teenager')
    else:
        print('kid')
    
    worked = True
    isDone = 'Done' if worked else 'not yet'
    print(isDone)

    10.ループ判定
    for name in c:
        print(name)
    
    
    print("range          : ", range(4))

    continueとbreak
    11.組み込みコレクション:list[],tuple()(カッコまたはカッコなし)、dict{},set([])
            
    

    11.1リスト名[インデックスアドレス値]
    ### name[ 1 :5] from 1 ~ 5
    
    ### name[ -1: -2 ]        ,   2
    ### list   
    c = [1, 2, 3, "  "]
    c.append("     ")
    c.insert(1, "   1  ")
    c.remove(2) #         2   
    c.index(2)  #        2    
    c[2:]  #             ,          2      3         
    c[-2:] #          ,       (    )    
    c[0:3] #  0   2 ( 3   )     
    #c.sort() #       , c.sort(reverse=True) #       
    print(c[1])
    print(c[2:4])
    print(c[-1:: -2])
    print(" list c     : %s " % len(c))

    11.2多次元リスト
    a = [1 ,2,3,4,5]     #     
    multi_dim_a = [[1,2,3],
                   [2,3,4],
                   [3,4,5]]  #     
    

    11.3 tuple元祖不変
    classmates = ('Michael', 'Bob', 'Tracy')
    classmates02 = 'Michael', 'Bob', 'Tracy'
    t = ('a', 'b', ['A', 'B'])
    t[2][0] = 'X'
    t[2][1] = 'Y'
    # t =  ('a', 'b', ['X', 'Y'])

    11.4 dict、すなわち辞書
    (     map),key - value     
    
    ###  key           , get()   ,     none
    ###    :
    ###                ,    key      ;
    ###               ,     。
    
    ## dict      ,       dict,   collections    OrderDict  
    
    d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
    print("  : d.get('xx')  =  d['xx']: ", d.get('Bob'))
    #        
    d.pop('Bob')
    del d['Tracy']
    d[1] = 20  #        ,    
    
    ##        ,      ,
    d4 = {'apple': [1,2,3], 'pear':{1:3, 3:'a'}, 'orange':func}
    print(d4['pear'][3])    # a

    11.5 set:自己重量除去属性
    ## add , remove
    s = set([1, 2, 3])
    s.add(4)
    print("s.add() ", s)
    s.remove(4)
    print("s.remove :: ", s)
    print("s.pop() ", s.pop())
    print("after s.pop()::", s)

    12.反復器
    13.ジェネレータ
    14.関数の定義
    def hi_name(yourname):
        print(yourname)
    def hi(yourname, num):
        print(yourname,num)

    14.1デフォルトパラメータ
    ##                    =      ,                           
    def function_name(price, color='red', brand='carmy', is_second_hand=True):
        print('price', price,
              'color', color,
              'brand', brand,
              'is_second_hand', is_second_hand, )
    hi_name("            ")

    14.2セルフコール
    '''
                  ,  if         True,           。
                 ,if        False,         。 
    '''
    if __name__ == '__main__':
        #code_here
        print("     ")

    14.3可変パラメータ
    def report(name, *grades):
        total_grade = 0
        for grade in grades:
            total_grade += grade
        print(name, 'total grade is ', total_grade)
    report('wang', 12,14,16,20)

    14.4キーワードパラメータ
    ## universal_func(*args, **kw) ==>         
    def portrait(name, **kw):
        print('name is', name)
        for k, v in kw.items():
            print(k, v)
    print(portrait('Mike', age=24, country='China', education='bachelor'))

    15.グローバル変数
    global_param = 100
    def for_local():
        local_parm = 20
        print("value of local_parm is %d" % local_parm)
        print("value of global_parm is %d" % global_param)
    
    
    # print("local_parm does not exit" % local_parm)
    print("value of global_parm is %d" % global_param)

    16.ファイル操作
    '''
       r          ,       。
    
      r+           ,       。
    
      rb+            ,       。
    
      rt+           ,     。
    
      w       ,            0,         。            。
    
      w+        ,             ,         。            。
    
      a             。      ,       ,      ,            ,            。(EOF   )
    
      a+              。      ,       ,      ,             ,            。 (   EOF    )
    
      wb               ;      。
    
      wb+               ,     。
    
      wt+               ;    。
    
      at+           ,            。
    
      ab+            ,            。
    
    
    
                  
            \' '
            \"  "
            \a ‘bi’   
            \b    
            \f    (    )
            
    , \r , \t ( ) \\ \ '''
    game_data = {"position": "N2 E3", "pocket": ["key", "knife"], "money": 160} save_file = open("save.dat", "wb") ## 'w':write;'r':read. pickle.dump(game_data, save_file) save_file.close() ## load_file = open("save.dat", "rb") load_game_data = pickle.load(load_file) load_file.read() load_file.readline() # load_file.readlines() # python_list print(load_game_data) load_file.close() for x, y in [(1, 1), (2, 4), (3, 9)]: print(x, y)

    16.1 forサイクルの後にif判断を加えることもでき、偶数のみの二乗をスクリーニングすることができます.
    [x * x for x in range(1, 11) if x % 2 == 0]
    
    [m + n for m in 'ABC' for n in 'XYZ']
    
    import os  #   os  ,         
    [d for d in os.listdir('.')]  # os.listdir         

    16.2オブジェクト向けプログラミング
    class Calculator:       #      ,     
        name = 'Good Calculator'  #   class   
        price = 18
        def add(self,x,y):
            print(self.name)
            result = x + y
            print(result)
        def minus(self,x,y):
            result=x-y
            print(result)
        def times(self,x,y):
            print(x*y)
        def divide(self,x,y):
            print(x/y)
    
    '''
        cal=Calculator()  #      class     "()",                ,      .
        cal.name
        cal.add(10,20)
    '''
    
    
    # __init__        class   ,     initial      .      ,      ,
    #              
    #
    #
    #   c=Calculator('bad calculator',18,17,16,15),           。     。
    
    class Calculator:
        name = 'good calculator'
        price = 18
        def __init__(self,name,price,height,width,weight):   #   ,           
            self.name=name
            self.price=price
            self.h=height
            self.wi=width
            self.we=weight

    17.異常処理
    try:
        file=open('eeee.txt','r')  #      
    except Exception as e:  #        e  
        print(e)

    18.ZIP関数
    a=[1,2,3]
    b=[4,5,6]
    ab=zip(a,b)
    print(list(ab)) ##   list         
    for i,j in zip(a,b):
         print(i/2,j*2)

    19. map
    def fun(x,y):
        return (x+y)
    list(map(fun,[1],[2]))