条件语句

if(bool expression):
    pass

多个条件组合:and or
检查值是否在列表中:in not in

小海龟画正方形经典例程

import turtle as t
t.setup(500,600)
for i in range(100):
    y = i%4
    if y==0:
        t.color("red")
    if y==1:
        t.color("yellow")
    if y==2:
        t.color("blue")
    if y==3:
        t.color("green")
    t.forward(2*i)
    t.right(90)

多路分支结构:

if condition_1:
    pass
elif condition_2:
    pass
elif condition_3:
    pass
else:
    pass

词典练习

import random
import time

class dic:
    def __init__(self,filename):
        random.seed(time.time())
        self.words = {}
        self.db = filename
        inFile = open(filename,"r")
        wordsCache = list(map(lambda x:x.split(),inFile.readlines()))
        for rec in wordsCache:
            self.words[rec[0]] = []
            for chs in rec[1:]:
                self.words[rec[0]].append(chs)
        inFile.close()
    def save_words(self):
        outFile = open(self.db,"w")
        outStr = ""
        for rec in self.words.keys():
            outStr += rec
            for word in self.words[rec]:
                outStr += " " + word
            outFile.write(outStr+"\n")
            outStr = ""
        outFile.close()

    def add_word(self,en,ch):
        if en not in self.words.keys():
            self.words[en] = []
            self.words[en].append(ch)
        elif ch not in self.words[en]:
            self.words[en].append(ch)

    def del_word(self,en):
        if en in self.words.keys():
            del self.words[en]

    def query_word(self,query):
        for rec in self.words.keys():
            if rec.lower() == query.lower():
                return (rec,self.words[rec])
            for word in self.words[rec]:
                if word == query:
                    return (rec,self.words[rec])
        return null

    def random_word(self):
        key = list(self.words.keys())[random.randint(0,len(self.words)-1)]
        return (key,self.words[key])

    def list_words(self):
        for rec in self.words.keys():
            print((rec,self.words[rec]))


def cmd(obj,command):
    if command == "list":
        obj.list_words()
    elif command == "exit":
        obj.save_words()
        exit(0)
    elif command == "add":
        en = input("English:")
        ch = input("Chinese:")
        obj.add_word(en,ch)
    elif command == "del":
        en = input("English:")
        obj.del_word(en)
    elif command == "random":
        print(obj.random_word())
    elif command == "query":
        query = input("Search:")
        print(obj.query_word(query))
    else:
        print("use command: list,add,del,random,query,exit")
    print("\n $>> ", end='');


if __name__ == "__main__":
    Dic = dic("words");
    cmd(Dic,"");
    while 1==1:
        cmd(Dic,input())
    Dic.save_words();