python学习笔记(一)基础入门

python怎么读

第一个,我们要弄明白这个怎么读:
英[ˈpaɪθən],美[ˈpaɪθɑ:n]
我们一般读英式读音—-派森

Hello, World例子

我学习的环境是Ubuntu,所以直接上手来使用python的学习了。

我们学习一种语言的第一个例子,一般都是Hello, World,那python的Hello, World样例如下:
先在目录下新建hello_world.py文件,内容如下:

#!/usr/bin/python

print "hello world"

我们执行:

python hello_world.py

输出:

hello world

其实我们也可以执行:

chmod +x hello_world.py

给hello_world.py添加执行权限,那我们就可以直接使用命令:

./hello_world.py

执行此文件了,同样此文件输出:

hello world

中文编码

如果我们想输出中文,如hello_world.py文件:

#!/usr/bin/python

print "输出"

执行此文件,输出:

  File "./hello_world.py", line 3
SyntaxError: Non-ASCII character '\xe8' in file ./hello_world.py on line 3, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

这是因为Python中默认的编码格式是 ASCII 格式,在没修改编码格式时无法正确打印汉字,所以在读取中文时会报错。

解决方法为只要在文件开头加入 # -- coding: UTF-8 -- 或者 #coding=utf-8 就行了。
如:

#!/usr/bin/python
#-*-coding:UTF-8-*-

print "输出"

则输出:

输出

问题解决了。

注释

python单行注释采用 # 开头,多行注释采用三个单引号(”’)或三个双引号(“”“)

#!/usr/bin/python
#-*-coding:UTF-8-*-
# 第一个注释
# 文件名:hello_world.py

'''
这是多行注释,使用单引号。
这是多行注释,使用单引号。
这是多行注释,使用单引号。
'''

"""
这是多行注释,使用双引号。
这是多行注释,使用双引号。
这是多行注释,使用双引号。
"""

print "hello world" # 单行注释

print 默认输出是换行的,如果要实现不换行需要在变量末尾加上逗号:

#!/usr/bin/python
#-*-coding:UTF-8-*-
print '------不换行输出-------'
print "hello world 01",
print "hello world 02",
print "-------换行输出--------"
print "hello world 03"
print "hello world 04"

输出:

------不换行输出-------
hello world 01 hello world 02 -------换行输出--------
hello world 03
hello world 04

行和缩进

学习 Python 与其他语言最大的区别就是,Python 的代码块不使用大括号 {} 来控制类,函数以及其他逻辑判断。python 最具特色的就是用缩进来写模块。

缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量,这个必须严格执行。

变量类型

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

  • Numbers(数字)
  • String(字符串)
  • List(列表)
  • Tuple(元组)
  • Dictionary(字典)

Numbers(数字)

Number 数据类型用于存储数值,使用del语句删除一些 Number 对象引用。

#!/usr/bin/python
#-*-coding:UTF-8-*-

var_Number01 = 1;
print "var_Number01:",var_Number01;
print "---------------------------"
var_Number02 = 10;
print "var_Number02:",var_Number02;
print "---------------------------"
del var_Number01;
del var_Number02;

输出:

var_Number01: 1
---------------------------
var_Number02: 10
---------------------------

String(字符串)

字符串是 Python 中最常用的数据类型,可以使用引号(‘或”)来创建字符串。
这个样例给了一些常用字符串使用:

#!/usr/bin/python
#-*-coding:UTF-8-*-
import string

a = "Hello"
b = "Python"
print "a:", a
print "b:", b

print "a + b 输出结果:", a + b
print "a * 2 输出结果:", a * 2
print "a[1] 输出结果:", a[1]
print "a[1:4] 输出结果:", a[1:4]

print "string.upper(a):", string.upper(a);
print "len(a):", len(a);

if( "H" in a) :
    print "H 在变量 a 中"
else :
    print "H 不在变量 a 中"

if( "M" not in a) :
    print "M 不在变量 a 中"
else :
    print "M 在变量 a 中"

List(列表)

列表是Python中最基本的数据结构。列表中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。

#!/usr/bin/python
#-*-coding:UTF-8-*-

list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];

print "list1[0]: ", list1[0]
print "list1[-1]: ", list1[-1]
print "list1: ", list1
print "len(list1): ", len(list1)
print "list1+list2: ", list1+list2
print "'physics' in list1: ", 'physics' in list1
print "max(list1): ", max(list1)

list1.append(5)
print "list1: ", list1
list1.sort()
print "list1: ", list1

print "list2[1:5]: ", list2[1:5]

输出:

list1[0]:  physics
list1[-1]:  2000
list1:  ['physics', 'chemistry', 1997, 2000]
len(list1):  4
list1+list2:  ['physics', 'chemistry', 1997, 2000, 1, 2, 3, 4, 5, 6, 7]
'physics' in list1:  True
max(list1):  physics
list1:  ['physics', 'chemistry', 1997, 2000, 5]
list1:  [5, 1997, 2000, 'chemistry', 'physics']
list2[1:5]:  [2, 3, 4, 5]

Tuple(元组)

Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

#!/usr/bin/python
#-*-coding:UTF-8-*-

tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );

print "tup1[0]: ", tup1[0]
print "tup2[1:5]: ", tup2[1:5]

# 以下修改元组元素操作是非法的。
# tup1[0] = 100;

# 创建一个新的元组
tup3 = tup1 + tup2;
print tup3;

输出:

tup1[0]:  physics
tup2[1:5]:  (2, 3, 4, 5)
('physics', 'chemistry', 1997, 2000, 1, 2, 3, 4, 5, 6, 7)

Dictionary(字典)

字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中。键必须是唯一的,但值则不必。值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

#!/usr/bin/python
#-*-coding:UTF-8-*-

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];

dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];

print "dict.keys(): ", dict.keys();
print "dict.values(): ", dict.values();

输出:

dict['Name']:  Zara
dict['Age']:  7
dict['Age']:  8
dict['School']:  DPS School
dict.keys():  ['School', 'Age', 'Name', 'Class']
dict.values():  ['DPS School', 8, 'Zara', 'First']

条件语句

Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。

#!/usr/bin/python
#-*-coding:UTF-8-*-

name = 'luren'
if name == 'python':
  print 'name == python'
else:
  print 'name != python'

print '--------------------------------'
num = 1
if num == 3:
  print 'num==3'
elif num == 2:
  print 'num==2'
elif num == 1:
  print 'num==1'
elif num < 0: 
  print 'num<3'
else:
  print 'else'

输出:

name != python
--------------------------------
num==1

循环语句

while

#!/usr/bin/python
#-*-coding:UTF-8-*-

count = 0
while (count < 9):
  print 'The count is:', count
  count = count + 1
print "Good bye!"

输出:

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

for

#!/usr/bin/python
#-*-coding:UTF-8-*-

for letter in 'Python':
  print '当前字母 :', letter
print "-----------------------------"
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: 
  print '当前水果 :', fruit

输出:

当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : h
当前字母 : o
当前字母 : n
-----------------------------
当前水果 : banana
当前水果 : apple
当前水果 : mango

函数

函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。函数能提高应用的模块性,和代码的重复利用率。
函数语法如下:

def functionname( parameters ):
   "函数_文档字符串"
   function_suite
   return [expression]

例如:

#!/usr/bin/python
#-*-coding:UTF-8-*-

def printme( str ):
   "打印传入的字符串到标准显示设备上"
   print str
   return

# 调用函数
printme("我要调用用户自定义函数!");
printme("再次调用同一函数");

输出:

我要调用用户自定义函数!
再次调用同一函数

异常处理

捕捉异常可以使用try/except语句,如:

try:
<语句>        #运行别的代码
except <名字>:
<语句>        #如果在try部份引发了'name'异常
except <名字>,<数据>:
<语句>        #如果引发了'name'异常,获得附加的数据
else:
<语句>        #如果没有异常发生

try-finally 语句无论是否发生异常都将执行最后的代码

try:
<语句>
finally:
<语句>    #退出try时总会执行
raise
#!/usr/bin/python
#-*-coding:UTF-8-*-

try:
    fh = open("testfile", "w")
    fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
    print "Error: 没有找到文件或读取文件失败"
else:
    print "内容写入文件成功"
    fh.close()

输出:

内容写入文件成功

查看文件:

cat testfile 
这是一个测试文件,用于测试异常!!
chmod -w testfile
ll
-r--r--r-- 1 android android   47 May 19 21:56 testfile

再执行此文件,则输出:

Error: 没有找到文件或读取文件失败

触发异常:
我们可以使用raise语句自己触发异常,raise语法格式如下:

raise [Exception [, args [, traceback]]]

参考资料

1.python学习网站
http://www.runoob.com/python/python-tutorial.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hfreeman2008

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值