inputs
<name>, <name>,...
def <name>(<parameters>):
4个空格<block>
def get_next_target(s):
start_link = s.find('<a href=')
start_quote = s.find('"', start_link)
end_quote = s.find('"', start_quote +1)
url = s[start_quote+1, end_equpte]
return <expression>, <expression>, ...
def sum(a,b):
a = a+b
return a
可以是两个数字inputs,outputs两个数的和
可以是两个字符串inputs,outputs两个字符串的拼接
print sum(2,2)
print sum('hello' , ' world!')
4
hello world!
Q:定义一个程序square,输入一个数字,输出平方
A:
def square(n):
return n*n
Q:定义一个程序sum3,3个inputs,outputs3个数字的和
A:
def sum3(a,b,c):
return a+b+c
Q:定义一个程序abbaize,两个字符串inputs,输出第一个第二个第二个第一个字符串abbaize('a', 'b') --> abba
A:
def abbaize(a,b):
return a+b+b+a
Q:定义程序 find_second,inputs两个字符串,搜索字符串和目标字符串,outputs在搜索字符串中第二次出现目标字符串的位置
A:
def find_second(search , target):
first = search.find(target)
return search.find(target , first + 1)
==, < , >= ,… <number><operate><number>
if:
if <TestExpression>:
<Block>
------------------------
if <TestExpression>:
<Block>
else:
<Block>
def absolute(x):
if x < 0:
x= -x
return x
--------------------------
def bigger(a,b):
if a>b:
r = a
else:
r = b
return r
或 or <Expression> or <Expression>
有一个True 返回True 否则False
Q:定义程序 biggest , inputs3个数字 输出最大值
A:
def biggest(a,b,c):
if a > b :
if a > c :
return a
else:
return c
else:
if b > c:
return b
else:
return c
------------------------------------
def bigger(a,b):
if a>b:
return a
else :
return b
def biggest(a,b,c):
return bigger(bigger(a,b), c)
循环 Loops
while <TestExpression>:
<Block>
乘阶
def factorial(n):
result = 1
while n > 1:
result = result * n
n = n-1
return result
中断 break 跳出循环
def get_next_target(page):
start_link = page.find('<a href=')
start_quote = page.find('"', start_link)
end_quote = page.find('"', start_quote+1)
url = page[start_quote+1: end_quote]
return url, end_quote
多重赋值 Multiple Assignment<Name1>,<Name2>,... = <Expression1>,<Expression2>,...
url , end_quote = get_next_target(page)
Q: s,t = t,s
做了什么
A:s和t的值换了
#找到string页面的链接
def get_next_target(page):
start_link = page.find('<a href=')
if start_link == -1:
return None , 0
start_quote = page.find('"', start_link)
end_quote = page.find('"', start_quote+1)
url = page[start_quote+1: end_quote]
return url, end_quote
Q:打印所有链接
A:
def print_all_links(page):
while True:
url , endpos = get_next_target(page)
if url :
print url
page = page[endpos:]
else:
break
视频中获取网页源码get_page方法要自己写