python学习笔记(一)之入门

1、python的安装

官网下载.exe文件直接安装即可,在安装过程中选择加入环境变量,就不用在安装后再去增添环境变量了。
本文选择的是python3.6版本,没有选择2.7版本。

2、启动python解释器和运行.py文件

安装过程中选择创建桌面图标连接,在安装过后可以直接点击图标即可,或者在cmd下输入python即可。
我们可以看到如下图所示内容:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 

在python解释器中>>>是主提示符,...是次要提示符。

>>> str = '''python
...is cool!'''
>>> print(str)
python
is cool!

python程序文件是以.py结尾,运行该文件可以在cmd中转到代码目录,然后使用以下命令即可:

> python filename.py

也可以使用各种编辑器如pycharm,可以在编辑器中直接执行。

3、print语句和“Hello World!”

在python3.6 版本中,print语句采用print()的形式。

#!/usr/bin/env python
# _*_coding:utf-8_*_
# name:'first.py'
print('Hello World!')

执行first.py

> python first.py
Hello World!

也可以直接打开python解释器直接输入:

>>> print('Hello World!')
Hello World!

在解释器中“_”有着特别的意义:表示最后一个表达式的值,是表达式而不是普通语句。

>>> _
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_' is not defined
>>> str = 'Hello World!'
>>> str
'Hello World!'
>>> _
'Hello World!'

print语句的标准化输出

采用的是类似于C语言的printf()类似的写法:

>>> print('I want to say %s' % (str))
I want to say Hello World!

此外,在了解到stdout:

>>> import sys
>>> sys.stdout.write('Hello World!')
Hello World!>>>

这里的sys.stdout.write()不会在句尾自动回车。

疑问

在学习到标准化输出时,了解到重定向,采用的是linux中的>>符号:
运行下一段代码时出现错误:

#!/usr/bin/env python
import sys
logfile = open('log.txt', 'w+')
ser = sys.stderr
print >> logfile, 'Hello World!'
print >> ser, 'stderr'
logfile.close()

输出错误:

Hello World!
Traceback (most recent call last):
  File "G:/Code/python/fan.py", line 6, in <module>
    print >> logfile, 'Hello World!'
TypeError: unsupported operand type(s) for >>: 'builtin_function_or_method' and '_io.TextIOWrapper'. Did you mean "print(<message>, file=<output_stream>)"?

Process finished with exit code 1

怀疑是平台的问题,之后再linux上测试了一下,没有问题:

$ python fan.py
stderr
$ cat log.txt
Hello World!

至于具体原因还不知,望哪位大神告知!

输入与input()内建函数

python使用input()函数进行程序输入,它读取标准输入,并将读取到的数据复制给指定的变量。在这之中你可以使用int()内建函数将用户输入的字符串转换为整型。

>>> name = input('Please input your name:')
Please input your name:yt
>>> num = input('Please input your num:')
Please input your num:22
>>> print('Your name is %s' % (name))
Your name is yt
>>> print('Your age is %d' % (num))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
>>> print('Your age is %d' % (int(num)))
Your age is 22
>>> print('Your age is %s' % (num))
Your age is 22

可见input()得到的标准化输入为字符串,当需要整型数值是需要使用int()内建函数。可以使用help(input)查看帮助信息:

>>> help(input)
Help on built-in function input in module builtins:

input(prompt=None, /)
    Read a string from standard input.  The trailing newline is stripped.
    
    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.
    
    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.

在python2中使用的是raw_input()函数,查看帮助信息会发现其标准化输入为字符串,输出也为字符串:

Help on built-in function raw_input in module __builtin__:

raw_input(...)
    raw_input([prompt]) -> string  

    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.
(END)

注释

python使用的和其他的unix-shell脚本的注释一样都是:#.

# Author:yt
# 标注作者

此外,在函数中的注释使用的是双引号;

#!/usr/bin/env python

def test(x):
    "This is a test function"
    print('The result is %d' % (x+x))
test(1)
$ python3 fan.py
The result is 2

需要注意最好在脚本开始加上这两句代码:

#!/usr/bin/env python 指定代码执行程序
# _*_coding:utf-8_*_ 指定编码格式

操作符

主要包括算术操作符、比较操作符和逻辑操作符。
算术操作符:

+   加
-   减
/   算术除
*   乘
//  相除取整
%   取余
**  乘方
>>> 5/3
1.6666666666666667
>>> 5//3
1
>>> 5%3
2
>>> 5**3
125

比较操作符:
< > == <= >= != <>
python目前支持两种不等于比较操作符,但是对于2和3支持却不相同:

$ python
Python 2.7.13 (default, Mar 13 2017, 20:56:15)
[GCC 5.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 5!=1
True
>>> 5<>1
True
----------------------------------------------------------
$ python3
Python 3.6.1 (default, Mar 21 2017, 21:49:16)
[GCC 5.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 5!=1
True
>>> 5<>1
  File "<stdin>", line 1
    5<>1
      ^
SyntaxError: invalid syntax

逻辑操作符:
and or not
有一个特殊的现象:

True
>>> 3<4 and 4<5
True

变量与赋值

python的变量名是大小敏感的,其命名是以字母开头,大小写皆可,在加上数字和下划线。
python是动态语言,不需要预先声明变量的类型,其类型和值在被赋值的那一刻就已经被初始化了。
python支持增量赋值,即:

>>> n = 10
>>> n += 10
>>> n
20

但是并不支持自增与自减。

数字

主要包括:有符号整型、长整型、布尔值、浮点值和复数
eg:
long 27879898L -7867L
complex 6.23+1.5j 0+1j 1+0j

其中长整型在3.6版本应该发生了变化:

$ python3、
Python 3.6.1 (default, Mar 21 2017, 21:49:16)
[GCC 5.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> nj = 1231321L
  File "<stdin>", line 1
    nj = 1231321L
                ^
SyntaxError: invalid syntax
-----------------------------------------------------------
$ python
Python 2.7.13 (default, Mar 13 2017, 20:56:15)
[GCC 5.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> nj = 182391283L
>>>

更具体的需要去查询文档。

此外还包括第六种数字类型:decimal用于十进制浮点数,python2.4之后已经增加了。

>>> import decimal
>>> decimal.Decimal(1.1)
Decimal('1.100000000000000088817841970012523233890533447265625')
>>> print(decimal.Decimal('1.1'))
1.1

字符串

Python中的字符串被定义为引号之间的字符集合。python支持使用成队的单引号或者双引号,三引号可以用来包含特殊字符。使用索引和切片可以得到子字符串。字符索引从0开始,最后一个字符索引为-1.

#!/usr/bin/env python
# _*_coding:utf-8_*_
str1 = "python"
str2 = "cpython"

print(str1)
print(str2)
print(str1[::-1])

for i in range(len(str1)):
    print(str1[i])

for i in range(len(str2)):
    print(str2[:i+1])

输出:

C:\Users\yanta\AppData\Local\Programs\Python\Python36\python.exe G:/Code/python/1.py
python
cpython
nohtyp
p
y
t
h
o
n
c
cp
cpy
cpyt
cpyth
cpytho
cpython

Process finished with exit code 0

列表和元组

列表和元组可以当成普通的“数组”,能够保存任意数量的任意类型的Python对象。和数组一样,可通过数字索引访问元素,且索引从0开始。依然可以切片运算。

区别:list用中括号[]包裹,元素个数和值可以改变。tuple是使用小括号()包裹,不可改变,可以看成只读的列表。

list = [1, 2, 3, 4]
tuple = ('a', 'b', 'c', 'd')

print(list[::-1])
print(tuple[::-1])

for i in range(len(list)):
    print(list[i])

for i in range(len(tuple)):
    print(tuple[i])

for i in range(len(list)):
    print(list[:i+1])

for i in range(len(tuple)):
    print(tuple[:i+1])

输出结果:

[4, 3, 2, 1]
('d', 'c', 'b', 'a')
1
2
3
4
a
b
c
d
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
('a',)
('a', 'b')
('a', 'b', 'c')
('a', 'b', 'c', 'd')

字典

字典是python的映射数据类型,有键值对构成。值可以为任意类型的python对象,字典元素用大括号({ })包裹。

# 字典
dict = {'name': 'yt', 'age': '17'}

print(dict.keys())

dict['name'] = 'boy'
print(dict)
for key in dict:
    print(dict[key])

输出结果:

dict_keys(['name', 'age'])
{'name': 'boy', 'age': '17'}
boy
17

这里的dict.keys()在2.7和3.6版本中有所变化:

Python 2.7.13 (default, Mar 13 2017, 20:56:15)
[GCC 5.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> dict = {'name': 'yt', 'age': '17'}
>>> dict.keys()
['age', 'name']
-----------------------------------------
$ python3
Python 3.6.1 (default, Mar 21 2017, 21:49:16)
[GCC 5.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> dict = {'name': 'yt', 'age': '17'}
>>> dict.keys()
dict_keys(['name', 'age'])

代码块缩进对齐

python的代码块书写时不要靠小括号(())和花括号({ })来区分代码块区域的,而是直接使用缩进的方式,通用的缩进距离是4。
在解释器中输入代码也要注意缩进:

>>> for i in range(3):
... print(i) #无缩进
  File "<stdin>", line 2
    print(i)
        ^
IndentationError: expected an indented block
>>> for i in range(3):
...     print(i)  #有缩进
...
0
1
2

语句

if语句

语法如下:

if expression:
    pass

特别注意缩进和if语句后的:.

if expression1:
    pass1
elif expression2:
    pass2
else:
    pass3

while循环

语法如下:

while expression:
    pass

for循环

python中的for循环与传统的for循环不一样,更像shell脚本中的foreach迭代。每次选取迭代对象中的一个。

>>> for i in [1, 2, 3, 4]:
...     print(i)
...
1
2
3
4

此外,for循环经常与range()内建函数一起使用:

list = ['a', 'b', 'c', 'd']

for i in range(3):
    print(i)

for i in range(len(list)):
    print(list[i])

输出结果:

0
1
2
a
b
c
d

列表解析

就是你可以在这一行中使用一个for循环将所有的值放到一个列表中;

>>> [x**2 for x in range(4)]
[0, 1, 4, 9]

还可以加入过滤条件:

>>> [x**2 for x in range(4) if not x%2]
[0, 4]
>>> [x**2 for x in range(4) if  x%2]
[1, 9]

文件与内建函数open()

python可以进行文件访问:
open()函数可以打开文件,并且可以指定使用什么方式:

myfile = open('filename', 'r,w,a,b,[+]')

其中‘+’表示读写,‘b’表示二进制,默认为‘r’。如果执行成功,一个文件对象句柄会被返回。后续文件操作必须通过此文件句柄进行。

文件对象有一些方法,如readlines()和close(),通过句点标识法访问。

logfile = open('log.txt', 'r')
for eachline in logfile:
    print(eachline)
logfile.close()

执行结果:

$ python3

Python 3.6.1 (default, Mar 21 2017, 21:49:16)

[GCC 5.4.0] on cygwin

Type "help", "copyright", "credits" or "license" for more information.

错误与异常

主要就是将代码封装进入try-except语句中就可以了。try之后是你打算管理的代码,expect之后则是处理错误的代码。

# python3.6
try:
    logfile = open('log.txt', 'r')
    for eachline in logfile:
        print(eachline)
    logfile.close()
except IOError:
    print('file open error')
# python2.7
try:
    logfile = open('log.txt', 'r')
    for eachline in logfile:
        print(eachline)
    logfile.close()
except IOError, e:
    print('file open error:', e)

从商可以看到两个版本中还是有多不同的,也可以使用as来达到同样的效果:

try:
    logfile = open('log.txt', 'r')
    for eachline in logfile:
        print(eachline)
    logfile.close()
except IOError as e:
    print('file open error', e)

当删除log.txt后可以看到异常:

file open error [Errno 2] No such file or directory: 'log.txt'

此外在还可以增加else语句,else语句表示当没有异常,try后代码语句执行成功后,执行else后的语句;而且在执行异常处理expect语句后可以执行再finaily语句。

try:
    logfile = open('log.txt', 'r')
    for eachline in logfile:
        print(eachline)
    logfile.close()
except IOError as e:
    print('file open error', e)
else:
    print('Open log.txt sucessful!')
finally:
    print('IOError ...')

输出结果:

$ python3

Python 3.6.1 (default, Mar 21 2017, 21:49:16)

[GCC 5.4.0] on cygwin

Type "help", "copyright", "credits" or "license" for more information.

Open log.txt sucessful!

函数

定义函数语法:

def functionName([arguments]):
    "说明语句"
    pass

调用函数:

functionName(arg)

此外,参数可以设置默认值

def test(name = 'yt'):
    print(name)

test('hehe')
test()

测试结果:

hehe
yt

定义类语法:

class ClassName(base_class[es]):         
    "optional documentation string"          
    static_member_declarations          
    method_declarations 

eg:

class test(object):
    name = 'yt'
    def __init__(self, num = 17):
        self.age = num
        print('age is ', num)

    def show(self): 
        print(self.name, ' is ', self.age, 'years old!')
        print(self.__class__.__name__)

foo = test() #定义类后需要创建实例
foo.show()  #再调用方法

输出:

age is  17
yt  is  17 years old!
test

模块

模块实际上就是一个python程序文件,包括可执行代码、函数和类或者其他的东西组合。

当你创建一个python源文件,模块的名字就是不带.py后缀的文件名。

模块的导入方法:

import module
from module improt method

eg:

>>> import sys
>>> sys.stdout.write('Hello World!')
>>> Hello World!

补充

dir([obj]):描述对象的属性,如果没有提供参数,则会显示全局变量的名字

>>> dir(3)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'dict', 'i']
posted @ 2017-10-26 21:35  水木梵华  阅读(393)  评论(0编辑  收藏  举报