Python复习笔记

太久没动程序了,参加Kaggle:Predict Future Sales,顺便将之前学的快速复习一下,在此做个摘抄笔记。

Python print()函数生成Loading….

语法

以下是 print() 方法的语法:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

参数

  • objects – 复数,表示可以一次输出多个对象。输出多个对象时,需要用 , 分隔。
  • sep – 用来间隔多个对象,默认值是一个空格。
  • end – 用来设定以什么结尾。默认值是换行符 \n,我们可以换成其他字符串。
  • file – 要写入的文件对象。
  • flush – 输出是否被缓存通常决定于 file,但如果 flush 关键字参数为 True,流会被强制刷新。
1
2
3
4
5
6
7
8
import time
print("---RUNOOB EXAMPLE : Loading 效果---")
print("Loading",end = "")
for i in range(20):
print(".",end = '',flush = True)
time.sleep(0.5)

来源:https://www.runoob.com/python3/python-func-print.html

help()函数显示自建函数说明

看程序一目了然:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def least_difference(a, b, c):
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
return min(diff1, diff2, diff3)
help(least_difference)
>>Help on function least_difference in module __main__:
least_difference(a, b, c)
#j加上函数注释
def least_difference(a, b, c):
"""Return the smallest difference between any two numbers
among a, b and c.
>>> least_difference(1, 5, -5)
4
"""
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
return min(diff1, diff2, diff3)
help(least_difference)
>>Help on function least_difference in module __main__:
least_difference(a, b, c)
Return the smallest difference between any two numbers
among a, b and c.
>>> least_difference(1, 5, -5)
4

总结:加了注释的函数使用help()会展现说明(即函数本身注释说明)。

max()函数调用自建函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def mod_5(x):
"""Return the remainder of x after dividing by 5"""
return x % 5
print(
'Which number is biggest?',
max(100, 51, 14),
'Which number is the biggest modulo 5?',
max(100, 51, 14, key=mod_5),
sep='\n',
)
>>
Which number is biggest?
100
Which number is the biggest modulo 5?
14

来源:https://www.kaggle.com/colinmorris/functions-and-getting-help

字符串易冲突点

1
2
3
4
5
6
7
8
9
What you type... What you get example print(example)
\' ' 'What\'s What's up?
\" " "That's \"cool\" That's "cool"
\\ \ "A mountain: /\\" A mountain: /\
\n "1\n2 3" 1
2 3
hello = "hello\nworld" 对等 triplequoted_hello = """hello
world"""

str.split()相反对等str.join()

1
2
3
4
5
6
7
8
datestr = '1956-01-31'
year, month, day = datestr.split('-')
>>
1956 01 31
'/'.join([month, day, year])
>>
'01/31/1956'

str.format()多种展示方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#直接调用
"{}, you'll always be the {}th planet to me.".format(planet, position)
#切片调用,可配合运算符等
"{} weighs about {:.2} kilograms ({:.3%} of Earth's mass). It is home to {:,} Plutonians.".format(
planet, pluto_mass, pluto_mass / earth_mass, population,
)
#索引调用
s = """Pluto's a {0}.
No, it's a {1}.
{0}!
{1}!""".format('planet', 'dwarf planet')
print(s)

来源:https://www.kaggle.com/colinmorris/strings-and-dictionaries

待续….

---------------本文终---------------

文章作者:刘俊

最后更新:2020年05月23日 - 21:05

许可协议: 转载请保留原文链接及作者。