Life is short, I use Python.
版本:3.6
文档:The Python Language Reference
入门:廖雪峰Python教程
环境:Win 10 / Linux
安装:sudo apt install python
基础
hello,world!
print('hello,world!')
Python之禅
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
指定解释器,对Linux
#!/usr/bin/python3
输入输出
a = input()
print(a)
数据类型:整数,浮点数,字符串
格式化输入输出(与C语言一致):%d
%f
%s
%x
整数浮点运算:*
/
//
%
print(10/3)
print(10//3)
print(10%3)
字符串与编码
指定编码格式,确保编辑器使用UTF-8 without BOM编码
# -*- coding: utf-8 -*-
list(可变) & tuple(不可变对象) & dict(可变)& set(可变)
A = [1, 2, 'hello', 'world']
B = (1,23,5,'shit')
C = {
1:10, 'hello':'world'}
D = {
1,2,3}
条件分支
a = 5
if a > 10:
print('a > 10')
elif a > 5:
print('5 < a <= 10')
else:
print('a <= 5')
循环
A = [1,2,3]
for a in A:
print(a)
n = 1
while n < 10:
print(n)
n = n+1
缩进控制代码块层次,推荐使用空格而不是制表符。
函数
内建函数
函数定义
def power2(x):
return x*x
print(power2(10))
默认参数,从后往前添加(与C++类似)
def power(x, n = 2):
res = 1
while n > 0:
res *= x
n = n-1
return res
可变参数
# variable arguments, pass arguments as a tuple
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n*n
return sum
print(calc(1,2,3,4))
print(calc(*[1,2,3,4]))
# use * to change elements of a tuple or list into variable arguments
nums = [