兩週學會Python 第02天(上午)
阿新 • • 發佈:2019-01-30
目標: 學會寫靈活健壯簡潔的程式
學習知識點:
控制結構:
條件分支
迴圈
異常處理:
捕獲與產生異常
自定義異常
函式:
名稱與docstrings
引數與引數的拆分
存取全域性範圍變數
lambda函式
斷言
學習程式碼示例:
make_html_skeleton.py 使用程式生成站點的框架HTML檔案,之後根據需要使用合適的內容對其進行完善
import datetime
import xml.sax.saxutils
COPYRIGHT_TEMPLATE = "Copyright (c) {0} {1}. All rights reserved."
STYLESHEET_TEMPLATE = ('<link rel="stylesheet" type="text/css" '
'media="all" href="{0}" />\n')
HTML_TEMPLATE = """<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" \
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>{title}</title>
<!-- {copyright} -->
<meta name="Description" content="{description}" />
<meta name="Keywords" content="{keywords}" />
<meta equiv="content-type" content="text/html; charset=utf-8" />
{stylesheet}\
</head>
<body>
</body>
</html>
"""
class CancelledError(Exception): pass
def main():
#定義一個資訊字典
information = dict(name=None, year=datetime.date.today().year,
filename=None, title=None, description=None,
keywords=None, stylesheet=None)
while True:
try:
print("\nMake HTML Skeleton\n" )
#構造完整資訊
populate_information(information)
#將資訊填充到模板,構造html檔案
make_html_skeleton(**information)
except CancelledError:
print("Cancelled")
if (get_string("\nCreate another (y/n)?", default="y").lower()
not in {"y", "yes"}):
break
def populate_information(information):
#獲取名稱
name = get_string("Enter your name (for copyright)", "name",
information["name"])
if not name:
raise CancelledError()
#獲取年份
year = get_integer("Enter copyright year", "year",
information["year"], 2000,
datetime.date.today().year + 1, True)
if year == 0:
raise CancelledError()
filename = get_string("Enter filename", "filename")
if not filename:
raise CancelledError()
if not filename.endswith((".htm", ".html")):
filename += ".html"
title = get_string("Enter title", "title")
if not title:
raise CancelledError()
description = get_string("Enter description (optional)",
"description")
#獲取keywords
keywords = []
while True:
keyword = get_string("Enter a keyword (optional)", "keyword")
if keyword:
keywords.append(keyword)
else:
break
stylesheet = get_string("Enter the stylesheet filename "
"(optional)", "stylesheet")
if stylesheet and not stylesheet.endswith(".css"):
stylesheet += ".css"
#更新詞典
information.update(name=name, year=year, filename=filename,
title=title, description=description,
keywords=keywords, stylesheet=stylesheet)
def make_html_skeleton(year, name, title, description, keywords,
stylesheet, filename):
#將時間,名稱作為版權資訊,對名稱進行xml轉義
copyright = COPYRIGHT_TEMPLATE.format(year,
xml.sax.saxutils.escape(name))
#將標題轉義
title = xml.sax.saxutils.escape(title)
#將描述資訊轉義
description = xml.sax.saxutils.escape(description)
#對keywords轉義,並且多個keyword通過,相連
keywords = ",".join([xml.sax.saxutils.escape(k)
for k in keywords]) if keywords else ""
#對stylesheet轉義
stylesheet = (STYLESHEET_TEMPLATE.format(stylesheet)
if stylesheet else "")
#將本地變數資訊,填充至模板中
html = HTML_TEMPLATE.format(**locals())
#將檔案儲存至filename中
fh = None
try:
fh = open(filename, "w", encoding="utf8")
fh.write(html)
except EnvironmentError as err:
print("ERROR", err)
else:#如果fh為None,則列印資訊
print("Saved skeleton", filename)
finally:
if fh is not None:
fh.close()
def get_string(message, name="string", default=None,
minimum_length=0, maximum_length=80):
#將預設值新增至提示資訊中
message += ": " if default is None else " [{0}]: ".format(default)
#獲取一個正確的字串
while True:
try:
line = input(message)
if not line:
#使用預設字串
if default is not None:
return default
if minimum_length == 0:
return ""
else:
raise ValueError("{0} may not be empty".format(
name))
#檢測字串長度
if not (minimum_length <= len(line) <= maximum_length):
raise ValueError("{name} must have at least "
"{minimum_length} and at most "
"{maximum_length} characters".format(
**locals()))
return line
except ValueError as err:
print("ERROR", err)
def get_integer(message, name="integer", default=None, minimum=0,
maximum=100, allow_zero=True):
#越界異常
class RangeError(Exception): pass
#構建提示資訊
message += ": " if default is None else " [{0}]: ".format(default)
while True:
try:
line = input(message)
#使用預設值
if not line and default is not None:
return default
i = int(line)
if i == 0:
if allow_zero:
return i
else:
raise RangeError("{0} may not be 0".format(name))
#檢測值是否符合規定範圍
if not (minimum <= i <= maximum):
raise RangeError("{name} must be between {minimum} "
"and {maximum} inclusive{0}".format(
" (or 0)" if allow_zero else "", **locals()))
return i
except RangeError as err:
print("ERROR", err)
except ValueError as err:
print("ERROR {0} must be an integer".format(name))
main()
總結
- Python的控制結構語法和shell簡直一模一樣,需要注意的是,Python沒有do while語法
Python的異常處理和java的異常處理類似,唯一的區別在於,python的語法中,多了一個else,下面的程式碼一執行,你就懂了else的作用啦!
try:
a = int(input())
if a:
raise Exception()
except:
print(“except”)
else:
print(“else”)名稱(命名規範),Docstrings:在Java中和/** **/註釋效果一樣
def get_integer(message, name=”integer”, default=None, minimum=0,
maximum=100, allow_zero=True):
”’
獲取字串
:param message:
:param name:
:param default:
:param minimum:
:param maximum:
:param allow_zero:
:return:
”’
4. make_html_skeleton(**information), **對引數的拆分
5. def product(*args) *args相當於java中 Object…args
6. global x 將x設為全域性變數
下面的要多練練才能掌握
- assert all(args)斷言,為開發者設計,多用用才知道
- lambda函式