第一章 基础知识
1.1 解释器的安装
下载地址:http://www.python.org/getit/
一路下一步,完成安装
修改path,添加安装路径
命令行运行显示如下结果:
1.2 交互式解释器
示例:helloworld.py
print("Hello World !中国")
运行示例程序:
Python ~/helloworld.py
1.3 算法
1.4 数字和表达式
>>> 1+1
2
>>> 1/2
0
>>> 1//2
0
#只执行普通和除法
>>> from __future__ import division
>>> 1/2
0.5
#执行整除
>>>1//2
0
#取余
>>> 1%2
1
#乘方
>>> 2**3
8
>>>
长整型数
>>>1%2
1
>>> 2**3
8
>>>
十六进制和八进制
>>>0xAF
175
>>>010 有问题
8
1.5 变量
>>> x=3
>>> x*2
6
1.6 语句
>>>2*2
4
>>> print (2*2);
4
1.7 获取用户输入
>>> input ("input an number:");
input an number: 30
'30'
1.8 函数
#乘方
>>> 2**3
8
>>> pow(2,3)
8
#绝对值
>>>abs(-10)
10
>>>round(1.0/2.0)
1
1.9 模块
>>> import math
>>> math.floor(32.9)
32
>>>math.sqrt(9)
3.0
#虚数
>>>import cmath
>>>cmath.sqrt(-1)
1j
#复数
>>>(1+3j)*(9+4j)
(-3+31j)
1.10 保存并执行程序
//hello.py文件内容如下:
Print(“helloworld!”);
//命令行窗口运行如下命令
C:\Users\Administrator>pythond:\workspace_python\hello.py
hello world!
让文件直接运行
Linux中,在文件中添加#!/usr/bin/env python (python的绝对路径)
注释用#
1.11 字符串
单引号和双引号打印字符串没有区别
>>>"helloworld"
'helloworld'
>>> 'helloworld'
'helloworld'
>>>
当引号中有单引号时需要\进行转义
>>>'i\'m a shabi'
"i'm a shabi"
>>>
拼接字符串
>>> "hello"'world'
'helloworld'
>>> "hello"' world'
'hello world'
>>> "hello"" world"
'hello world'
#也可以用以下方式拼接字符串
>>> "hello"+' world'
'hello world'
#将python值转换为字符串的三种方法:str repr 和反引号(`)
Input和raw_input的比较(暂没发现有什么区别)
长字符串 用三个引号表示’’’
>>> print('''hello
... wrold''');
hello
wrold
原始字符串
>>>print("c:\note"); #错误方法
c:
ote
>>> print(r"c:\note"); #使用原始字符串的正确方法
c:\note
>>>
Unicode字符串 u”字符串”