数分でスタートPython

15511 ワード

取得コード:learnpython.py
PythonはGuido Van Rossumが1991年に創造した.現在存在する最も流行している言語の一つです.Pythonが好きになったのは、簡潔な文法のためです.基本的には擬似コードで実行されます.
注意:この文章はPython 2.7に適用されますが、Python 2に適用される可能性があります.x.Python 2.7は2020年にサポートを停止します.
書いたPythonコードは、Python 2.7と3に互換性がある.xは完全に可能である.Pythonの__を使うことでfuture__imports.Python 3で書かれたコードをPython 2で実行することができます.
詳細はこちらをご覧ください
#         #   。

"""      
         """   
"""


####################################################
## 1.            
####################################################

#     
3  # => 3

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

#        。       。
5 / 2  # => 2

#                 
2.0     #        
11.0 / 4.0  # => 2.75         

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

#               (         )
#                '/'。
from __future__ import division
11/4    # => 2.75  
11//4   # => 2 

#      
7 % 3 # => 1

#     
2**4 # => 16

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

#      
#    「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

#   「not」  
not True  # => False
not False  # => 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

#        「"」  「'」  
"This is a string."
'This is also a string.'

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

#        
"Hello" * 3  # => "HelloHelloHello"

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

#      「%」    
#   「%」    Python 3.1                   
#     ,               。
x = 'apple'
y = 'lemon'
z = "The items in the basket are %s and %s" % (x,y)

#              
#           
"{} is a {}".format("This", "placeholder")
"{0} can be {1}".format("strings", "formatted")
#        ,        
"{name} wants to eat {food}".format(name="Bob", food="lasagna")

# None     
None  # => None

#     「==」   None     
#   「is」  
"etc" is None  # => False
None is None  # => True

# 「is」             。
#               ,
#          。

#                    。
#           :
#    - None
#    -           (e.g., 0, 0L, 0.0, 0j)
#    -      (e.g., '', (), [])
#    -      (e.g., {}, set())
#    -                  
#    :https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
#          (  bool()     True)
bool(0)  # => False
bool("")  # => False


####################################################
## 2.      
####################################################

# Python    print  
print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!

#              
input_string_var = raw_input("Enter some data: ") #     String   
input_var = input("Enter some data: ") #     Int   
#   :  input()       
#   : Python 3,input()     ,  raw_input()   input()

#              
some_var = 5    #            
some_var  # => 5

#                  。
#   「    」        。
some_other_var  #          

# 「if」       C      「?:」
"yahoo!" if 3 > 2 else 2  # => "yahoo!"

# Lists  
li = []
#            list
other_li = [4, 5, 6]

#   append   list      
li.append(1)    # li is now [1]
li.append(2)    # li is now [1, 2]
li.append(4)    # li is now [1, 2, 4]
li.append(3)    # li is now [1, 2, 4, 3]
#   pop list       
li.pop()        # => 3 and li is now [1, 2, 4]
#          
li.append(3)    # li is now [1, 2, 4, 3] again.

#   list        
li[0]  # => 1
#   「=」               
li[0] = 42
li[0]  # => 42
li[0] = 1  # Note: setting it back to the original value
# Look at the last element
#         
li[-1]  # => 3

#          IndexError
li[4]  # Raises an IndexError

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

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

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

#   「extend()」   list
li.extend(other_li)   # Now li is [1, 2, 3, 4, 5, 6]

#              
li.remove(2)  # li is now [1, 3, 4, 5, 6]
li.remove(2)  #     ValueError,  2    li  

#            
li.insert(1, 2)  # li is now [1, 2, 3, 4, 5, 6] again

#          
li.index(2)  # => 1
li.index(7)  #     ValueError,  7  li 

#   「in」  list        
1 in li   # => True

#   「len()」  list  
len(li)   # => 6


#   「Tuples」   list,        
tup = (1, 2, 3)
tup[0]   # => 1
tup[0] = 3  # Raises a TypeError

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

#     tuples(  lists)         
a, b, c = (1, 2, 3)     # a is now 1, b is now 2 and c is now 3
d, e, f = 4, 5, 6       # you can leave out the parentheses
# Tuples      
g = 4, 5, 6             # => (4, 5, 6)
#            
e, d = d, e     # d is now 5 and e is now 4


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

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

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

# Get all values as a list with "values()"
#   「values()」        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
#   filled_dict.get("four")      None
# (get           )

#      list         
filled_dict["four"] = 4  # now, filled_dict["four"] => 4

# 「setdefault()」                 
filled_dict.setdefault("five", 5)  # filled_dict["five"] is set to 5
filled_dict.setdefault("five", 6)  # filled_dict["five"] is still 5


empty_set = set()
#    set
some_set = set([1, 2, 2, 3, 4])   # some_set is now set([1, 2, 3, 4])

#          ,            
another_set = set([4, 3, 2, 2, 1])  # another_set is now set([1, 2, 3, 4])

#  Python 2.7  ,{}        set
filled_set = {1, 2, 2, 3, 4}   # => {1, 2, 3, 4}

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

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

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

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

# set    「^」     
{1, 2, 3, 4} ^ {2, 3, 5}  # => {1, 4, 5}

#                
{1, 2} >= {1, 2, 3} # => False

#                
{1, 2} <= {1, 2, 3} # => True

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


####################################################
## 3.     
####################################################

#           
some_var = 5

#      if  。   Python     !
if some_var > 10:
    print "some_var is totally bigger than 10."
elif some_var < 10:    #   elif       
    print "some_var is smaller than 10."
else:           #         
    print "some_var is indeed 10."


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

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

"""
「range(number)」                   
prints:
    4
    5
    6
    7
