python的一些语法糖

# 1."else" after the "while","for":
#   the "else" object will be executed when no "break" was executed in "while","for" object before
# num = [1, 2, 3, 4]
# mark = 0
# while mark < len(num):
#     n = num[mark]
#     if n % 2 == 0:
#         print(n)
#         # break
#     mark += 1
# else:
#     print("done")


# 2."zip" to zip two lists
# a = [1, 2, 3]
# b = ['one', 'two', 'three']
# list(zip(a, b))


# 3.推导式

#     3.1.列表推导式:[ expr for value in collection if condition ]
# strings = ['Bob', 'Tom', 'alice', 'Jerry', 'Wendy', 'Smith']
# result = [name.upper() for name in strings if len(name) > 3]

#     3.2.字典推导式:{ key_exp : value_exp for expression in iterable }
# strings = ['import', 'is', 'with', 'if', 'file', 'exception']
# result = {key: val for val, key in enumerate(strings)}

#     3.3.集合推导式:{ expression for expression in iterable }
# strings = ['a', 'is', 'with', 'if', 'file', 'exception']
# result = {len(s) for s in strings}


# 4.函数

#     4.1.默认参数值
#         需要同时设定所有参数的默认值,不能单独设定部分参数,
#         否则会报错:SyntaxError: non-default argument follows default argument
#         同时列表字典等可变数据类型不能作为默认参数值
# def do(a=1, b=1, c=1):
#     print(a, b, c)
#
#
# do()
# do(3)
# do(3, 3)
# do(3, 3, 3)

#     4.2.lambda匿名函数
# do = lambda x: x * x
# print(do(4))


# 5.super()调用父类方法
# class Father():
#     def __init__(self, name):
#         self.name = name
#         print("Father is here")
#
#
# class Son(Father):
#     def __init__(self, name, age):
#         super().__init__(name)
#         self.age = age
#
#
# a = Son('Jack', 15)
# print(a.name, a.age)
#
#
# 6.实例方法:
#       实例方法,以self作为第一个参数,当它被调用时,Python会把调用该方法的的对象作为self参数传入。
# class Person():
#     age = 15
#
#     def __init__(self, Age):
#         self.age = Age
#         print(Person.age)  # Person.age为类特征
#         print(self.age)  # self.age为对象特征
#
#
# Jack = Person(20)


# 7.{} & ".format"
#     usually used to change the format of output
# print('{} {} {}'.format(11, 22, 33))
# print('{2:2d} {0:-10d} {1:10d}'.format(11, 22, 33))
# print('{a} {b} {c}'.format(a=11, b=22, c=33))



你可能感兴趣的:(python语言)