python crash course

interpreter

builtin types

builtin data type

flow control

n = 11
if n <= 10:
    print("n <= 10")
elif n < 20:
    print("10 < n < 20")
else:
    print("n >= 20")
print("print many star!")
n = 10
while n > 0:
    print('*' * n)
    n = n - 1
animals = ['dog', 'cat', 'snake']
for animal in animals:
    print(f'this is {animal}')

for i in range(1, 10, 2):
    print('*'*i)
for i in range(5):
    print(f'start loop i: {i}')
    if i == 2:
        print('i == 2, continue')
        continue
    if i == 3:
        print('i == 3, pass')
    for j in range(5):
        print(f'>>>> start loop in j: {j}')
        if i*j > 8:
            print(f'>>>>>> {i}*{j} > 8, break')
            break
        print(f'>>>>>> this is {i}*{j}')
        print(f'>>>> end loop in j: {j}')
    print(f'end loop in i: {i}')

function

how to define function, with default value

def this_is_a_function(normal_arg, default_arg=3, another_default_arg=4):
    """this is a docstring"""
    print(f'normal_arg: {normal_arg}, default_arg: {default_arg}, another_default_arg: {another_default_arg}')

>>> this_is_a_function(1)
normal_arg: 1, default_arg: 3, another_default_arg: 4
>>> this_is_a_function(1, 10)
normal_arg: 1, default_arg: 10, another_default_arg: 4
>>> this_is_a_function(1, another_default_arg=10)
normal_arg: 1, default_arg: 3, another_default_arg: 10

how to define function, with arbitrary arguments and keywords

def that_is_a_function(normal_arg, *args, **keywords):
    print(f'normal_arg: {normal_arg}, args: {args}, keywords: {keywords}')
>>> that_is_a_function(1)
normal_arg: 1, args: (), keywords: {}
>>> that_is_a_function(1, 2, 3)
normal_arg: 1, args: (2, 3), keywords: {}
>>> that_is_a_function(1, 2, 3, name='jhon', age=18)
normal_arg: 1, args: (2, 3), keywords: {'name': 'jhon', 'age': 18}
>>> that_is_a_function(1, *[2, 3], **{'name':'jhon', 'age':18})
normal_arg: 1, args: (2, 3), keywords: {'name': 'jhon', 'age': 18}

lambda

f = lambda x: x % 2 == 0
l = [1,2,3,4,5]
even_numbers = filter(f, l)
print(list(filter(f, l)))
>>> [2, 4]

class

class People:
    my_attr = 'class variable shared by all instances'

    def __init__(self, name):
        self.name = name
        self._age = 0

    def say_hi(self):
        print(f'this is a instance method, call with instance.say_hi(). name: {self.name}')

    def say_hello(self):
        print("say hello from People")

    @classmethod
    def cls_method(cls):
        print('this is a class method, call with People.cls_method')

    @staticmethod
    def sts_method():
        print('this is a static method, call with People.sts_method')

    def _my_protect_method(self):
        print('this is a protected method, only me and my subinstance can call')

    def __my_private_method(self):
        print('this is a private method, do not call it. But if you have to, I will not stop you.')

    @property
    def age(self):
        return self._age

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

class Teacher(People):
    teacher_attr = 'teacher attr'

    def teach(self):
        print("good good study, day day up")

    def say_hello(self):
        print("say hello from Teacher")



>>> p = People('jhon')
>>> p.say_hello()
say hello from People
>>> p.say_hi()
this is a instance method, call with instance.say_hi(). name: jhon
>>> p._my_protect_method()
this is a protected method, only me and my subinstance can call
>>> People.cls_method()
this is a class method, call with People.cls_method
>>> People.sts_method()
this is a static method, call with People.sts_method
>>> p.age
0
>>> p.age = 10
>>> p.age
10
>>> dir(p)
['_People__my_private_method', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_age', 'age', 'cls_method', 'my_attr', 'name', 'say_hello', 'say_hi', 'sts_method']
>>> p._People__my_private_method()
this is a private method, do not call it. But if you have to, I will not stop you.


>>> t = Teacher('david')
>>> t.say_hi()
this is a instance method, call with instance.say_hi(). name: david
>>> t._my_protect_method()
this is a protected method, only me and my subinstance can call
>>> t.__my_private_method()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Teacher' object has no attribute '__my_private_method'
>>> t.say_hello()
say hello from Teacher
>>> t.age
0
>>> t.my_attr
'class variable shared by all instances'
>>> t.teacher_attr
'teacher attr'