来源
老早就听说有python这种语言,这是知道很流行,而且,爬虫非常好写。作为曾今在爬虫中深受其害的本帅来说。是由必要研究一下python这操作。
开始学习
进入start开始学习。
bala bala 一些必要前奏
然后就到了MovingToPythonFromOtherLanguages,看了下介绍文章,其实没看完。
得到信息
- 空格和缩进在python中很重要。
python中的list表示
Python indexes and slices for a six-element list.
Indexes enumerate the elements, slices enumerate the spaces between the elements.
Index from rear: -6 -5 -4 -3 -2 -1 a=[0,1,2,3,4,5] a[1:]==[1,2,3,4,5]
Index from front: 0 1 2 3 4 5 len(a)==6 a[:5]==[0,1,2,3,4]
+---+---+---+---+---+---+ a[0]==0 a[:-2]==[0,1,2,3]
| a | b | c | d | e | f | a[5]==5 a[1:2]==[1]
+---+---+---+---+---+---+ a[-1]==5 a[1:-1]==[1,2,3,4]
Slice from front: : 1 2 3 4 5 : a[-2]==4
Slice from rear: : -5 -4 -3 -2 -1 :
b=a[:]
b==[0,1,2,3,4,5] (shallow copy of a)
两个查阅目录
Python 2.4 Quick Reference
Python Module Index
python特点
- 交互式 -- 及时反馈
- 应用广泛
- 多用途
- 易学易读
python的原意是:大蟒蛇
编写特点
- 非局限式语法
- 无明确声明
- 支持oop
- 强大的debug功能
下载须知
选择对应操作系统以及系统的寻址方式:
web-based installer 是需要通过联网完成安装的
executable installer 是可执行文件(*.exe)方式安装
embeddable zip file 嵌入式版本,可以集成到其它应用中。
上面3种途径,如果有网络,选择web-based;
我的windows64版,所以选择了Windows x86-64 web-based installer
运行简单代码
把含有python.exe文件的路径添加到环境变量中。
写好如下代码:
## world.py
print("hello, world!")
## cal.py
print('Interest Calculator:')
amount = float(input('Principal amount ?'))
roi = float(input('Rate of Interest ?'))
years = int(input('Duration (no. of years) ?'))
total = (amount * pow(1 + (roi / 100) , years))
interest = total - amount
print('\nInterest = %0.2f' %interest)
控制台运行
PS D:\git\pythonTest> python .\world.py
hello, world!
PS D:\git\pythonTest> python .\cal.py
Interest Calculator:
Principal amount ?11
Rate of Interest ?0.1
Duration (no. of years) ?2
Interest = 0.02
基础学习
自动化程序,批量修改,跨平台支持,解释型语言
传参
脚本的名称以及参数都通过sys模块以字符串列表形式放在argv参数中,使用时需要导入sys模块。
_
在python 里面表示上一次的结果
在python中缩进来表示代码块indentation is Python’s way of grouping statements.
语句
while a < 100:
a = a + 100
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
... else:
... print('More')
...
>>> for w in words[:]: # Loop over a slice copy of the entire list.
... if len(w) > 6:
... words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
/**
range(5, 10)
5, 6, 7, 8, 9
range(0, 10, 3)
0, 3, 6, 9
range(-10, -100, -30)
-10, -40, -70
*/
>>> print(range(10))
range(0, 10)
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
>>> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
pass
Statements
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
Defining Functions
方法传递方式为引用传递,不是值传递。
>>> def fib(n): # write Fibonacci series up to n
... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)
i = 5
def f(arg=i):
print(arg)
i = 6
f()
5
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
def cheeseshop(kind, *arguments, **keywords): # (*name must occur before **name.)
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", keywords[kw])
Lambda Expressions
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
编码格式 Intermezzo: Coding Style
-
Use 4-space indentation, and no tabs.
4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). Tabs introduce confusion, and are best left out.
-
Wrap lines so that they don’t exceed 79 characters.
This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.
Use blank lines to separate functions and classes, and larger blocks of code inside functions.
When possible, put comments on a line of their own.
Use docstrings.
Use spaces around operators and after commas, but not directly inside bracketing constructs:
a = f(1, 2) + g(3, 4)
.Name your classes and functions consistently; the convention is to use
CamelCase
for classes andlower_case_with_underscores
for functions and methods. Always useself
as the name for the first method argument (see A First Look at Classes for more on classes and methods).Don’t use fancy encodings if your code is meant to be used in international environments. Python’s default, UTF-8, or even plain ASCII work best in any case.
Likewise, don’t use non-ASCII characters in identifiers if there is only the slightest chance people speaking a different language will read or maintain the code.