python学习笔记(一)

来源:互联网 发布:codeblocks c语言 编辑:程序博客网 时间:2024/06/10 01:41

1.输出文本

>>>print“Hello,World!”

Hello,World!

2.当做计算器使用

>>>2+2

4

整数除以整数,取整数部分。

>>>2/3

0

参与出发两个数中有一个为浮点数,结果为浮点数

>>>1.0/2

0.5

>>>1/2.0

0.5

若希望python只执行普通除法,加上以下语句,或者直接在解释器里面执行它:

>>>from_future_import division

长整数:(普通整数不能大于2 147 483 647)

>>>1000000000000000000

1000000000000000000L

十六进制和八进制

>>>0xAF

175

>>>010

8

3.变量赋值

>>>x=3

>>>x*2

6

注意:变量名可以包括字母、数字和下划线(_)。变量不能以数字开头,如9a

4.获取用户输入;input函数

>>> x=input("x:")
x:2
>>> y=input("y:")
y:3
>>> print x*y
6

5.函数

>>> round(1.0/2.0)
1.0

round函数把浮点数四舍五入为最接近的整数值。若想取小,则需要调用模块中的floor函数

6.模块(import导入)

>>> import math
>>> math.floor(32.9)
32.0

>>> int((math.floor(32.9)))
32

import导入的另一种方式

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

7.复数与cmath

>>> import cmath
>>> cmath.sqrt(-1)
1j

1j为虚数

8.将文件存为.py结尾的脚本文件后,双击打开,会弹出dos窗口,但是程序运行完毕,窗口也会关掉,这时在脚本后加入一行代码即可解决:

name=raw_input("what's your name?")
print"hello. "+name+"!"

raw_input("Press<enter>")

9.注释:

#这是一行注释

10.单引号字符串和转义引号

>>> "hello,world!"
'hello,world!'

>>> 'hello,world!'
'hello,world!'

>>> "let's go!"
"let's go!"

>>> 'let's go'
SyntaxError: invalid syntax

因为python读取let之后不知道如何处理后面的s,可以使用反斜号(\)对字符串中的引号进行转义。

>>> 'let\'s go!'
"let's go!"

11.拼接字符串

>>> "let's say" ' "hello,world!" '
'let\'s say "hello,world!" '

>>> "hello. "+"world!"
'hello. world!'
>>> x="hello. "
>>> y="world!"
>>> x+y
'hello. world!'

12.字符串表示,str和repr

值被转换成字符串的两种机制:一是通过str函数,它会把值转换为合理形式的字符串,以便用户理解。二是repr函数,会创建一个字符串,它以合法的python表达式的形式来表示值。

>>> print repr("hello.world!")
'hello.world!'
>>> print repr(100000L)
100000L
>>> print str("hello.world!")
hello.world!
>>> print str(10000L)
10000

repr(x)也可以用·x·来表示。如果希望打印一个包含数字的句子,可以用反引号(· ·,就是那个在1左边的符号)

>>> temp =42
>>> print "the temperature is "+`temp`
the temperature is 42

>>> temp=42
>>> print "the temperature is "+ repr(temp)
the temperature is 42

13.input和raw_input 函数区别

input会假设用户输入的是合法的python表达式。

>>> name=input("what's your name?")
what's your name?melody

会报错....输入'melody'才行

raw_input函数会把所有的输入当做原始数据,然后将其放入字符串中。

>>> raw_input("enter a number: ")
enter a number: 3
'3'

14.长字符串、原始字符串和Unicode


0 0