python学习笔记(1)--《python基础教程》第1章内容总结

来源:互联网 发布:mysql日期格式化 编辑:程序博客网 时间:2024/05/16 07:54

最近再看《python基础教程》,为了巩固学习,决定每看完一章进行总结一次

平台:Windows,版本3.3.2

1.打印print,在这个版本中(貌似是3.0以后都是这样),print要加括号,不加括号会报错

如:

>>> print("Hello World")
Hello World
>>> print(2*2)
4
>>> 
2.除法(/)运算,3.0以前进行整除运算,3.0以后就自动进行浮点数运算了,如果想进行整除,那就用(//)

如:

>>> 1/3
0.3333333333333333
>>> 2//3
0

>>> 1.0//2.0

0.0

3.取模运算(%),对浮点数也适用

如:

>>> 1.2%2.5
1.2

4.大数,3.0以后不用加L,python会自动处理的

如:

>>> 1000L
SyntaxError: invalid syntax
>>> 42343255353553545+4738478347
42343260092031892

>>> print(1000L)
SyntaxError: invalid syntax
>>> print(423523535345435)
423523535345435
>>> 

5.十六进制和八进制

十六进制前加0x,八进制要加0o(0和小(大)写的o)

如:

>>> 0x12
18
>>> 0O12
10

6.变量赋值

>>> x=3
>>> print(x)
3
>>> 

7.用户输入input,3.0以后raw_input就没有了,如果想输入整数,然后进行运算,需要强制转换

>>> string=input("enter a word:")
enter a word:hello
>>> print(string)
hello
>>> x=int(input("x=:"))
x=:12
>>> y=int(input("y=:"))
y=:12
>>> x*y
144
>>> 

8.幂运算(**),pow函数

>>> 2**3
8
>>> pow(2,3)
8

如果需要对结果进行取模,可以再加个参数

如:

>>> pow(2,3,3)
2
>>> 

9.round函数(四舍五入,如果需要精度,可以加第二个参数)和abs函数(绝对值)

>>> round(3.22222,3)
3.222
>>> abs(-1.2)
1.2
>>> 

10.用import导入模块

>>> import math
>>> math.sqrt(9)
3.0
>>> math.floor(9.3)
9
>>> 

如果不想在每次使用函数时都写上模块,可以使用“from模块import函数”

>>> from math import sqrt
>>> sqrt(9)
3.0
>>> 

10.计算负数平方根,用从cmath模块

>>> from cmath import sqrt
>>> sqrt(-1.0)
1j
>>> 

这种情况下,就不用使用普通的sqrt函数了,可以用import cmath

11.字符串单引号,双引号

单独使用时,两者没什么区别,但是单引号里不能包含单引号,双引号里不能包含双引号(这个道理应该类似于C/C++中的注释符/**/),r如果需要嵌套,要加上反斜线进行转义

如;

>>> print("hello"she"world")
SyntaxError: invalid syntax
>>> print("hello'she'world")
hello'she'world
>>> print("hello\"she\"world")
hello"she"world
上面说的双引号里不能包含双引号,不准确,

如:

>>> print("hello" "orld")
helloorld

这种情况属于字符串拼接;另外一种字符串拼接就是用+

如:

>>> print("hello"+"world")
helloworld
>>> 

12.str()和repr()

前者是把值转换成合理形式的字符串,属于一种类型,目的是方便用户理解;后者是创建一个字符串,是个函数,,目的是用合法表达式的形式来表示值;看下面的结果

>>> temp=str("hello world")
>>> print(temp)
hello world
>>> temp=repr("hello world")
>>> print(temp)
'hello world'
>>> 

13.原始字符串,以r开头,不会把反斜线当作转义字符

>>> print(r'let\' go')
let\' go

注意最后一个字符不能是反斜线,否则python不知道是否应该结束字符串

如:

>>> print(r'let\'s go\')
      
SyntaxError: EOL while scanning string literal
>>> 


这一章内容主要就是这些,一些问题的原因还不清楚,希望通过接下来的学习深入了解python

0 0
原创粉丝点击