Pythonpythonpython

Python基础

2016-04-19  本文已影响63943人  纵我不往矣

Python 基础教程

实例(Python 2.0+)

#!/usr/bin/python
print "Hello, World!";

实例(Python 3.0+)

#!/usr/bin/python
print("Hello, World!");

Python 简介

Python 是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。


Python 环境搭建

集成开发环境: PythonWin


Python 中文编码

#!usr/bin/python
#coding=utf-8
print("hello world!");

Python 基础语法

$ python test.py

以下划线开头的标识符是有特殊意义的。


Python 变量类型

exit()就可以退出

Python有五个标准的数据类型:

Python字符串

python的字串列表有2种取值顺序:

s = 'ilovepython'
s[1:5]
结果是love,第一个要,最后一个不要。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str = 'Hello World!'
print str # 输出完整字符串
print str[0] # 输出字符串中的第一个字符
print str[2:5] # 输出字符串中第三个至第五个之间的字符串
print str[2:] # 输出从第三个字符开始的字符串
print str * 2 # 输出字符串两次
print str + "TEST" # 输出连接的字符串

以上实例输出结果:

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python列表
#!/usr/bin/python
# -*- coding: UTF-8 -*-
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # 输出完整列表
print list[0] # 输出列表的第一个元素
print list[1:3] # 输出第二个至第三个的元素 
print list[2:] # 输出从第三个开始至列表末尾的所有元素
print tinylist * 2 # 输出列表两次
print list + tinylist # 打印组合的列表

以上实例输出结果:

['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Python元组
#!/usr/bin/python
# -*- coding: UTF-8 -*-
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # 输出完整元组
print tuple[0] # 输出元组的第一个元素
print tuple[1:3] # 输出第二个至第三个的元素 
print tuple[2:] # 输出从第三个开始至列表末尾的所有元素
print tinytuple * 2 # 输出元组两次
print tuple + tinytuple # 打印组合的元组

以上实例输出结果:

('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

以下是元组无效的,因为元组是不允许更新的。而列表是允许更新的:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # 元组中是非法应用
list[2] = 1000 # 列表中是合法应用
Python元字典
#!/usr/bin/python
# -*- coding: UTF-8 -*-
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # 输出键为'one' 的值
print dict[2] # 输出键为 2 的值
print tinydict # 输出完整的字典
print tinydict.keys() # 输出所有键
print tinydict.values() # 输出所有值

输出结果为:

This is one
This is two 
{'dept': 'sales', 'code': 6734, 'name': 'john'} 
['dept', 'code', 'name'] 
['sales', 6734, 'john']

Python 运算符

a**b 为10的20次方, 输出结果 100000000000000000000

if ( a == b ): print "1 - a 等于 b"
else: print "1 - a 不等于 b"
Python成员运算符
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
   print "1 - 变量 a 在给定的列表中 list 中"
else: 
   print "1 - 变量 a 不在给定的列表中 list 中"
Python身份运算符
a = 20
b = 20
if ( a is b ):
   print "1 - a 和 b 有相同的标识"
else: 
   print "1 - a 和 b 没有相同的标识"

Python 条件语句

if 判断条件: 
   执行语句……
else:
   执行语句……
if 判断条件1: 
   执行语句1……
elif 判断条件2: 
   执行语句2……
elif 判断条件3: 
   执行语句3……
else: 
   执行语句4……

Python While循环语句

#!/usr/bin/python
# -*- coding: UTF-8 -*-
var = 1
while var == 1 : # 该条件永远为true,循环将无限执行下去 
   num = raw_input("Enter a number :") 
   print "You entered: ", num
print "Good bye!"
#!/usr/bin/python
count = 0
while count < 5: 
   print count, " is less than 5" 
   count = count + 1
else: 
   print count, " is not less than 5"

注意:以上的无限循环你可以使用 CTRL+C 来中断循环。

Python for 循环语句

#!/usr/bin/python
# -*- coding: UTF-8 -*-
for letter in 'Python': # 第一个实例 
   print '当前字母 :', letter

fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # 第二个实例
   print '当前字母 :', fruit
print "Good bye!"
当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : h
当前字母 : o
当前字母 : n
当前字母 : banana
当前字母 : apple
当前字母 : mangoGood bye!
通过序列索引迭代
#!/usr/bin/python
# -*- coding: UTF-8 -*-
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)): 
   print '当前水果 :', fruits[index]
print "Good bye!"
#!/usr/bin/python
# -*- coding: UTF-8 -*-
for num in range(10,20):         # 迭代 10 到 20 之间的数字
   for i in range(2,num):          # 根据因子迭代
      if num%i == 0:               # 确定第一个因子 
         j=num/i                   # 计算第二个因子 
         print '%d 等于 %d * %d' % (num,i,j)  
         break                     # 跳出当前循环 
else:                            # 循环的 else 部分 
print num, '是一个质数'

Python pass 语句

pass

Python 数字

数据类型是不允许改变的,这就意味着如果改变数字数据类型得值,将重新分配内存空间。
以下实例在变量赋值时 Number 对象将被创建:

var1 = 1
var2 = 10

您也可以使用del语句删除一些数字对象引用。
del语句的语法是:

del var1[,var2[,var3[....,varN]]]]

Python 字符串

#!/usr/bin/python
var1 = 'Hello World!'
var2 = "Python Runoob"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]

以上实例执行结果:

var1[0]: H
var2[1:5]: ytho
Python字符串格式化
#!/usr/bin/python
print "My name is %s and weight is %d kg!" % ('Zara', 21) 

以上实例输出结果:

