您的位置:首页 > 编程语言 > Python开发

2014-4-5安装python以及基础知识

2014-04-05 10:15 253 查看
1.下载安装

从python官网下载python2.7.6

https://www.python.org/download/releases/2.7.6 建议用迅雷下载 会比较快

2.交互式解释器 运行一步 输出一下
print "hello world"
按下回车键 就会输出 hello world
>>>提示符
输入 help查看帮助

3.数字和表达式
>>>2+2
4
//输入2+2 会得到4
加减乘同上

>>>1/2
0
整数除以整数 结果只留下整数 去掉余数或者小数

>>>1.0/2
0.5
只要其中含有一个浮点数 值会为浮点数
如果希望Python只执行普通的除法 可以加上
>>>from _future_ import division

取余 >>>10/3
3 除法 结果为3

>>>10%3
1 取余 结果为1

幂(乘方)
>>>2**3
8
2的3次方

>>>-3**2
-9
>>>(-3)**2
9
乘方的优先级高于一元减运算符(-)

4.长整型
普通整数不能大于2147 483 647 也不能小于(2147 483 647)
再大的话 建议写成111111111111111000L 加个L转换为长整形 建议用L不建议用小写l 跟数字1相似

5. 十六进制和八进制
>>>0xAD //十六进制
175
>>>010 //八进制
8

6.变量
>>>x=3
>>>x*2
6
变量名:字母 数字 下划线

7.获得用户输入
>>> input("the meaning of life:")
the meaning of life:43
//此行原本是the meaning of life: 输入43后回车后显示如下
43

8.函数
>>>2**3
8

>>>pow(2,3)
8
使用的是函数

>>>abs(-10)
10
>>>round(1.0/2.0)
1.0
//round四舍五入
//floor向相邻小的数取整
//ceil向相邻小的数取整

9.模块
>>>import math
>>>math.floor(32.9)
32.0

>>>import math
>>>math.ceil(32.9)
33.0
//floor向相邻小的数取整
//ceil向相邻小的数取整

另外一种导入方式
>>>from math import sqrt
>>>sqrt(9)
3.0
使用了"from模块import函数"就不需要使用模块名为前缀(math.sqrt(9))

如果需要计算负数的平方根的时候 需要使用cmath模块

10.保存和执行程序
关闭包含程序的窗口 在idle 里面 File->new新建一个纯文本编辑器 写入代码 然后另存为xx.py
测试的时候 在idle 里面 File->open打开文件 按下ctrl+f5即可
name=raw_input("what is your name:")
print "hello,"+name+"!"
按下ctrl+f5
what is your name:hellen(hellen是输入的)
hello,hellen!

在dos窗口也可以打开
C:\>cd C:/Python27/zpy

C:\Python27\zpy>name.py
what is your name:tom
hello,tom!

想双击打开怎么办?
一般双击打开 就只能看到一个黑窗口一闪而过加上这行代码即可
raw_input("Press <enter>")

11.注释
单行注释用#
多行注释用""" """或者''' '''
三个双引号 或者三个单引号

12. 字符串
单双引号
'let's go!'
'let\'s go!'
需要转义

字符串拼接
>>>"hello"+"world"
hello world

str函数 可将值转换为合理形式的字符串
>>>print str("hello,world")
hello world

>>>print str(1000L)
1000
发生了转换

repr 创建一个字符串以合法的python表达式的形式来表示值 类似于原样打印
>>>print repr("hello,world")
'hello world'

>>>print repr(1000L)
1000L
不发生转换

repr(x)也可以用`x`来表示
>>> temp=42
>>> print "the temperature is "+temp

Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
print "the temperature is"+temp
TypeError: cannot concatenate 'str' and 'int' objects
>>> print "the temperature is"+`temp`
the temperature is 42
#错误是因为无法判断字符串与数字是相加还是拼接
改为repr 就以字符串形式拼接

input 与raw_input
如果使用input 需要用户输入的时候带上'' 有点强人所难了
raw_input会将用户所有的输入作为原始数据
建议使用raw_input!!!!

字符串太长??
1.用三个单引号或者三个双引号代替引号
print '''good morning sir.
hello li!'''

2.普通字符串句尾加\ 会转义换行符 忽略掉
>>>print "hello,\
world!"
hello world
3.原始字符串
print r'C:\xp'
会打印原始字符串 而不是转义
里面也可以转义 所以 最后一个字符不能是\'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: