zoukankan      html  css  js  c++  java
  • 彭亮—Python学习

    1.1 Python简单介绍


    1.2 安装Python和配置环境

     1.配置Python

         1.1 下载Python(直接去官网下载就可以)
         1.2 安装Python(点解默认安装即可,可以使用GUI的中的shell编辑,也可以用Python下的命令提示符)
     
    2. IDLE介绍
        (一般不用官网下载的Pyhon的IDE,不利于工程化的编辑)
    3. PyDev介绍
         3.1 Eclipse(Eclipse主要是基于Java开发使用的)
         3.2 PyDev for Eclipse
         
    4. 配置Eclipse
         4.1 下载安装Java
         4.2 下载Eclipse 

    1.3 配置PyDev
    1. 介绍Python Interpreter
     
    2. Windows 命令行中运行Python (配置环境变量)
     
    3. 配置Eclipse     
         3.1 配置Eclipse中java的路径
         3.2 测试Java
     
    4. 配置PyDev
         4.1 在Eclipse里安装PyDev
         4.2 用PyDev创建Python项目
         4.3 在Python项目里创建模块
         4.4 测试运行"Hello World"程序
     
     
    什么是dll文件?
    DLL是Dynamic Link Library的缩写,意为动态链接库。在Windows中,许多应用程序并不是一个完整的可执行文件,
    它们被分割成一些相对独立的动态链接库,即DLL文件,放置于系统中。当我们执行某一个程序时,相应的DLL文件
    就会被调用。一个应用程序可有多个DLL文件,一个DLL文件也可能被几个应用程序所共用,这样的DLL文件被称为
    共享DLL文件。DLL文件一般被存放在C:WindowsSystem目录下。
     

    2.1 Package以及数据类型1
    1. 自带package和外部package
         1.1 自带package举例: os; os.getwd()             (Operating System操作系统)          print( os.getwd())打印模块os所在的路径  
     
    2. 外部package以及管理系统介绍: easy_install, pip (comes with Python 3.4)
     
    3. 环境变量中配置easy_install, pip
     
    4. 使用easy_install, pip安装package举例
     
    >>> import requests
     
    >>> r = requests.get('https://api.github.com/events')
     
    >>> r.text
     
    >>> r.url
     
    >>> r.encoding

    2.2 数据类型2: Numeric & String

    1. Python数据类型
         1.1 总体:numerics, sequences, mappings, classes, instances, and exceptions
         1.2 Numeric Types(数字型): int (包含boolean), float, complex
         1.3 int: unlimited length; float: 实现用double in C, 可查看 sys.float_info; complex: real(实部) & imaginary(虚部),用z.real 和 z.imag来取两部分
         1.4 具体运算以及法则参见:https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex
         1.5 例子
     
    import sys
     
    a = 3
    b = 4
     
    c = 5.66
    d = 8.0
     
     
    e = complex(c, d)
    f = complex(float(a), float(b))
     
    print ("a is type:" , type(a))       #前面一个字符串,用逗号连接后面的一个字符串type(a)   输出:a is type:<class 'int'>
    print ("b is type" , type(b))
    print ("c is type" , type(c))
    print ("d is type" , type(d))
    print ("e is type" , type(e))
    print ("f is type" , type(f))
    print (sys.float_info)           #浮点型支持的最大最小值及其范围

      

     
    print(a + b)
    print(d / c)
    print (b / a)
    print (b // a)
    print (e)
    print (e + f)
     
    print ("e's real part is: " , e.real)
    print ("e's imaginary part is: " , e.imag)
     
    print (sys.float_info)

    1. 字符串:
              一串字符               print打印字符串用单引号和双引号都可以,三引号则可以用于多行字符串的打印  print('''    ''')
              导出   显示或者打印出来文字信息
              编码:# -*- coding: utf-8 -*-
              单引号,双引号,三引号
              不可变(immutable)
              Format字符串
                   age = 3
                   name = "Tom"
                   print("{0} was {1} years old".format(name, age))      {0}通过format函数建立起关联{0}代表name对应的值
              联合:+: print(name + " was " + str(age) + " years old")
              换行符: print("What's your name? Tom")
     
    2. 字面常量(literal constant):
     
    可以直接以字面的意义使用它们:
    如:6,2.24,3.45e-3, "This is a string"
    常量:不会被改变
     
    3. 变量:
              储存信息
              属于identifier
              identifier命名规则:
                   第一个字符必须是字母或者下划线
              其余字符可以是字母,数字,或者下划线
              区分大小写
              如:合法:i, name_3_4, big_bang
                   不合法:2people, this is tom, my-name, >123b_c2
              
     
     
    4. 注释: #
     
    5. 缩进(Indentation)
     

     demo的含义:

    Demo是英文Demonstration的缩写,在商业影视作品和广告片中,Demo的含意为“示范”、“展示”、“样片”、“样稿”,

    Demo字样通常是加在未制作完成的影视作品或广告视频中的,加上Demo字样的影视作品或广告片是只用来供商业

    客户审片用,不允许随意发布和传播的。在电脑上的DEMO简单的说就是展示电脑图形与音乐的程式,所以游戏开

    始的动画展示也是DEMO的一种。在电脑公司,可以看到电脑上展示介绍电脑软硬件的程式,这些属于商业性质的

    DEMO;这些DEMO是凭借图形与音乐来吸引顾客,达到宣传的目的。中文说的就是预告片的意思。

    演示版,使用版,试玩版


    3.1数据结构列表:
    1. print中的编码:
            编码:# -*- coding: utf-8 -*-                          #告诉系统程序在这里使用的是utf-8的编码方式,特殊编码,并不是作为编码执行,作为注释,告诉系统程序的编码方式
                                                                                 #打印中文需要有这样的注释说明
     
    2. print中的换行
              print("What's your name? Tom")
     
    3. List
         创建
         访问
         更新    
         删除
         脚本操作符
         函数方法
     
     
    Code:
     
    # -*- coding: utf-8 -*-
     
    #创建一个列表
     
    number_list = [1, 3, 5, 7, 9]
     
    string_list = ["abc", "bbc", "python"]
     
    mixed_list = ['python', 'java', 3, 12]
     
     
    #访问列表中的值
     
    second_num = number_list[1]
     
    third_string = string_list[2]
     
    fourth_mix = mixed_list[3]
     
    print("second_num: {0} third_string: {1} fourth_mix: {2}".format(second_num, third_string, fourth_mix))
     
    #更新列表
    print("number_list before: " + str(number_list))
     
    number_list[1] = 30
     
    print("number_list after: " + str(number_list))
     
    #删除列表元素
    print("mixed_list before delete: " + str(mixed_list))
     
    del mixed_list[2]
     
    print("mixed_list after delete: " + str(mixed_list))
     
    #Python脚本语言
     
    print(len([1,2,3])) #长度
    print([1,2,3] + [4,5,6]) #组合
    print(['Hello'] * 4) #重复
    print(3 in [1,2,3]) #某元素是否在列表中
     
    #列表的截取
    abcd_list =['a', 'b', 'c', 'd'] 
    print(abcd_list[1])
    print(abcd_list[-2])
    print(abcd_list[1:])
     
    # 列表操作包含以下函数:
    # 1、cmp(list1, list2):比较两个列表的元素 
    # 2、len(list):列表元素个数 
    # 3、max(list):返回列表元素最大值 
    # 4、min(list):返回列表元素最小值 
    # 5、list(seq):将元组转换为列表 
    # 列表操作包含以下方法:
    # 1、list.append(obj):在列表末尾添加新的对象
    # 2、list.count(obj):统计某个元素在列表中出现的次数
    # 3、list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
    # 4、list.index(obj):从列表中找出某个值第一个匹配项的索引位置
    # 5、list.insert(index, obj):将对象插入列表
    # 6、list.pop(obj=list[-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
    # 7、list.remove(obj):移除列表中某个值的第一个匹配项
    # 8、list.reverse():反向列表中元素
    # 9、list.sort([func]):对原列表进行排序
     
     

    3.2元组Tuple
    1. List
    # 列表操作包含以下函数:
    # 1、cmp(list1, list2):比较两个列表的元素 
    # 2、len(list):列表元素个数 
    # 3、max(list):返回列表元素最大值 
    # 4、min(list):返回列表元素最小值 
    # 5、list(seq):将元组转换为列表 
    # 列表操作包含以下方法:
    # 1、list.append(obj):在列表末尾添加新的对象
    # 2、list.count(obj):统计某个元素在列表中出现的次数
    # 3、list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
    # 4、list.index(obj):从列表中找出某个值第一个匹配项的索引位置
    # 5、list.insert(index, obj):将对象插入列表
    # 6、list.pop(obj=list[-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
    # 7、list.remove(obj):移除列表中某个值的第一个匹配项
    # 8、list.reverse():反向列表中元素
    # 9、list.sort([func]):对原列表进行排序
     
    2. 元组(tuple)
         创建
         访问
         删除
         脚本操作符
         函数方法

    3.2_Part2列表List元组tuple对比

    #创建只有一个元素的tuple,需要用逗号结尾消除歧义
    a_tuple = (2,)
     
    #tuple中的list
    mixed_tuple = (1, 2, ['a', 'b'])
     
    print("mixed_tuple: " + str(mixed_tuple))
     
    mixed_tuple[2][0] = 'c'
    mixed_tuple[2][1] = 'd'
     
    print("mixed_tuple: " + str(mixed_tuple))
     
    Tuple 是不可变 list。 一旦创建了一个 tuple 就不能以任何方式改变它。
     
    Tuple 与 list 的相同之处
    定义 tuple 与定义 list 的方式相同, 除了整个元素集是用小括号包围的而不是方括号。
    Tuple 的元素与 list 一样按定义的次序进行排序。 Tuples 的索引与 list 一样从 0 开始, 所以一个非空 tuple 的第一个元素总是 t[0]。
    负数索引与 list 一样从 tuple 的尾部开始计数。
    与 list 一样分片 (slice) 也可以使用。注意当分割一个 list 时, 会得到一个新的 list ;当分割一个 tuple 时, 会得到一个新的 tuple。
     
    Tuple 不存在的方法
    您不能向 tuple 增加元素。Tuple 没有 append 或 extend 方法。
    您不能从 tuple 删除元素。Tuple 没有 remove 或 pop 方法。
    然而, 您可以使用 in 来查看一个元素是否存在于 tuple 中。
     
    用 Tuple 的好处
    Tuple 比 list 操作速度快。如果您定义了一个值的常量集,并且唯一要用它做的是不断地遍历它,请使用 tuple 代替 list。
    如果对不需要修改的数据进行 “写保护”,可以使代码更安全。使用 tuple 而不是 list 如同拥有一个隐含的 assert 语句,说明这一数据是常量。如果必须要改变这些值,则需要执行 tuple 到 list 的转换。
     
    Tuple 与 list 的转换
    Tuple 可以转换成 list,反之亦然。内置的 tuple 函数接收一个 list,并返回一个有着相同元素的 tuple。而 list 函数接收一个 tuple 返回一个 list。从效果上看,tuple 冻结一个 list,而 list 解冻一个 tuple。
     
    Tuple 的其他应用
    一次赋多值
    >>> v = ('a', 'b', 'e')
    >>> (x, y, z) = v
    解释:v 是一个三元素的 tuple, 并且 (x, y, z) 是一个三变量的 tuple。将一个 tuple 赋值给另一个 tuple, 会按顺序将 v  的每个值赋值给每个变量。
     
     

    3.3 字典 Dictionary
    键(key),对应值(value)
     
    结构介绍
     
    # -*- coding: utf-8 -*-
     
    #创建一个词典
    phone_book = {'Tom': 123, "Jerry": 456, 'Kim': 789}
     
    mixed_dict = {"Tom": 'boy', 11: 23.5}
     
    #访问词典里的值
    print("Tom's number is " + str(phone_book['Tom']))
     
    print('Tom is a ' + mixed_dict['Tom'])
     
     
    #修改词典
    phone_book['Tom'] = 999
     
    phone_book['Heath'] = 888
     
    print("phone_book: " + str(phone_book)) 
     
    phone_book.update({'Ling':159, 'Lili':247})
     
    print("updated phone_book: " + str(phone_book)) 
     
    #删除词典元素以及词典本身
    del phone_book['Tom']
    print("phone_book after deleting Tom: " + str(phone_book)) 
     
    #清空词典
    phone_book.clear()
    print("after clear: " + str(phone_book))
     
     
    #删除词典
    del phone_book
     
    # print("after del: " + str(phone_book))
     
    #不允许同一个键出现两次
    rep_test = {'Name': 'aa', 'age':5, 'Name': 'bb'}
    print("rep_test: " + str(rep_test))
     
     
    #键必须不可变,所以可以用书,字符串或者元组充当,列表不行
     
    list_dict = {['Name']: 'John', 'Age':13}
    list_dict = {('Name'): 'John', 'Age':13}
     
     
    # 六、字典内置函数&方法
    # Python字典包含了以下内置函数:
    # 1、cmp(dict1, dict2):比较两个字典元素。
    # 2、len(dict):计算字典元素个数,即键的总数。
    # 3、str(dict):输出字典可打印的字符串表示。
    # 4、type(variable):返回输入的变量类型,如果变量是字典就返回字典类型。
    # Python字典包含了以下内置方法:
    # 1、radiansdict.clear():删除字典内所有元素
    # 2、radiansdict.copy():返回一个字典的浅复制
    # 3、radiansdict.fromkeys():创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
    # 4、radiansdict.get(key, default=None):返回指定键的值,如果值不在字典中返回default值
    # 5、radiansdict.has_key(key):如果键在字典dict里返回true,否则返回false
    # 6、radiansdict.items():以列表返回可遍历的(键, 值) 元组数组
    # 7、radiansdict.keys():以列表返回一个字典所有的键
    # 8、radiansdict.setdefault(key, default=None):和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
    # 9、radiansdict.update(dict2):把字典dict2的键/值对更新到dict里
    # 10、radiansdict.values():以列表返回字典中的所有值
     
    3.4 函数Function1
    函数:程序中可重复使用的程序段
     
    给一段程程序起一个名字,用这个名字来执行一段程序,反复使用 (调用函数)
     
    用关键字 ‘def' 来定义,identifier(参数)
     
    identifier 
     
    参数list
     
    return statement
     
    局部变量 vs 全局变量
     
     
     
     
    Code:
     
     
    #-*- coding: utf-8 -*-
     
    #没有参数和返回的函数
    def say_hi():
    #     print(" hi!")
    #     
    # say_hi()
    # say_hi()
    #    
    #    
    #有参数,无返回值
    def print_sum_two(a, b):
    #     c = a + b
    #     print(c)
    #     
    # print_sum_two(3, 6)
        
    def hello_some(str):
    #     print("hello " + str + "!")
    #         
    # hello_some("China")
    # hello_some("Python")
     
     
    #有参数,有返回值
    def repeat_str(str, times):
    #     repeated_strs = str * times
    #     return repeated_strs
    # repeated_strings = repeat_str("Happy Birthday!", 4)
    # print(repeated_strings)
       
     
    #全局变量与局部 变量
    # x = 60
    def foo(x):
    #     print("x is: " + str(x))
    #     x = 3
    #     print("change local x to " + str(x))
    foo(x)
    # print('x is still', str(x))
     
     
     
     
    x = 60
     
    def foo():
        global x
        print("x is: " + str(x))
        x = 3
        print("change local x to " + str(x))
     
    foo()
    print('value of x is' , str(x))
     
     


    3.4 函数Function2
    默认参数
     
    关键字参数
     
    VarArgs参数
     
     
     
    Code:
    #-*- coding: utf-8 -*-
     
    # 默认参数
    def repeat_str(s, times = 1):
        repeated_strs = s * times
        return repeated_strs
      
      
    repeated_strings = repeat_str("Happy Birthday!")
    print(repeated_strings)
     
    repeated_strings_2 = repeat_str("Happy Birthday!" , 4)
    print(repeated_strings_2)
     
    #不能在有默认参数后面跟随没有默认参数
    #f(a, b =2)合法
    #f(a = 2, b)非法
     
    #关键字参数: 调用函数时,选择性的传入部分参数
    def func(a, b = 4, c = 8):
        print('a is', a, 'and b is', b, 'and c is', c)
     
    func(13, 17)
    func(125, c = 24)
    func(c = 40, a = 80)
     
     
    #VarArgs参数                                             #传入多个参数,其中函数的形参前面加一个*表示传入的是一个列表,函数的形参前面加两个**表示,传入的是关键字
    def print_paras(fpara, *nums, **words):
        print("fpara: " + str(fpara))
        print("nums: " + str(nums))
        print("words: " + str(words))
        
        
    print_paras("hello", 1, 3, 5, 7, word = "python", anohter_word = "java")
     
    输出结果为 :

    fpara: hello
    fpara: (1, 3, 5, 7)
    fpara: {'word': 'python', 'another_word': 'java'} 



    4.1 控制流 :If语句&for语句
    1. if 语句
     
    if condition:
         do something
    elif other_condition:
         do something
     
     
    2. for 语句
     
    Code:
     
     
    # #if statement example
    # number = 59
    # guess = int(input('Enter an integer : '))
    # if guess == number:
    #     # New block starts here
    #     print('Bingo! you guessed it right.')
    #     print('(but you do not win any prizes!)')
    #     # New block ends here
    # elif guess < number:
    #     # Another block
    #     print('No, the number is higher than that')
    #     # You can do whatever you want in a block ...
    # else:
    #     print('No, the number is a  lower than that')
    #     # you must have guessed > number to reach here
    # print('Done')
    # # This last statement is always executed,
    # # after the if statement is executed.
     
     
    #the for loop example
     
    # for i in range(1, 10):
    #     print(i)
    # else:
    #     print('The for loop is over')
    #     
    #     
    # a_list = [1, 3, 5, 7, 9]
    # for i in a_list:
    #     print(i)
    # a_tuple = (1, 3, 5, 7, 9)
    # for i in a_tuple:
    #     print(i)
    #     
    # a_dict = {'Tom':'111', 'Jerry':'222', 'Cathy':'333'}
    # for ele in a_dict:
    #     print(ele)
    #     print(a_dict[ele])
    #     
    # for key, elem in a_dict.items():
    #     print(key, elem)

    4.2 控制流:while语句&range语句
    1. while语句
     
    2. range语句
     
    Code:
     
    #while example
     
    # number = 59
    # guess_flag = False
    #  
    # while guess_flag == False:
    #     guess = int(input('Enter an integer : '))
    #     if guess == number:
    #         # New block starts here
    #         guess_flag = True
    #         # New block ends here
    #     elif guess < number:
    #         # Another block
    #         print('No, the number is higher than that, keep guessing')
    #         # You can do whatever you want in a block ...
    #     else:
    #         print('No, the number is a  lower than that, keep guessing')
    #         # you must have guessed > number to reach here
    # print('Bingo! you guessed it right.')
    # print('(but you do not win any prizes!)') 
    # print('Done')
     
    #For example 
     
    number = 59
    num_chances = 3
    print("you have only 3 chances to guess")
     
    for i in range(1, num_chances + 1):
        print("chance " + str(i))
        guess = int(input('Enter an integer : '))
        if guess == number:
            # New block starts here
            print('Bingo! you guessed it right.')
            print('(but you do not win any prizes!)') 
            break
     
            # New block ends here
        elif guess < number:
            # Another block
            print('No, the number is higher than that, keep guessing, you have ' + str(num_chances - i) + ' chances left')
            # You can do whatever you want in a block ...
        else:
            print('No, the number is lower than that, keep guessing, you have ' + str(num_chances - i) + ' chances left')
            # you must have guessed > number to reach here
     
     
    print('Done')
     

    4.3 控制流2Break&Continue&Pass
     
    1. break
     
    2. continue
     
    3. pass
     
    Code:
     
     
    #break & continue example
    # number = 59
    #  
    # while True:
    #     guess = int(input('Enter an integer : '))
    #     if guess == number:
    #         # New block starts here
    #         break                                                        #符合条件,直接跳出当前循环,直接到while外执行 print('Bingo!                                                                                     you guessed it right.')下面的程序
    #  
    #         # New block ends here
    #     if guess < number:
    #         # Another block
    #         print('No, the number is higher than that, keep guessing')
    #         continue                                                            #直接跳出当前的循环,然后从新回到while出开始循环
    #         # You can do whatever you want in a block ...
    #     else:
    #         print('No, the number is a  lower than that, keep guessing')
    #         continue
    #         # you must have guessed > number to reach here
    #  
    # print('Bingo! you guessed it right.')
    # print('(but you do not win any prizes!)') 
    # print('Done')
     
    #continue and pass difference
     
    # a_list = [0, 1, 2]
    # print("using continue:")
    # for i in a_list:
    #     if not i:
    #         continue
    #     print(i)                                        执行结果using continue 1 2
    #     
    # print("using pass:")    
    # for i in a_list:
    #     if not i:
    #         pass          #pass直接忽略当前,直接执行下面 的内容print(i)
    #     print(i)                             执行结果using continue 0 1 2
     
     
     

    5.1输入输出格式IoConsole
    接受用户的输入: input()
     
    输入格式:str(), format
     
    Code:
     
    str_1 = input("Enter a string: ")
    str_2 = input("Enter another string: ")
     
    print("str_1 is: " + str_1 + ". str_2 is :" + str_2)
    print("str_1 is {} + str_2 is {}".format(str_1, str_2))
     
     

    5.2文件输入输出
    1. 写出文件
    2. 读入文件
     
    Code:
     
    some_sentences = '''
    I love learning python
    because python is fun
    and also easy to use
    '''
     
    #Open for 'w'irting
    f = open('sentences.txt', 'w')
    #Write text to File
    f.write(some_sentences)
    f.close()
     
    #If not specifying mode, 'r'ead mode is default
    f = open('sentences.txt')
    while True:
        line = f.readline()
        #Zero length means End Of File
        if len(line) == 0:
            break
        print(line)
    # close the File
    f.close
     
     
     

    6.1错误与异常ErrorsExceptions
    Python有两种错误类型:
     
    1. 语法错误(Syntax Errors)
     
    2. 异常(Exceptions)
     
     
     
    首先,try语句下的(try和except之间的代码)被执行
    如果没有出现异常,except语句将被忽略
    如果try语句之间出现了异常,try之下异常之后的代码被忽略,直接跳跃到except语句
    如果异常出现,但并不属于except中定义的异常类型,程序将执行外围一层的try语句,如果异常没有被处理,将产生unhandled exception的错误
     

    处理异常(Handling Exceptions)
     
     
    Code:
     
    #Example of Syntax errors
     
    # while True print("Hello World!")
     
     
    #Examples of exceptions
     
    # print(8/0)
     
    # print(hello * 4)
     
    num = 6
    # print("Hello World " + num )
     
    #Handling exceptions
     
    # while True:
    #     try:
    #         x = int(input("Please enter a number"))
    #         break
    #     except ValueError:
    #         print("Not valid input, try again...")
     
     
    7.1面向对象以及装饰器OoDecorators
    1. 面向对象编程
     
    Python支持面向对象编程
     
    类(class):现实世界中一些事物的封装 (如:学生)
    类:属性 (如:名字,成绩)
     
    类对象
    实例对象
     
    引用:通过引用对类的属性和方法进行操作
    实例化:创建一个类的具体实例对象 (如:学生张三)
     
    2. 装饰器(decorator)
     
    Code:
     
     
    #Python OO example
     
    class Student:
        def __init__(self, name, grade):
            self.name = name
            self.grade = grade
            
        def introduce(self):
            print("hi! I'm " + self.name)
            print("my grade is: " + str(self.grade))
            
        def improve(self, amount):
            self.grade = self.grade + amount
     
    jim = Student("jim", 86)
    jim.introduce()
     
    jim.improve(10)
    jim.introduce()
     
     
    # def add_candles(cake_func):
    #     def insert_candles():
    #         return cake_func() + " candles"
    #     return insert_candles
    #  
    # def make_cake():
    #     return "cake"
    #  
    # gift_func = add_candles(make_cake)
    #  
    # print(make_cake())
    # print(gift_func())
     
     
     
     
     
    # def add_candles(cake_func):
    #     def insert_candles():
    #         return cake_func() + " candles"
    #     return insert_candles
    #   
    # def make_cake():
    #     return "cake"
    #   
    # make_cake = add_candles(make_cake)
    #   
    # print(make_cake())
    # # print(gift_func)
     
     
     
     
    # def add_candles(cake_func):
    #     def insert_candles():
    #         return cake_func() + " and candles"
    #     return insert_candles
    # @add_candles
    # def make_cake():
    #     return "cake"
    #  
    # # make_cake = add_candles(make_cake)
    #  
    # print(make_cake())
    # # print(gift_func)
     
     

     8.1图形界面介绍GuiTkinter
    1. GUI: Graphical User Interface
     
    2. tkinter: GUI library for Python
     
    3. GUI Example
     
     
    Code:
     
    # -*- coding: utf-8 -*-
     
    from tkinter import *                                                 #从thinter这个库中导导入所有的模块(*代表是所有的模块)
    import tkinter.simpledialog as dl                              #导入模块simpledialog(简单的对话框)   把simpledialog起名为dl(简称),这样调用简单(也可以不写as dl)
    import tkinter.messagebox as mb
     
    #tkinter GUI Input Output Example
    #设置GUI
    root = Tk()
    w = Label(root, text = "Label Title")
    w.pack()
     
    #欢迎消息
    mb.showinfo("Welcome", "Welcome Message")
    guess = dl.askinteger("Number", "Enter a number")
     
    output = 'This is output message'
    mb.showinfo("Output: ", output)
     

    8.2猜数字游戏
    1. GUI from tkinter

    2. 逻辑层 
     
    Code:
     
    # #设置GUI
    # root = Tk()                                #创建一个主函数的框
    # w = Label(root, text = "Guess Number Game")                   #Label(标签)是tkinter自带的一个类
    # w.pack()
    #  
    # #欢迎消息
    # mb.showinfo("Welcome", "Welcome to Guess Number Game")
    #  
    #  
    # #处理信息
    # number = 59
    #  
    # while True:
    # #让用户输入信息
    #     guess = dl.askinteger("Number", "What's your guess?")
    #        
    #     if guess == number:
    #         # New block starts here
    #         output = 'Bingo! you guessed it right, but you do not win any prizes!'
    #         mb.showinfo("Hint: ", output)
    #         break
    #         # New block ends here
    #     elif guess < number:
    #         output = 'No, the number is a  higer than that'
    #         mb.showinfo("Hint: ", output)
    #     else:
    #         output = 'No, the number is a  lower than that'
    #         mb.showinfo("Hint: ", output)
    #     
    # print('Done')
     
     

     9创建网页

    1. 下载并安装python 2.7 32 bit
     
    2. 下载并安装easy_install windows installer (python 2.7 32bit)
     

    3. 安装 lpthw.web

       windows 命令行:  C:Python27Scriptseasy_install lpthw.web
     
     
    5. 目录下创建 app.py:
     
    import web
     
    urls = (
      '/', 'index'
    )
     
    app = web.application(urls, globals())
     
    class index:
        def GET(self):
            greeting = "Hello World"
            return greeting
     
    if __name__ == "__main__":
        app.run()
     
    6. Windows cmd 运行:
     
    7. 打开浏览器:localhost:8080
     

  • 相关阅读:
    webpack学习04--打包图片资源
    webpack学习03--打包HTML资源
    webpack学习02--打包样式资源
    webpack学习01--基本使用
    Node.js学习02--创建express服务
    Node.js学习01--npm常用命令
    CSS3的flex布局
    PictureCleaner 官方版 v1.1.5.0607,免费的图片校正及漂白专业工具,专业去除文档图片黑底麻点杂色,规格化A4、B5尺寸输出,还你一个清晰的文本。
    python常识系列22-->jsonpath模块解析json数据
    杂七杂八的问题处理05--jmeter解决部分情况下jtl报告转html报告报错
  • 原文地址:https://www.cnblogs.com/AlvinSui/p/8032203.html
Copyright © 2011-2022 走看看