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

Python学习之一 Python基础知识

2012-03-12 15:46 453 查看
1、print函数,在3.0一下直接 print 42可以将42打印出来,但在

3.0以后print作为函数,需要print(42)这样使用。

2、input函数, x = input("x:")

3、输入一个很大的数,python会自动转换为长整型,比如:100000000000 输出:100000000000L

4、//整除号 1.0//2=0 1/2=0 1.0/2=0.5 1/2.=0.5

5、**幂运算符 2**3=8 -3**2=-9 (-3)**2=9,也可以用函数代替pow,pow(2,3) = 2**3 = 8

6、导入模块 import math 导入后可以使用math模块中的函数,如:math.floor(2.5) = 2.0

7、导入函数 from math import sqrt 将sqrt函数导入,然后就可以直接使用sqrt函数了

8、使用变量引用函数 foo=math.sqrt 则可以 foo(4) = 2

9、python中将数值转换成字符串三种方式:

a、str函数 print str(1000L) 输出:1000

b、repr函数 print repr(1000L) 输出:1000L,将数值转换成标准的pytho表达式,创建一个新的字符串

c、反引号 ‘’ 功能与repr函数相同,在3.0以后不可用

10、python中两种输入函数

a、input函数,python默认用户输入的是标准的python表达式。

例:name = input("enter name:"), 当执行时,
用户输入:tom,会报错,
用户输入:"tom" 正常执行。

b、raw_input函数。他会把用户输入的当作原数据,然后将其放入字符串中。上面例子中在这里输入tom是可运行的

例:>>> input("input a number:")
input a number: 3
3
>>> raw_input("input a number:")
input a number: 3
'3' #输出的是字符串
>>> x = input("input a number:")
input a number:2
>>> y = input("input a number:")
input a number:3
>>> x + y
5
>>> x = raw_input("input a number:")
input a number:2
>>> y = raw_input("input a number:")
input a number:3
>>> x + y
'23'

写程序时,尽量使用raw_input函数

11、长字符串、原始字符串和Unicode

a、长字符串

如果需要写一个很长的字符串,他需要跨多行,那么,可以使用三个引号来代替普通引号。

例:>>> print '''abcdef

ghijkl'

mnopkrst''

uvwxyz

123456'''

输出:

abcdef

ghijkl'

mnopkrst''

uvwxyz

123456

普通字符串也可以跨行,如果一行之中最后一个字符为反斜线,那么换行符本身就“转义”了,也就被忽略了。

例:>>> print 'hello \

world'

hello world

>>> #同样适用于表达式

>>> print 1 + 2 \

+ 4 + 5

12

>>> print \

'hello world'

hello world

b、原始字符串

原始字符串不会把反斜线当成特殊字符,在原始字符串中输入的每个字符串都会与书写的方式保持一致。

例:

>>> print "c:\nabcddskf"

c:

abcddskf

>>> print r"c:\nabcdfds"

c:\nabcdfds

不能在原始字符串结尾输出反斜线。除非对最后的反斜线进行转义。否则会出错:

例:>>> print r"hello\"

SyntaxError: EOL while scanning single-quoted string

>>> print r"hello\\"

hello\\

如果想要一个字符串是以反斜线结尾:

例:>>> print "hello" '\\'

hello\

c、Unicode字符串

Unicode字符串可以表示在字符更多,在python3.0中,所有字符串都是Unicode字符串。

例:>>> print u"hello"

hello

本章函数:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: