python基礎チュートリアル大全速学

13027 ワード

pythonゼロ基礎学習
(皆さんに役に立つことを願って、主に自分の復習に使います)
Pythonは、Guido Van Rossum(Guido Van Rossum)が90年代初期に設計した.解釈性、コンパイル性、インタラクティブ性、オブジェクト向けのスクリプト言語を高度に組み合わせて理解します.読みやすさが強く、他の言語よりも英語のキーワードをよく使用し、他の言語の句読点は、他の言語よりも特色のある文法構造を持っています.
Pythonは解釈型言語です.これは開発過程でコンパイルという一環がなくなったことを意味します.PHPやPerl言語のようなPythonはインタラクティブな言語です.これは、Pythonプロンプトでプログラムを直接インタラクティブに書くことができることを意味します.Pythonはオブジェクト向け言語です.これは、Pythonがオブジェクト向けのスタイルやコードをオブジェクトにカプセル化するプログラミング技術をサポートしていることを意味します.pythonは、簡単な文字処理からブラウザ、ゲームまで、幅広いアプリケーション開発をサポートしています.Python自体もC、C++、SmallTalk、Algol-68、ABC、Unix、shellModula-3、その他のスクリプト言語など、多くの他の言語から発展してきました.Perl言語のようにPythonソースコードはGPL(GNU General Public License)プロトコルに従う.ツールはpycharm pycharmでアクティブ化できます.詳細は、次のとおりです.https://blog.csdn.net/weixin_43620922/article/details/85468272注意:このチュートリアルはPython 3に基づいて書かれたデータ型と演算子です.
#   
3  # => 3

#            
1 + 1  # => 2
8 - 1  # => 7
10 * 2  # => 20

#       ,         
35 / 5  # => 7.0
5 / 3  # => 1.6666666666666667

#              
5 // 3     # => 1
5.0 // 3.0 # => 1.0 #       
-5 // 3  # => -2
-5.0 // 3.0 # => -2.0

#              
3 * 2.0 # => 6.0

#   
7 % 3 # => 1

# x y  
2**4 # => 16

#         
(1 + 3) * 2  # => 8

#    
True
False

#  not  
not True  # => False
not False  # => True

#      ,  and or    
True and False # => False
False or True # => True

#           
0 and 2 # => 0
-5 or 0 # => -5
0 == False # => True
2 == True # => False
1 == True # => True

#  ==    
1 == 1  # => True
2 == 1  # => False

#  !=    
1 != 1  # => False
2 != 1  # => True

#     
1 < 10  # => True
1 > 10  # => False
2 <= 2  # => True
2 >= 2  # => True

#          !
1 < 2 < 3  # => True
2 < 3 < 2  # => False

#            
"      "
'       '

#         
"Hello " + "world!"  # => "Hello world!"

#             
"This is a string"[0]  # => 'T'

#  .format       
"{} can be {}".format("strings", "interpolated")

#            
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
# => "Jack be nimble, Jack be quick, Jack jump over the candle stick"

#        ,      
"{name} wants to eat {food}".format(name="Bob", food="lasagna") 
# => "Bob wants to eat lasagna"

#     Python3     Python2.5      ,            
"%s can be %s the %s way" % ("strings", "interpolated", "old")

# None     
None  # => None

#   None         ==,  is。is                  。
"etc" is None  # => False
None is None  # => True

# None,0,    ,   ,      False
#        True
bool(0)  # => False
bool("")  # => False
bool([]) # => False
bool({}) # => False

変数とコレクション
# print        
print("I'm Python. Nice to meet you!")

#              
#           ,        
some_var = 5
some_var  # => 5

#              
#                
some_unknown_var  #   NameError

#    (list)    
li = []
#               
other_li = [4, 5, 6]

#  append         
li.append(1)    # li   [1]
li.append(2)    # li   [1, 2]
li.append(4)    # li   [1, 2, 4]
li.append(3)    # li   [1, 2, 4, 3]
#  pop       
li.pop()        # => 3  li   [1, 2, 4]
#  3    
li.append(3)    # li  [1, 2, 4, 3]

#          
li[0]  # => 1
#         
li[-1]  # => 3

#        IndexError
li[4]  #   IndexError

#        
li[1:3]  # => [2, 4]
#   
li[2:]  # => [4, 3]
#   
li[:3]  # => [1, 2, 4]
#       
li[::2]   # =>[1, 4]
#     
li[::-1]   # => [3, 4, 2, 1]
#                  
# li[ : :  ]

#  del        
del li[2]   # li is now [1, 2, 3]

#       
#   :li other_li     
li + other_li   # => [1, 2, 3, 4, 5, 6]

#  extend    
li.extend(other_li)   # li   [1, 2, 3, 4, 5, 6]

#  in         
1 in li   # => True

#  len     
len(li)   # => 6

#           
tup = (1, 2, 3)
tup[0]   # => 1
tup[0] = 3  #   TypeError

#              
len(tup)   # => 3
tup + (4, 5, 6)   # => (1, 2, 3, 4, 5, 6)
tup[:2]   # => (1, 2)
2 in tup   # => True

#           ,     
a, b, c = (1, 2, 3)     #   a 1,b 2,c 3
#              
d, e, f = 4, 5, 6
#              
e, d = d, e     #   d 5,e 4

#          
empty_dict = {}
#       
filled_dict = {"one": 1, "two": 2, "three": 3}

#  []  
filled_dict["one"]   # => 1

#   keys       。
#    keys          ,           list  。            。
#   :          ,             。
list(filled_dict.keys())   # => ["three", "two", "one"]

#  values      。 keys  ,  list   ,       。
list(filled_dict.values())   # => [3, 2, 1]

#  in             
"one" in filled_dict   # => True
1 in filled_dict   # => False

#           KeyError
filled_dict["four"]   # KeyError

#  get   KeyError
filled_dict.get("one")   # => 1
filled_dict.get("four")   # => None
#         get         
filled_dict.get("one", 4)   # => 1
filled_dict.get("four", 4)   # => 4

# setdefault                
filled_dict.setdefault("five", 5)  # filled_dict["five"]  5
filled_dict.setdefault("five", 6)  # filled_dict["five"]  5

#     
filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
filled_dict["four"] = 4  #        

#  del  
del filled_dict["one"]  #  filled_dict  one  

#  set    
empty_set = set()
#        ,       。
some_set = {1, 1, 2, 2, 3, 4}   # some_set   {1, 2, 3, 4}

#           
filled_set = some_set

#        
filled_set.add(5)   # filled_set   {1, 2, 3, 4, 5}

# &    
other_set = {3, 4, 5, 6}
filled_set & other_set   # => {3, 4, 5}

# |    
filled_set | other_set   # => {1, 2, 3, 4, 5, 6}

# -    
{1, 2, 3, 4} - {2, 3, 5}   # => {1, 4}

# in           
2 in filled_set   # => True
10 in filled_set   # => False

プロセス制御と反復
#          
some_var = 5

#    if  。     Python      
#   "some_var 10 "
if some_var > 10:
    print("some_var 10 ")
elif some_var < 10:    # elif     
    print("some_var 10 ")
else:                  # else     
    print("some_var  10")

"""
 for        
  :
    dog is a mammal
    cat is a mammal
    mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
    print("{} is a mammal".format(animal))

"""
"range(number)"       0     
  :
    0
    1
    2
    3
"""
for i in range(4):
    print(i)

"""
while         
  :
    0
    1
    2
    3
"""
x = 0
while x < 4:
    print(x)
    x += 1  # x = x + 1    

#  try/except       
try:
    #  raise    
    raise IndexError("This is an index error")
except IndexError as e:
    pass    # pass    ,           
except (TypeError, NameError):
    pass    #             
else:   # else      ,      except  
    print("All good!")   #    try                

# Python         (iterable)     。               
#    。     range           。

filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
print(our_iterable) # => dict_keys(['one', 'two', 'three']),             

#          
for i in our_iterable:
    print(i)    #    one, two, three

#          
our_iterable[1]  #   TypeError

#               
our_iterator = iter(our_iterable)

#                   
#  __next__         
our_iterator.__next__()  # => "one"

#      __next__      
our_iterator.__next__()  # => "two"
our_iterator.__next__()  # => "three"

#             ,   StopIteration
our_iterator.__next__() #   StopIteration

#    list            
list(filled_dict.keys())  # => Returns ["one", "two", "three"]

**関数**
#  def     
def add(x, y):
    print("x is {} and y is {}".format(x, y))
    return x + y    #  return    

#     
add(5, 6)   # =>   "x is 5 and y is 6"    11

#               
add(y=6, x=5)   #             

#               
def varargs(*args):
    return args

varargs(1, 2, 3)   # => (1, 2, 3)

#                   
def keyword_args(**kwargs):
    return kwargs

#           :
keyword_args(big="foot", loch="ness")   # => {"big": "foot", "loch": "ness"}

#             
def all_the_args(*args, **kwargs):
    print(args)
    print(kwargs)
"""
all_the_args(1, 2, a=3, b=4) prints:
    (1, 2)
    {"a": 3, "b": 4}
