編程基礎:Python 學習總結

這門課程不是從語法開始,而是通過6個項目串聯講解Python的一些編程思想。從函數的使用、類的使用到創建類。在項目的實現中介紹如何查看閱讀Python文檔,如何解決bug,Python內置模塊、函數的結構等內容。總的來說這門課程是在介紹Python的編程思想而非語法細節。課程地圖:

一、簡介

介紹課程內容,簡單的循環、IF語句測試,以及Python的安裝。

二、使用函數

這部分主要完成兩個項目:

  1. 休息一下:寫程序安排一天的休息時段
  2. 秘密消息:給文件重命名

休息一下

要求每隔一段時間跳出一個頁面播放音樂提醒大家休息。
解決這個問題的思路是:
Repeat{

  1. 等待2小時
  2. 打開瀏覽器
    }

代碼很簡單,主要是學到庫 webbrowser

import time
import webbrowser
total = 3
count = 0
print 'this program started on ' + time.ctime()
while(count < total):
    time.sleep(10)
    webbrowser.open('https://classroom.udacity.com')
    count += 1

秘密消息

要求對文件夾下的所有圖片重命名,顯示隱藏的信息。
解決思路:

  1. 得到文件夾下所有的文件名
  2. 對每個文件重命名

主要學習文件操作。

import os
import string
def rename_files():

    #1.get file names from a floder
    file_list = os.listdir('/home/nimo/Course/PythonU/prank')
    #print os.getcwd()              #輸出當前操作目錄
    #切換當前操作目錄。按理說file_list 已經存了所有文件名,在不在prank文件夾下都可以對其遍歷。但是重命名操作需要定位文件所在位置。
    os.chdir('/home/nimo/Course/PythonU/prank')              

    #2.for each file,rename filename
    for file_name in file_list:
        print "old name:",file_name
        print "new name:",file_name.translate(None,'0123456789')
        os.rename(file_name,file_name.translate(None,'0123456789'))         #需要定位到文件所在位置

目前用于解決問題的方法都是建文件寫函數逐行寫執行操作,但是函數也有不能完成的任務——電影展示:同一個模板不同的對象使用,重復代碼顯然不是好方法。

三、使用類

1. 畫烏龜

畫一圈正方形形成一個圓。結果如圖

turtle是Python中一個繪制圖像的函數庫,好像一只烏龜在坐標系上爬行,用路徑構成所畫圖像。

import turtle
#畫方形
def draw_square(t):
    for i in range(1,5):
        t.forward(100)
        t.right(90)       #右轉90度,每次以爬行前進方向確定左右。
        #t.right(60)
        
#畫圖主要實現函數
def draw_art():
    #定義畫布
    window = turtle.Screen()
    window.bgcolor('green')

    #create turtle brad, draw a square
    brad = turtle.Turtle()          #使用turtle類生成實例對象
    brad.shape("turtle")
    brad.color("yellow")
    brad.speed(2)
    
    for i in range(1,37):
        draw_square(brad)
        brad.right(10)
    
    #產生另一個實例畫圓
    angie = turtle.Turtle()
    angie.shape('arrow')
    angie.color("blue")
    angie.circle(100)
    
    window.exitonclick()

輸出結果:

這個例子主要是為了引入類的概念,改進一下可以畫出很多有趣的圖形。如分形樹:

from turtle import Turtle, mainloop
 
def tree(plist, l, a, f):
    """ plist is list of pens
    l is length of branch
    a is half of the angle between 2 branches
    f is factor by which branch is shortened
    from level to level."""
    if l > 5: #
        lst = []
        for p in plist:
            p.forward(l)#沿著當前的方向畫畫Move the turtle forward by the specified distance, in the direction the turtle is headed.
            q = p.clone()#Create and return a clone of the turtle with same position, heading and turtle properties.
            p.left(a) #Turn turtle left by angle units
            q.right(a)# turn turtle right by angle units, nits are by default degrees, but can be set via the degrees() and radians() functions.
            lst.append(p)#將元素增加到列表的最后
            lst.append(q)
        tree(lst, l*f, a, f)
   
def main():
    p = Turtle()
    p.color("green")
    p.pensize(5)
    #p.setundobuffer(None)
    p.hideturtle() #Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing,
    #because hiding the turtle speeds up the drawing observably.
    #p.speed(10)
   # p.getscreen().tracer(1,0)#Return the TurtleScreen object the turtle is drawing on.
    p.speed(10)
    #TurtleScreen methods can then be called for that object.
    p.left(90)# Turn turtle left by angle units. direction 調整畫筆
 
    p.penup() #Pull the pen up – no drawing when moving.
    p.goto(0,-200)#Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation.
    p.pendown()# Pull the pen down – drawing when moving. 這三條語句是一個組合相當于先把筆收起來再移動到指定位置,再把筆放下開始畫
    #否則turtle一移動就會自動的把線畫出來
 
    #t = tree([p], 200, 65, 0.6375)
    t = tree([p], 200, 65, 0.6375)
     
