13个你不知道的Python技巧( 二 )

while-else  吗?这个 else 语句会在你的循环没有中断地运行完后执行,如果中途中断了循环 , 则不会执行 。
# for-elsefor x in range(5):    print(x)else:    print("Loop Completed") # executed# while-elsei = 0 while i < 5:    breakelse:    print("Loop Completed") # Not executed8. f-string的强大a = "Python"b = "Job"# Way 1string = "I looking for a {} Programming {}".format(a, b)print(string) # I looking for a Python Programming Job#Way 2string = f"I looking for a {a} Programming {b}"print(string) # I looking for a Python Programming Job9. 改变递归深度这是 Python 的另一个重要特性,它可以让您设置 Python 程序的递归限制 。看一下下面的代码示例以更好地理解:
import sysprint(sys.getrecursionlimit()) # 1000 默认值sys.setrecursionlimit = 2000print(sys.getrecursionlimit) # 200010. 条件赋值条件赋值功能使用三元运算符,可以在特定条件下为变量赋值 。看看下面的代码示例:
x = 5 if 2 > 4 else 2print(x) # 2y = 10 if 32 > 41 else 24print(y) # 2411. 参数解包您可以解压缩函数中的任何可迭代数据参数 。看看下面的代码示例:
def func(a, b, c):    print(a, b, c)x = [1, 2, 3]y = {'a': 1, 'b': 2, 'c': 3}func(*x) # 1 2 3func(**y) # 1 2 312. 呼唤世界(没啥用)import __hello__ # 你猜输出啥?# other codeimport osprint(os) # <module 'os' from '/usr/lib/python3.6/os.py'>13. 多行字符串此功能将向您展示如何编写没有三重引号的多行字符串 。看看下面的代码示例:
# 多行字符串str1= "Are you looking for free Coding " "Learning material then " "welcome to py2fun.com"print(str1) # Are you looking for free Coding Learning material then welcome to Medium.com# 三重引号字符串str2 = """Are you looking for free CodingLearning material then welcome to py2fun.com"""print(str2) #和上面的是不同的 , 换行也会被输出 。小节这些就是今天分享的 Python 的 13 个特性,希望你觉得这篇文章读起来有趣且有用 。




推荐阅读