"""

#                   , *    , **    。
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args)   #     foo(1, 2, 3, 4)
all_the_args(**kwargs)   #     foo(a=3, b=4)
all_the_args(*args, **kwargs)   #     foo(1, 2, 3, 4, a=3, b=4)

#      
x = 5

def setX(num):
    #       x     x    
    x = num # => 43
    print (x) # => 43

def setGlobalX(num):
    global x
    print (x) # => 5
    x = num #       x   
    print (x) # => 6

setX(43)
setGlobalX(6)

#    Python     
def create_adder(x):
    def adder(y):
        return x + y
    return adder

add_10 = create_adder(10)
add_10(3)   # => 13

#       
(lambda x: x > 2)(3)   # => True

#        
map(add_10, [1, 2, 3])   # => [11, 12, 13]
filter(lambda x: x > 5, [3, 4, 5, 6, 7])   # => [6, 7]

#                。               。
[add_10(i) for i in [1, 2, 3]]  # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5]   # => [6, 7]

**クラス**
#       object  
class Human(object):

    #    ,          。
    species = "H. sapiens"

    #     ,           。           ,       
    #      Python     ,          。           
    #    。
    def __init__(self, name):
        # Assign the argument to the instance's name attribute
        self.name = name

    #     ,       self,        
    def say(self, msg):
        return "{name}: {message}".format(name=self.name, message=msg)

    #    ,          。           。
    @classmethod
    def get_species(cls):
        return cls.species

    #     。            。
    @staticmethod
    def grunt():
        return "*grunt*"

#       
i = Human(name="Ian")
print(i.say("hi"))     #    "Ian: hi"

j = Human("Joel")
print(j.say("hello"))  #    "Joel: hello"

#        
i.get_species()   # => "H. sapiens"

#          
Human.species = "H. neanderthalensis"
i.get_species()   # => "H. neanderthalensis"
j.get_species()   # => "H. neanderthalensis"

#       
Human.grunt()   # => "*grunt*"

モジュール
#  import    
import math
print(math.sqrt(16))  # => 4.0

#             
from math import ceil, floor
print(ceil(3.7))  # => 4.0
print(floor(3.7))   # => 3.0

#             
#   :      
from math import *

#         
import math as m
math.sqrt(16) == m.sqrt(16)   # => True

# Python         Python  。      ,    ,
#             。

#                 
import math
dir(math)

高度な使い方
#     (generators)        
def double_numbers(iterable):
    for i in iterable:
        yield i + i

#                 。             ,       
#      。
#
# range           ,    1 900000000            。
#
#        Python         ,           。
range_ = range(1, 900000000)
#       >=30       
#      `double_numbers`       30  。
for i in double_numbers(range_):
    print(i)
    if i >= 30:
        break

#    (decorators)
#      ,beg  say
# beg    say。     say_please  ,beg         。
from functools import wraps

def beg(target_function):
    @wraps(target_function)
    def wrapper(*args, **kwargs):
        msg, say_please = target_function(*args, **kwargs)
        if say_please:
            return "{} {}".format(msg, "Please! I am poor :(")
        return msg

    return wrapper

@beg
def say(say_please=False):
    msg = "Can you buy me a beer?"
    return msg, say_please

print(say())  # Can you buy me a beer?
print(say(say_please=True))  # Can you buy me a beer? Please! I am poor :(


1.勉強しやすい:Pythonは比較的少ないキーワードがあり、構造が簡単で、明確に定義された文法があり、勉強がもっと簡単です.2.読みやすい:Pythonコードの定義がより明確です.3.メンテナンスが容易:Pythonの成功は、ソースコードがかなりメンテナンスしやすいことです.4.広範な標準ライブラリ:Pythonの最大の利点の一つは豊富なライブラリであり、プラットフォームをまたいでUNIX、Windows、Macintoshで互換性が高い.5.インタラクティブモード:インタラクティブモードのサポートで、端末から実行コードを入力して結果を得る言語、インタラクティブなテストとデバッグコードの断片を入力することができます.6.移植可能:そのオープンソースの特性に基づいて、Pythonはすでに多くのプラットフォームに移植(つまり、それを動作させる)されている.7.拡張性:実行が速いキーコードが必要な場合、またはオープンしたくないアルゴリズムを作成する場合は、CまたはC++を使用してプログラムの一部を完了し、Pythonプログラムから呼び出すことができます.8.データベース:Pythonはすべての主要なビジネスデータベースのインタフェースを提供します.9.GUIプログラミング:PythonはGUIをサポートし、多くのシステム呼び出しに作成および移植することができる.10.埋め込み可能:PythonをC/C++プログラムに埋め込み、プログラムのユーザーに「スクリプト化」の能力を得ることができます.