Python

Python is powerful… and fast; plays well with others; runs everywhere; is friendly & easy to learn; is Open.

python zh_CN

Hello World

  • Install

  • cmd

C:\Users\houbinbin>python
Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 100+200
300
>>> print("hello, world")
hello, world
>>>
  • run *.py
2016/09/02  10:10                22 hello.py
               1 个文件             22 字节
               2 个目录 125,722,767,360 可用字节

D:\python>python hello.py
hello, world

the content of hello.py is:

print("hello,world");

Python Base

Input

>>> name=input();
ryo
>>> name
'ryo'
>>> print(name);
ryo
  • run *.py
D:\python>python hello.py
Please enter your name: ryo
hello,  ryo

the content of hello.py is;

name=input("Please enter your name: ");
print("hello, ", name);

Charset

  • ord & chr
>>> ord("a");
97
>>> ord("你");
20320
>>> chr(97);
'a'
>>> chr(20320);
'你'
  • encode & decode
>>> "abc".encode("utf-8");
b'abc'
>>> "你好".encode("utf-8");
b'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> "你好".encode("ascii");
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
>>> b'abc'.decode("utf-8");
'abc'
>>> b'\xe4\xbd\xa0\xe5\xa5\xbd'.decode("utf-8");
'你好'
  • len
>>> len("abc");
3
>>> len("你好");
2
>>> len("\xe4\xbd\xa0\xe5\xa5\xbd");
6
>>> len("你好".encode("utf-8"));
6

Read encode

当Python解释器读取源代码时,为了让它按UTF-8编码读取,我们通常在文件开头写上这两行:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
  • 第一行注释是为了告诉Linux/OS X系统,这是一个Python可执行程序,Windows系统会忽略这个注释;

  • 第二行注释是为了告诉Python解释器,按照UTF-8编码读取源代码,否则,你在源代码中写的中文输出可能会有乱码。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

print("中文测试");

Format

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

s1 = 72
s2 = 85
r=(s2-s1)/s1*100
print("小明成绩提高了%.1f%%"%r)

the result is:

小明成绩提高了18.1%

参考资料

廖雪峰的入门教程