python语法初学1

我装的是centos7,自带了python2.7,输入python,再输入help()即可看到,里面介绍了一个教程的网址。我就是照着这个教程的网址来学的:https://docs.python.org/2.7/tutorial/

Python是个解释型语言,与通过编译器把代码转换成机器码的编译型语言(如c)不同,它是把代码翻译成中间代码然后给解释器运行,类似shell。

2.2.1编码方式的声明

一般写在第一行,格式如下:

# -*- coding: encoding -*-

默认encoding为ASCII,如果有类似shell的shebang,则写在第二行,如下

#!/usr/bin/env python

# -*- coding: cp1252 -*-

 

3.1.1输入数字和加减乘除可以直接计算

一些细节官方教程的例子已经足够了

>>> 17 / 3  # int / int -> int
5
>>> 17 / 3.0  # int / float -> float
5.666666666666667
>>> 17 // 3.0  # explicit floor division discards the fractional part
5.0
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17

With Python, it is possible to use the ** operator to calculate powers [1]:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128

 

等号可以用于给变量赋值,如下

>>> width = 20

>>> height = 5 * 9

>>> width * height

900

若变量未经定义就使用会报错

一些实例

,这里 _  表示上次输出的变量值,round函数显然是取后四位小数

另外,也支持复数计算,这里不做了解。

 

3.1.2字符

>>> 'doesn\'t'

"doesn't"    #显然,此处\ 为转义

字符也可以用双引号引用

当字符包含单引号时,输出为双引号包含这个字符,否则,输出为单引号,print可将输出的字符引号省略,且使转义字符生效,例子如下

>>> '\"'

'"'

>>> '\''

"'"

>>> s="first\nsecond"

>>> print s

first

second

 

输入多行字符,可用三个单引号或多引号来包含字符串,若不想换行被输入进字符串,可先输入转义字符,再输入换行。

 

字符常量的连接:对于两个或多个字符串常量,可以直接连接,但若常量有*这个操作符或者是字符串变量,需要加号连接,例子如下

>>> 'a'*3+'b''b'+s

'aaabbcd'

 

字符串可用类似数组的方式引用其中的字母,例子如下

>>> word = 'Python'

>>> word[0]  # character in position 0

'P'

>>> word[5]  # character in position 5

'n'

标号可以为负数,-1代表最后一个字母

 

还允许截取一段子字符串

>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)

'Py'

>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)

'tho'

 

括号左边不填默认为0,右边默认为数组大小,引用时不能越界,但是引用子字符串可以越界,如

>>> word[4:42]

'on'

 

这些引用虽然像数组,但不是变量,不能被赋值,len(string_name)可求长度

 

Unicode的先略过

List,可以保存一整串数字或字符,可以像string一样被引用,连接,且可以被改变,可以删除,增加,例子如下

>>> l=[1,2,3,4]

>>> l

[1, 2, 3, 4]

>>> l[0]

1

>>> l[0]=0

>>> l

[0, 2, 3, 4]

>>> l[1:4]=[1,2,3]

>>> l

[0, 1, 2, 3]

>>> l.append(4)

>>> l

[0, 1, 2, 3, 4]

>>> s=['a','b','c']

>>> s[1:2]=[]

>>> s

['a', 'c']

经测试,数字和字符混合的列表类型也是可以的

 

也可以创建包含list的list

>>> s=['a','b','c']

>>> s[1:2]=[]

>>> s

['a', 'c']

>>> l=[1,'c']

>>> l

[1, 'c']

>>> l1=['a','b','c']

>>> l2=[1,2,3]

>>> x=[l1,l2]

>>> x[0]

['a', 'b', 'c']

>>> x[1]

[1, 2, 3]

>>> x[0][0]

'a'

>>> x[0][1]

'b'

>>> x[1][2]

3

 

 

3.2给了个while循环生成斐波那契数列的例子,这里不重复,几个注意如下:几个变量的赋值可以写成a,b,c=1,2,3的形式,while判断的条件与c类似,但是注意while后的类型也可以为string和list,只要长度不为0均为真,while 条件:后面的内容必须用空格或换行,且一个while后面的一整块内容需保持一样的空格数,最后用空格表示该while代码块结束。

If与elif,例子如下

>>> if x < 0:

...     x = 0

...     print 'Negative changed to zero'

... elif x == 0:

...     print 'Zero'

... elif x == 1:

...     print 'Single'

... else:

...     print 'More'

...

More

 

For语句类似于shell

... words = ['cat', 'window', 'defenestrate']

>>> for w in words:

...     print w, len(w)

...

cat 3

window 6

defenestrate 12

 

range生成list,看看例子差不多了

>>> range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> range(5, 10)

[5, 6, 7, 8, 9]

>>> range(0, 10, 3)

[0, 3, 6, 9]

 

关于break的例子,本来想不贴的,但是那个例子有个与c不同的地方,如下

>>> for n in range(2, 10):

...     for x in range(2, n):

...         if n % x == 0:

...             print n, 'equals', x, '*', n/x

...             break

...     else:

...         # loop fell through without finding a factor

...         print n, 'is a prime number'

...

2 is a prime number

3 is a prime number

4 equals 2 * 2

5 is a prime number

6 equals 2 * 3

7 is a prime number

8 equals 2 * 4

9 equals 3 * 3

 

这里的else是与for对应的,当for顺利执行完后则运行else里的内容

 

Continue类似c,略

pass就是啥都不做

 

 

4.6函数定义

def fun(para1,para2…):

     statement1

     statement2

     …

       #与之前类似,用缩进表示代码块

 

另外,函数名可以像变量一样赋值,并调用,相当于可以给函数重命名

 

4.7.1默认参数值,函数可以定义默认参数值,然后在调用时,默认参数值可以有选择的填写

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):

    while True:

        ok = raw_input(prompt)

        if ok in ('y', 'ye', 'yes'):

            return True

        if ok in ('n', 'no', 'nop', 'nope'):

            return False

        retries = retries - 1

        if retries < 0:

            raise IOError('refusenik user')

        print complaint

 

上面用到了关键字in,用来判断一个序列是否包含了某个值

4.7.2 关键字参数,上述函数,第一个没有赋默认值,称为位置参数,第二个赋了默认值,则成为关键字参数,具体调用实例如下

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):

parrot(1000)                                          # 1 positional argument

parrot(voltage=1000)                                  # 1 keyword argument

parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments

parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments

parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments

parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

 

4.7.3

之前注释忘记说了,python单行注释用#,多行用”””comment…”””

关于**args和*args参考下面这篇文章

https://www.cnblogs.com/shitaotao/p/7609990.html

4.8 PEP8讲了代码规范,简略的说几个:用四个空格做代码缩进,,在操作符和符号前面用空格

猜你喜欢

转载自blog.csdn.net/sinat_30457013/article/details/89523390