"""
for i in range(4, 8):
    print i

"""
While            
prints:
    0
    1
    2
    3
"""
x = 0
while x < 4:
    print x
    x += 1  # Shorthand for x = x + 1

#   try/except        

#  Python2.6      :
try:
    #   「raise」      
    raise IndexError("This is an index error")
except IndexError as e:
    pass    # Pass       。          
except (TypeError, NameError):
    pass    #      ,             
else:   #   try/except        。        except    
    print "All good!"   #       try         
finally: #               
    print "We can clean up resources here"

#        with  ,  try/finally       
with open("myfile.txt") as f:
    for line in f:
        print line


####################################################
## 4.   
####################################################

#   「def」         
def add(x, y):
    print "x is {0} and y is {1}".format(x, y)
    return x + y    #   return      

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

#        ,         
add(y=6, x=5)   # Keyword arguments can arrive in any order.

#                   ,    「*」        
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)   # equivalent to foo(1, 2, 3, 4)
all_the_args(**kwargs)   # equivalent to foo(a=3, b=4)
all_the_args(*args, **kwargs)   # equivalent to foo(1, 2, 3, 4, a=3, b=4)

def pass_all_the_args(*args, **kwargs):
    all_the_args(*args, **kwargs)
    print varargs(*args)
    print keyword_args(**kwargs)

#        
x = 5

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

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

set_x(43)
set_global_x(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
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5

#            
map(add_10, [1, 2, 3])   # => [11, 12, 13]
map(max, [1, 2, 3], [4, 2, 1])   # => [4, 2, 3]

filter(lambda x: x > 5, [3, 4, 5, 6, 7])   # => [6, 7]

#       list      map    
[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]


####################################################
## 5.  
####################################################

#    object       
class Human(object):

    #       。             
    species = "H. sapiens"

    #       ,           。
    #                   Python  ,         
    #       。             。
    def __init__(self, name):
        #               
        self.name = name

        #      
        self.age = 0

    #        。       「self」       
    def say(self, msg):
        return "{0}: {1}".format(self.name, msg)

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

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

    # 「property」   getter  
    #       age()      
    @property
    def age(self):
        return self._age

    #           set
    @age.setter
    def age(self, age):
        self._age = age

    #             
    @age.deleter
    def age(self):
        del self._age

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

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

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

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

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

#     
i.age = 42

#     
i.age # => 42

#     
del i.age
i.age  # => raises an AttributeError


####################################################
## 6.   
####################################################

#        
import math
print math.sqrt(16)  # => 4

#                  
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
# you can also test that the functions are equivalent
from math import sqrt
math.sqrt == m.sqrt == sqrt  # => True

# Python        python  。                 。
#                 。

#      「dir」             
import math
dir(math)

#       Python    「math.py」           ,    
#             Python     。              
#    Python    。


####################################################
## 7.   
####################################################

# Generators help you make lazy code
def double_numbers(iterable):
    for i in iterable:
        yield i + i

# A generator creates values on the fly.
# Instead of generating and returning all values at once it creates one in each
# iteration.  This means values bigger than 15 wont be processed in
# double_numbers.
# Note xrange is a generator that does the same thing range does.
# Creating a list 1-900000000 would take lot of time and space to be made.
# xrange creates an xrange generator object instead of creating the entire list
# like range does.
# We use a trailing underscore in variable names when we want to use a name that
# would normally collide with a python keyword
xrange_ = xrange(1, 900000000)

# will double all numbers until a result >=30 found
for i in double_numbers(xrange_):
    print i
    if i >= 30:
        break


# Decorators
# in this example beg wraps say
# Beg will call say. If say_please is True then it will change the returned
# message
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 :(