现在的位置: 首页 > 编程语言 > 正文

Python基础:数据类型、变量定义、输入/输出、逻辑、函数/模块(导入)/类、异常处理

2018年10月06日 编程语言 ⁄ 共 2775字 ⁄ 字号 评论关闭

一、变量定义/注释

1.1 变量定义同C语言
         字母、数字、下划线
         字母或下划线开始
         区分大小写
        name = "Tom"
1.2 注释
        #
        “”:一种特别的注释,在模块、类或函数的起始添加一个字符串
二、数据类型

2.1 python对象

        身份:该对象的内存地址。 通过id()来得到。

        类型:该对象的值类型。通过type()来得到。

        值:

2.2 类型

        数字  ( 整型、长整型、浮点数、复数)

        字符串、列表、 元组、字典

        文件、类型、集合、布尔值、None

        函数/方法、模块、类

2.3 列表

        字符串只能有字符组成,而且是不可变的。

        列表中可以是任意类型的Python对象,且可变。 比C语言中的数组更灵活。

2.4 元组

        元组与列表的区别是:元组中的元素值是不可变的。

2.5 字典

        字典是映射类型key-value。

2.6 类型

2.7 列表、元组、字典示例

#!/usr/bin/env python

#List []
print "----------------------List---------------------"
aList = [123, "abc", 4.5, ["inner", "List"], 7-9j]

print "aList:", aList
print "aList[0]:", aList[0]
aList[0] = 100
print "aList[:3]:", aList[:3]
print "aList[3][1]:", aList[3][1]


#Tuple ()
print "----------------------Tuple---------------------"
aTuple = (123, "abc", 4.5, ["inner", "Tuple"], 7-9j)

print "aTuple:", aTuple
#aTuple[0] = 100
print "aTuple[3][1]:", aTuple[3][1]


#Dicr {}
print "----------------------Dict---------------------"
aDict = {"name":"Tom", "Port":80}

print "aDict:", aDict
print "aDict[name]:", aDict["name"]

        结果:

三、输入/输出

3.1 输入

        print

        输入格式化使用:%

3.2 输出

        raw_input()

        默认是字符串,可以用int()内建函数将字符串转为整数。

3.3. 示例

#!/usr/bin/env python

#input
version = raw_input("please input python version:")

#output
print "%s version is %d." % ("Python", int(version)) # int() change str to int

四、逻辑

4.1 if-elif-else

#!/usr/bin/env python

num = -1
if num < 0:
        print "%d is less than 0." % num
elif num > 0:
        print "%d is greater than 0." % num
else:
        print "%d is equal 0." % num

4.2 while

#!/usr/bin/env python

count = 0
while count < 5:
        print "the index is:", count  # must have ","
        count += 1


import time
while True:             # True
        print "test."
        time.sleep(1)       

4.3 for

#!/usr/bin/env python

nameList = ["Tom", "Bob", "Lucy"]

for name in nameList:
        print name

for index in range(len(nameList)):
        print nameList[index]

4.4 break、continue、pass

        break,continue同C语言。

        pass表示该条件下不做任何事,没有pass会报语法错误。

#!/usr/bin/env python

count = 0

if count == 0:
        print "count is 0."
else:
        pass

五、函数/模块(导入)/类

5.1  函数

        见下一节5.2

5.2 模块

        add.py

#/usr/bin/env python

def add(x=4):        #default value
        return x+x

5.3 导入

        2种导入方式:

        模块名 + 模块内函数名:

#!/usr/bin/env python

import add  # add.py

print add.add()
print add.add(4.2)
print add.add("hello")

        直接模块内函数名调用:

#!/usr/bin/env python

from add import *  # add.py

print add()
print add(4.2)
print add("hello")

5.4 类

#!/usr/bin/env python

class tclass:
        "this is a test class"
        var = 100
        def output(self):  # must have self
                print "var:", self.var

tc = tclass()
tc.output()

六、异常处理

6.1 异常处理

try-except:

        try如果没有异常,忽略except语句继续执行;

        try如果有异常,找到合适的except执行,try子句的剩余语句被忽略。 (except没有返回,继续向后执行)

        找except,会一个一个找,找不到就向上层交给调用者处理,如果到顶层还没找到对应处理器,就认为这个异常是未处理的。
try-finally:

        无论异常是否发生,都会执行finally的代码。

6.2 三种情况

        没有异常处理:test.py   

#!/usr/bin/env python


f = open("file.txt", "r")

print "success."

        try-except 异常处理:test01.py  

#!/usr/bin/env python


try:
        f = open("file.txt", "r")
except IOError,e:
        print e

print "success."

        try-finally 异常处理:test02.py  

#!/usr/bin/env python


try:
        f = open("file.txt", "r")
finally:
        print "finally"

print "success."

6.3 结果

        文件存在,没有异常:

        文件不存在,打开异常:

抱歉!评论已关闭.