码迷,mamicode.com
首页 > 编程语言 > 详细

python 基础笔记

时间:2015-02-16 18:19:29      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

1,去掉了C语言中的大括号,用空格来对齐语句块。(空格一般用2个或4个,但没有限制)

2,要在py文件代码中使用中文,需要在第一行加入下面的代码:

# -*- coding: utf-8 -*-

或者是:

#coding: utf-8

3,执行python文件的命令:>>>python first.py

4,注释用#号。

5,算数运算 1/2 结果是0,  1.0/2 结果是 0.5。两个操作数都是整数,按整除处理。

指数运算符是**,print 2**3,结果是8.

6,变量不需要声明类型。s="Hello”;s=5;s=5.0。同一变量可以被多次赋予不同类型的值。

7,输出语句print

# 直接输出字符串
print "Hello World"
# 直接输出多个字符串
print "Hello World","Python","Study"
# 字符串格式化输出
print "Let‘s talk about %s." % my_name
# 整数格式化输出
print "He‘s %d cm tall." % my_height
# 多个参数的输出
print "He‘s got %s eyes and %s hair." % (my_eyes, my_hair)

%r: String (converts any Python object using repr()).

%s: String (converts any Python object using str()).

8,print语句会自动换行,若不想换行需要在最后加一个逗号(python2.x)。

print "Hello",
print "World"

9,一行代码太长,可以在行末加‘\’反斜杠换行书写。

print end1 + end2 + end3

10,\n代表换行。\是转义符,这个和C#是一致的。例如:\”可以转义双引号。

11,三个双引号中间可以放置多行语句块,并且不需要转义。

print """
There‘s something going on here.
With the three double-quotes.
We‘ll be able to type as much as we like.
Even 4 lines if we want,or 5,or 6.
"""

12,正确显示字符串中的特殊字符,可以使用\进行转义;也可以用三个引号的方式括起来,这就不需要转义了。

13,输入函数:

print "How old are you?",

age = raw_input()

等价于

age = raw_input("How old are you?")

还有一个input函数,要求输入一个python表达式,计算后会得到相应的类型。

而raw_input函数把输入都看作字符串。需要我们自己转型,int(raw_input()),这样就转成整型。

14,格式化字符串是%r,不是\r,我又犯错了。

15,获取Python 命令后面的参数,需要引入sys模块的argv。

from sys import argv

#参数赋值给下面3个变量,第一个是python文件名
pythonfile,firstArg,secondArg=argv

#或者将所有输入赋值给一个数组
allArgument=argv

16,打印文件内容是print fp.read(), 不是print fp,fp仅仅是一个文件句柄。

17,用%r进行格式化,变量为字符串的话,会在字符串两边加上单引号‘ 或双引号“。如果将字符串格式化输出到文件,还是用%s比较好。

18,函数申明用def。

# * 代表参数是不定的
def print_two(*args):
    arg1, arg2 = args
    print "arg1: %r arg2: %r" % (arg1, arg2)

# 一个参数
def print_one(arg1):
    print "arg1: %r" % arg1	

# 没有参数	
def print_none():
    print "I got nothing."

print_two("Zed","Shaw")
print_one("First!")
print_none()

19,函数可以返回多个变量,这一点确实是个亮点。

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates

start_point = 10000
beans, jars, crates = secret_formula(start_point)

20,引用模块的某个函数,比如ex25.py的openfile函数,如果引用的是import ex25,则调用的时候ex25.openfile,前面的ex25模块名不能少。如果用from ex25 import openfile 的方式的话,就可以不写ex25前缀。from ex25 import * ,可以导入ex25的所有函数,虽然和import ex25差不多,但是可以避免写前缀。

21,pop函数会删除对应索引的元素,即便是调用函数,数组的传递方式和c#一样,是引用传递,值依然会被删除掉。

22,多条件语句是 if … elif…else…

23,range(0,5) 返回的数组的值是[0,1,2,3,4],不包含5.

24,for 语句 for i in range(0,4):    print i

25,while语句 while i<5: print i   i++

26,exit(0) 正常退出程序。 from sys import exit.

27,in 测试元素在某个集合中。

>>> lst = [1, 2, 3]
>>> 1 in lst
True
>>> myStr = "you are very good"
>>> "o" in myStr
True
>>> "are" in myStr
True
>>> "dd" in myStr
False
>>> 

28,两个正斜杠\\代表向下取整除。3//2.0 == 1.0

29,yield可以实现迭代,然后在for语句中使用,这个和C#是一样的。

# yield
def getOdd(max):
    i = 1 
    while i < max:
        if i % 2 == 1:
            yield i
        i += 1 # notation: python hasn‘t ++ operation

for odd in getOdd(10):
    print odd, ",",   

30,with语句,其实和C#的using语句是差不多的。

# with
# file object implements the __enter__ and __exit__ method
# so we can use directly
with open(r"E:\temp\py\test.txt") as f:
    print f.read()

# the follow line will get a closed file, becase
# file is closed in the __exit__ method 
print f 
可以自己写个类实现__enter__ 和 __exit__方法,注意__exit__必须带有四个参数。

31,try/catch/else/finally

# try/except/else/finally
def divideNum(a, b):
    try:
        num = a / b
        raise NameError("badName") # raise a error
    except ZeroDivisionError:
        print "Divide by Zero"   
    except NameError as e:
        print "message:%s" % e.message
    except:
        print "there is an error"
        raise # re-raise the error
    else:
        print "there is no error. num=%r" % num    
    finally:
        print "this is finally block"
   
print divideNum(10, 2) 
print divideNum(10, 0)

32,要在函数中使用模块中定义的变量,需要在函数中对模块中的变量用global关键字

def change():
    global x
    x = 2
    
x = 50
change()
print "x=%d" % x    

上面的结果是2。注意:如果只是访问x的值,不加global也是可以的,但不建议这么做,这不利于代码阅读。

如果本地变量和模块变量同名了,可以用内置函数globals来访问模块变量

def change(x):
    globals()[‘x‘] = 2
    
x = 50
change(x)
print "x=%d" % x   

33,exec执行python语句,eval计算python表达式的值,结果是一种类型的变量。

# excute python statement 
exec("print ‘abc‘")
exec("a = 1 + 2")
print a
# compute python statement
n = eval("1 + 3")
# out put <type ‘int‘>
print type(n)

34,删除数组的一个元素用del语句。

lst = [1,2,3]
print lst
# delete the last element
del lst[2]
print lst
# delete all the element
del lst
# the follew line will be error
print lst

35,….

python 基础笔记

标签:

原文地址:http://www.cnblogs.com/xiashengwang/p/4294409.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!