main()

時鐘程序:

import turtle  
from datetime import *  
   
# 抬起畫筆,向前運動一段距離放下  
def Skip(step):  
    turtle.penup()  
    turtle.forward(step)  
    turtle.pendown()  
   
def mkHand(name, length):  
    # 注冊Turtle形狀,建立表針Turtle  
    turtle.reset()  
    Skip(-length * 0.1)  
    # 開始記錄多邊形的頂點。當前的烏龜位置是多邊形的第一個頂點。  
    turtle.begin_poly()  
    turtle.forward(length * 1.1)  
    # 停止記錄多邊形的頂點。當前的烏龜位置是多邊形的最后一個頂點。將與第一個頂點相連。  
    turtle.end_poly()  
    # 返回最后記錄的多邊形。  
    handForm = turtle.get_poly()  
    turtle.register_shape(name, handForm)  
   
def Init():  
    global secHand, minHand, hurHand, printer  
    # 重置Turtle指向北  
    turtle.mode("logo")  
    # 建立三個表針Turtle并初始化  
    mkHand("secHand", 135)  
    mkHand("minHand", 125)  
    mkHand("hurHand", 90)  
    secHand = turtle.Turtle()  
    secHand.shape("secHand")  
    minHand = turtle.Turtle()  
    minHand.shape("minHand")  
    hurHand = turtle.Turtle()  
    hurHand.shape("hurHand")  
     
    for hand in secHand, minHand, hurHand:  
        hand.shapesize(1, 1, 3)  
        hand.speed(0)  
     
    # 建立輸出文字Turtle  
    printer = turtle.Turtle()  
    # 隱藏畫筆的turtle形狀  
    printer.hideturtle()  
    printer.penup()  
      
def SetupClock(radius):  
    # 建立表的外框  
    turtle.reset()  
    turtle.pensize(7)  
    for i in range(60):  
        Skip(radius)  
        if i % 5 == 0:  
            turtle.forward(20)  
            Skip(-radius - 20)  
             
            Skip(radius + 20)  
            if i == 0:  
                turtle.write(int(12), align="center", font=("Courier", 14, "bold"))  
            elif i == 30:  
                Skip(25)  
                turtle.write(int(i/5), align="center", font=("Courier", 14, "bold"))  
                Skip(-25)  
            elif (i == 25 or i == 35):  
                Skip(20)  
                turtle.write(int(i/5), align="center", font=("Courier", 14, "bold"))  
                Skip(-20)  
            else:  
                turtle.write(int(i/5), align="center", font=("Courier", 14, "bold"))  
            Skip(-radius - 20)  
        else:  
            turtle.dot(5)  
            Skip(-radius)  
        turtle.right(6)  
          
def Week(t):     
    week = ["星期一", "星期二", "星期三",  
            "星期四", "星期五", "星期六", "星期日"]  
    return week[t.weekday()]  
   
def Date(t):  
    y = t.year  
    m = t.month  
    d = t.day  
    return "%s %d%d" % (y, m, d)  
   
def Tick():  
    # 繪制表針的動態顯示  
    t = datetime.today()  
    second = t.second + t.microsecond * 0.000001  
    minute = t.minute + second / 60.0  
    hour = t.hour + minute / 60.0  
    secHand.setheading(6 * second)  
    minHand.setheading(6 * minute)  
    hurHand.setheading(30 * hour)  
      
    turtle.tracer(False)   
    printer.forward(65)  
    printer.write(Week(t), align="center",  
                  font=("Courier", 14, "bold"))  
    printer.back(130)  
    printer.write(Date(t), align="center",  
                  font=("Courier", 14, "bold"))  
    printer.home()  
    turtle.tracer(True)  
   
    # 100ms后繼續調用tick  
    turtle.ontimer(Tick, 100)  
   
def main():  
    # 打開/關閉龜動畫,并為更新圖紙設置延遲。  
    turtle.tracer(False)  
    Init()  
    SetupClock(160)  
    turtle.tracer(True)  
    Tick()  
    turtle.mainloop()  
   
if __name__ == "__main__":  
    main()

2. 發送消息

使用Twilio模塊發短信到手機。主要介紹Python類、模塊、函數的關系,from關鍵字的使用。

3. 冒犯語檢測器

檢測一段文本中是否含有冒犯語。
解決思路:

  1. 從文檔中讀取文本
  2. 檢查這段文本是否有冒犯語