My name is Zara and weight is 21 kg!
Python三引号(triple quotes)
>>> hi = '''hi 
there'''
>>> hi # repr()
'hi\nthere'
>>> print hi # str()
hi
there 
>>> u'Hello\u0020World !'
u'Hello World !'

Python 列表(List)

#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
print list1;
del list1[2];
print "After deleting value at index 2 : "
print list1;
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]

Python 元组


Python 字典(Dictionary)

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
删除字典元素
#!/usr/bin/python
# -*- coding: UTF-8 -*-
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # 删除键是'Name'的条目
dict.clear(); # 清空词典所有条目
del dict ; # 删除词典 
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];

Python 日期和时间

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time; # 引入time模块
ticks = time.time()
print "当前时间戳为:", ticks

以上实例输出结果:

当前时间戳为: 1459994552.51
获取当前时间
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time
localtime = time.localtime(time.time())
print "本地时间为 :", localtime

以上实例输出结果:

本地时间为 : time.struct_time(tm_year=2016, tm_mon=4, tm_mday=7, 
tm_hour=10, tm_min=3, tm_sec=27, tm_wday=3, tm_yday=98, tm_isdst=0)
获取格式化的时间asctime():
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time
localtime = time.asctime( time.localtime(time.time()) )
print "本地时间为 :", localtime

以上实例输出结果:

本地时间为 : Thu Apr 7 10:05:21 2016
格式化日期
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time
# 格式化成2016-03-20 11:45:39形式
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
# 格式化成Sat Mar 28 22:24:24 2016形式
print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) 
# 将格式字符串转换为时间戳a = "Sat Mar 28 22:24:24 2016"
print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))

以上实例输出结果:

2016-04-07 10:25:09
Thu Apr 07 10:25:09 2016
1459175064.0
获取某月日历
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import calendar
cal = calendar.month(2016, 1)
print "以下输出2016年1月份的日历:"
print cal;

以上实例输出结果:

以下输出2016年1月份的日历: 
January 2016
Mo Tu We Th Fr Sa Su 
               1  2  3 
   4  5  6  7  8  9  10
11  12 13 14 15 16 17
18  19 20 21 22 23 24
 25 26 27 28 29  30 31

Python 函数

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 定义函数
def printme( str ): 
      "打印任何传入的字符串" 
      print str; 
      return; 
# 调用函数
printme("我要调用用户自定义函数!");
printme("再次调用同一函数");

以上实例输出结果:

我要调用用户自定义函数!
再次调用同一函数
按值传递参数和按引用传递参数
#!/usr/bin/python
# -*- coding: UTF-8 -*- 
# 可写函数说明
def changeme( mylist ): 
      "修改传入的列表" 
      mylist.append([1,2,3,4]); 
      print "函数内取值: ", mylist 
      return 
# 调用changeme函数
mylist = [10,20,30];
changeme( mylist );
print "函数外取值: ", mylist

传入函数的和在末尾添加新内容的对象用的是同一个引用。故输出结果如下:

函数内取值: [10, 20, 30, [1, 2, 3, 4]]
函数外取值: [10, 20, 30, [1, 2, 3, 4]]
参数

-以下是调用函数时可使用的正式参数类型:

#!/usr/bin/python
# -*- coding: UTF-8 -*- 
# 可写函数说明
def printinfo( arg1, *vartuple ): "打印任何传入的参数" 
      print "输出: " print arg1 
      for var in vartuple: 
           print var 
      return; 
# 调用printinfo 函数
printinfo( 10 );
printinfo( 70, 60, 50 );

以上实例输出结果:

输出:
10
输出:
70
60
50
匿名函数
#!/usr/bin/python
# -*- coding: UTF-8 -*- 
# 可写函数说明
sum = lambda arg1, arg2: arg1 + arg2; 
# 调用sum函数
print "相加后的值为 : ", sum( 10, 20 )
print "相加后的值为 : ", sum( 20, 20 )

以上实例输出结果:

相加后的值为 : 30
相加后的值为 : 40

Python 模块

import 语句
#!/usr/bin/python
# -*- coding: UTF-8 -*- 
# 导入模块
import support # 现在可以调用模块里包含的函数
support.print_func("Zara")

以上实例输出结果:

Hello : Zara
From…import 语句
例如,要导入模块fib的fibonacci函数,使用如下语句:
from fib import fibonacci
from modname import *

这提供了一个简单的方法来导入一个模块中的所有项目。然而这种声明不该被过多地使用。

命名空间和作用域
dir()函数
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 导入内置math模块
import math 
content = dir(math) 
print content;

以上实例输出结果:

['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2',
 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 
'frexp', 'hypot', 'ldexp', 'log','log10', 'modf', 'pi', 'pow',
 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
globals()和locals()函数

两个函数的返回类型都是字典。所以名字们能用keys()函数摘取。

reload()函数
reload(module_name)
在这里,module_name要直接放模块的名字,而不是一个字符串形式。
Python中的包
#!/usr/bin/python
# -*- coding: UTF-8 -*- 
def Pots(): 
      print "I'm Pots Phone" 

同样地,我们有另外两个保存了不同函数的文件:

Phone/Isdn.py 含有函数Isdn()
Phone/G3.py 含有函数G3()

现在,在Phone目录下创建file init.py:

Phone/__init__.py
from Pots import Pots
from Isdn import Isdn
from G3 import G3

当你把这些代码添加到init.py之后,导入Phone包的时候这些类就全都是可用的了。

#!/usr/bin/python
# -*- coding: UTF-8 -*- 
# 导入 Phone 包
import Phone 
Phone.Pots()
Phone.Isdn()
Phone.G3()

以上实例输出结果:

I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone
上一篇 下一篇

猜你喜欢

热点阅读