A Brief Introduction to Python

2019-01-17  本文已影响0人  ningfreeman

1. Flow Control

1.1 If

import sys
if sys.version_info.major < 3:
    print("Version 2.X")
elif sys.version_info.major > 3:
    print("Future")
else:
    print("Version 3.X")
Version 3.X

1.2 Loop

1.2.1 For

for i in "Hello":
    print(i)
H
e
l
l
o

1.2.2 While

prod = 1
i = 1
while i < 10:
    prod = prod * i
    i += 1
print(prod)
362880

1.2.3 Break / Continue

for n in range(2, 10):
    if n % 2 == 0:
        print("Found an even number ", n)
        continue
    if n > 5:
        print("Greater Than 5!")
        break
Found an even number  2
Found an even number  4
Found an even number  6
Greater Than 5!

1.2.4 Iterators & Generators **

python = iter("Python")
print(python)
for i in python:
    print(i)
<str_iterator object at 0x000000B4F4F73198>
P
y
t
h
o
n
def reverse(data):
    for index in range(len(data)-1, -1, -1):
        yield data[index]

nohtyp = reverse("Python")
print(nohtyp)
for i in nohtyp:
    print(i)
<generator object reverse at 0x000000B4F618FF10>
n
o
h
t
y
P

1.3 Comprehensions

1.3.1 List

s = [2 * x for x in range(10) if x ** 2 > 3]
print(s)
[4, 6, 8, 10, 12, 14, 16, 18]
pairs = [(x, y) for x in range(2) for y in range(2)]
print(pairs)
[(0, 0), (0, 1), (1, 0), (1, 1)]

1.3.2 Set

s = {2 * x for x in range(10) if x ** 2 > 3}
print(s)
{4, 6, 8, 10, 12, 14, 16, 18}
pairs = {(x, y) for x in range(2) for y in range(2)}
print(pairs)
{(0, 1), (1, 0), (0, 0), (1, 1)}

1.3.3 Dict

ls = {s: len(s) for s in ["Python", "Javascript", "Golang"]}
print(ls)
sl = {v: k for k, v in ls.items()}
print(sl)
{'Golang': 6, 'Javascript': 10, 'Python': 6}
{10: 'Javascript', 6: 'Python'}

2. Functions

2.1 Definition

def f():
    """
    return 'Hello World!'
    """
    return "Hello World!"

print(f())
print(f.__doc__)
Hello World!

    return 'Hello World!'

2.2 Default Arguments

def f(name="World"):
    """
    return 'Hello, $name'
    """
    return "Hello, {}!".format(name)

print(f())
print(f("Python"))
Hello, World!
Hello, Python!

2.3 Keyword Arguments

def f(v, l="Python"):
    """
    return '$v, $l'
    """
    return "{}, {}".format(v, l)

print(f("Hello"))
print(f("Bye", "C++"))
Hello, Python
Bye, C++

2.4 Arbitrary Arguments

def f(*args, con=' & '):
    print(isinstance(args, tuple))
    print("Hello", con.join(args))
    
f("Python", "C", "C++", con = '/')
True
Hello Python/C/C++
def f(*args, **kargs):
    print("args ", args)
    print("krags ", kargs)
    print("FP: {} & Scripts: {}".format(kargs.get("fp"), '/'.join(args)))
    
f("Python", "Javascript", ms="C++", fp='Haskell')
args  ('Python', 'Javascript')
krags  {'ms': 'C++', 'fp': 'Haskell'}
FP: Haskell & Scripts: Python/Javascript


2.5 Lambda

pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs)
pairs.sort(key=lambda pair: pair[0])
print(pairs)
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]


2.6 Decorator

def log(f):
    def wrapper():
        print("Hey log~")
        f()
        print("Bye log~")
    return wrapper

@log
def fa():
    print("This is fa!")
    
def fb():
    print("This is fb!")
fb = log(fb)

fa()
print("*" * 10)
fb()
Hey log~
This is fa!
Bye log~
**********
Hey log~
This is fb!
Bye log~


3. Class (OOP)

3.1 Class

class Animal:
    """
    This is an Animal
    """
    def fly(self):
        print("I can fly!")
        
a = Animal()
a.fly()
print(a.__doc__)
I can fly!

    This is an Animal


3.2 _init_ & self

class Animal:
    """
    This is an Animal
    """
    def __init__(self, can_fly=False):
        print("Calling __init__() when instantiation!")
        self.can_fly = can_fly
        
    def fly(self):
        if self.can_fly:
            print("I can fly!")
        else:
            print("I can not fly!")
            
            
a = Animal()
a.fly()

b = Animal(can_fly = True)
b.fly()
Calling __init__() when instantiation!
I can not fly!
Calling __init__() when instantiation!
I can fly!


3.3 Instance

class Animal:
    pass
class Human:
    pass

a = Animal()
b = Human()
print(isinstance(a,Animal))
print(isinstance(b,Animal))
True
False


3.4 Inheritance

class Animal:
    """
    This is an Animal
    """
    def __init__(self, can_fly=False):
        self.can_fly = can_fly
        
    def fly(self):
        if self.can_fly:
            print("I can fly!")
        else:
            print("I can not fly!")
            

class Dog(Animal):
    """
    This is a Dog
    """
    def bark(self):
        print("Woof!")
        
d = Dog()
d.fly()
d.bark()
I can not fly!
Woof!


3.5 Override

class Animal:
    """
    This is an Animal
    """
    def __init__(self, can_fly=False):
        self.can_fly = can_fly
        
    def fly(self):
        if self.can_fly:
            print("I can fly!")
        else:
            print("I can not fly!")
            
class Bird:
    """
    This is a Bird
    """
    def fly(self):
        print("I am flying high!")
        
bird = Bird()
bird.fly()
I am flying high!


上一篇下一篇

猜你喜欢

热点阅读