本來以為檢測冒犯語的步驟會使用字符串查找匹配的方式,課程簡化為丟給網頁處理。主要還是文件的處理和標準庫中urllib的調用。

import urllib

def read_text():
    #quotes就是文件這個類的一個實例
    quotes = open('/home/nimo/Course/PythonU/2/movie_quotes.txt')
    contents_of_file = quotes.read()
    #print contents_of_file
    quotes.close()
    check_profanity(contents_of_file)
    
def check_profanity(text_to_check):
    connection = urllib.urlopen('http://www.wdylike.appspot.com/?q=' + text_to_check)
    output = connection.read()
    print output
    connection.close()

四、創造類

寫一個電影網頁,展示一些電影的海報,可播放其預告片。
首先是電影類的定義,放在media.py模快:

import webbrowser

class Movie():
    '''This class provides a way to store movie related information'''
    VALID_RATINGS = ['G', 'PG', 'PG-13', 'R']
    
    def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
        self.title = movie_title
        self.storyline = movie_storyline
        self.poster_image_url = movie_storyline
        self.trailer_youtube_url = trailer_youtube
        
    def show_trailer(self):
        #播放預告片
        webbrowser.open(self.trailer_youtube_url)

介紹了如何給函數寫文檔,如何定義類屬性和函數。

然后導入這個模塊生成對應實例,調用fresh_tomatoes模快生成網頁。

import media
import fresh_tomatoes

toy_story = media.Movie('Toy Story',
                        'A story of a boy and his toys that come to life',
                        'https://movie.douban.com/photos/photo/523015829/',
                        'http://www.le.com/ptv/vplay/26876125.html?ch=baiduald_mfdy')
                        
#print toy_story.storyline

avatar = media.Movie('avatar',
                     'A marine on an alien planet',
                     'https://movie.douban.com/photos/photo/492458287/',
                     '')
                     
school_of_rock = media.Movie('school_of_rock',
                     'storyline',
                     'https://movie.douban.com/photos/photo/2193668557/',
                     '')
                     
ratatouille = media.Movie('ratatouille',
                     'storyline',
                     'https://movie.douban.com/photos/photo/2151385036/',
                     '')
                     
midnight_in_paris = media.Movie('midnight_in_paris',
                     'storyline',
                     'https://movie.douban.com/photos/photo/944234798/',
                     '')    
                     
hunger_games = media.Movie('hunger_games',
                     'storyline',
                     'https://movie.douban.com/photos/photo/1460591675/',
                     '')                 

movies = [toy_story, avatar, school_of_rock, ratatouille, midnight_in_paris, hunger_games]
fresh_tomatoes.open_movies_page(movies)
#print media.Movie.__name__, media.Movie.__module__
import webbrowser
import os
import re

# Styles and scripting for the page
main_page_head = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Fresh Tomatoes!</title>
    <!-- Bootstrap 3 -->
    <link rel="stylesheet" >
    <link rel="stylesheet" >
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
    <style type="text/css" media="screen">
        body {
            padding-top: 80px;
        }
        #trailer .modal-dialog {
            margin-top: 200px;
            width: 640px;
            height: 480px;
        }
        .hanging-close {
            position: absolute;
            top: -12px;
            right: -12px;
            z-index: 9001;
        }
        #trailer-video {
            width: 100%;
            height: 100%;
        }
        .movie-tile {
            margin-bottom: 20px;
            padding-top: 20px;
        }
        .movie-tile:hover {
            background-color: #EEE;
            cursor: pointer;
        }
        .scale-media {
            padding-bottom: 56.25%;
            position: relative;
        }
        .scale-media iframe {
            border: none;
            height: 100%;
            position: absolute;
            width: 100%;
            left: 0;
            top: 0;
            background-color: white;
        }
    </style>
    <script type="text/javascript" charset="utf-8">
        // Pause the video when the modal is closed
        $(document).on('click', '.hanging-close, .modal-backdrop, .modal', function (event) {
            // Remove the src so the player itself gets removed, as this is the only
            // reliable way to ensure the video stops playing in IE
            $("#trailer-video-container").empty();
        });
        // Start playing the video whenever the trailer modal is opened
        $(document).on('click', '.movie-tile', function (event) {
            var trailerYouTubeId = $(this).attr('data-trailer-youtube-id')
            var sourceUrl = 'http://www.youtube.com/embed/' + trailerYouTubeId + '?autoplay=1&html5=1';
            $("#trailer-video-container").empty().append($("<iframe></iframe>", {
              'id': 'trailer-video',
              'type': 'text-html',
              'src': sourceUrl,
              'frameborder': 0
            }));
        });
        // Animate in the movies when the page loads
        $(document).ready(function () {
          $('.movie-tile').hide().first().show("fast", function showNext() {
            $(this).next("div").show("fast", showNext);
          });
        });
    </script>
</head>
'''

# The main page layout and title bar
main_page_content = '''
  <body>
    <!-- Trailer Video Modal -->
    <div class="modal" id="trailer">
      <div class="modal-dialog">
        <div class="modal-content">
          <a href="#" class="hanging-close" data-dismiss="modal" aria-hidden="true">
            ![](https://lh5.ggpht.com/v4-628SilF0HtHuHdu5EzxD7WRqOrrTIDi_MhEG6_qkNtUK5Wg7KPkofp_VJoF7RS2LhxwEFCO1ICHZlc-o_=s0#w=24&h=24)
          </a>
          <div class="scale-media" id="trailer-video-container">
          </div>
        </div>
      </div>
    </div>
    <!-- Main Page Content -->
    <div class="container">
      <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
        <div class="container">
          <div class="navbar-header">
            <a class="navbar-brand" href="#">Fresh Tomatoes Movie Trailers</a>
          </div>
        </div>
      </div>
    </div>
    <div class="container">
      {movie_tiles}
    </div>
  </body>
</html>
'''

# A single movie entry html template
movie_tile_content = '''
<div class="col-md-6 col-lg-4 movie-tile text-center" data-trailer-youtube-id="{trailer_youtube_id}" data-toggle="modal" data-target="#trailer">
    ![]({poster_image_url})
    <h2>{movie_title}</h2>
</div>
'''

def create_movie_tiles_content(movies):
    # The HTML content for this section of the page
    content = ''
    for movie in movies:
        # Extract the youtube ID from the url
        youtube_id_match = re.search(
            r'(?<=v=)[^&#]+', movie.trailer_youtube_url)
        youtube_id_match = youtube_id_match or re.search(
            r'(?<=be/)[^&#]+', movie.trailer_youtube_url)
        trailer_youtube_id = (youtube_id_match.group(0) if youtube_id_match
                              else None)

        # Append the tile for the movie with its content filled in
        content += movie_tile_content.format(
            movie_title=movie.title,
            poster_image_url=movie.poster_image_url,
            trailer_youtube_id=trailer_youtube_id
        )
    return content


def open_movies_page(movies):
    # Create or overwrite the output file
    output_file = open('fresh_tomatoes.html', 'w')

    # Replace the movie tiles placeholder generated content
    rendered_content = main_page_content.format(
        movie_tiles=create_movie_tiles_content(movies))

    # Output the file
    output_file.write(main_page_head + rendered_content)
    output_file.close()

    # open the output file in the browser (in a new tab, if possible)
    url = os.path.abspath(output_file.name)
    webbrowser.open('file://' + url, new=2)

最后介紹了下繼承、函數重寫覆蓋等概念,跑一遍例子就都清楚了。

class Parent():
    def __init__(self, last_name, eye_color):
        print 'Parent Constructor Called'
        self.last_name = last_name
        self.eye_color = eye_color
    
    def show_info(self):
        print 'last name:',self.last_name
        print 'eye color:',self.eye_color
        
class Child(Parent):
    def __init__(self, last_name, eye_color, number_of_toys):
        print 'Child Constructor Called'
        Parent.__init__(self, last_name, eye_color)
        self.number_of_toys = number_of_toys
        
    def show_info(self):
        print 'last name:',self.last_name
        print 'eye color:',self.eye_color
        print 'number_of_toys:',str(self.number_of_toys)
        
andy_cycus = Child('cycus', 'blue', 5)
#print andy_cycus.last_name, andy_cycus.number_of_toys
andy_cycus.show_info()
參考:

分形樹
時鐘

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,237評論 6 537
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,957評論 3 423
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,248評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,356評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,081評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,485評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,534評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,720評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,263評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,025評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,204評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,787評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,461評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,874評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,105評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,945評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,205評論 2 375

推薦閱讀更多精彩內容

  • http://python.jobbole.com/85231/ 關于專業技能寫完項目接著寫寫一名3年工作經驗的J...
    燕京博士閱讀 7,603評論 1 118
  • # Python 資源大全中文版 我想很多程序員應該記得 GitHub 上有一個 Awesome - XXX 系列...
    aimaile閱讀 26,530評論 6 427
  • 前言 ||| 第二章 使用ArcPy編寫腳本 Python支持大部分在其他語言中出現的編程結構。在本章內容中,我們...
    muyan閱讀 90,134評論 10 55
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,682評論 25 708
  • 這個周末,茶山入住了上海的金門大酒店,它位于上海南京路步行街附近,雖然不起眼,但據稱,這個酒店已經有超過100年的...
    茶山閱讀 215評論 0 2