10月 222020
 
# 列表操作方式的效率比较
import time

a = []
# t0 = time.clock()  # 异常:AttributeError: module 'time' has no attribute 'clock'
# https://docs.python.org/3/whatsnew/3.8.html
# https://docs.python.org/3/library/time.html#time.perf_counter
# 该函数在python3.3废弃,在python3.8移除
t0 = time.perf_counter()
for i in range(1, 20000):
    a.append(i)
print(time.perf_counter() - t0, 'seconds process time')

t0 = time.perf_counter()
b = [i for i in range(1, 20000)]
print(time.perf_counter() - t0, 'seconds process time')
C:\Users\harveymei\PycharmProjects\hellopython\venv\Scripts\python.exe C:/Users/harveymei/PycharmProjects/hellopython/hello.py
0.0017573999999999992 seconds process time
0.0005343000000000014 seconds process time

Process finished with exit code 0
# 列表操作方式的效率比较
import time

a = []
# t0 = time.clock()  # 异常:AttributeError: module 'time' has no attribute 'clock'
# https://docs.python.org/3/whatsnew/3.8.html
# https://docs.python.org/3/library/time.html#time.perf_counter
# 该函数在python3.3废弃,在python3.8移除
t0 = time.perf_counter()  # 调用函数返回精确浮点性能计数值,两次调用返回值的差计算程序运行时间
for i in range(1, 20000):
    a.append(i)
t1 = time.perf_counter()
print('T0 is', t0)
print('T1 is', t1)
print(t1 - t0, 'seconds process time')

t0 = time.perf_counter()
b = [i for i in range(1, 20000)]
print(time.perf_counter() - t0, 'seconds process time')
C:\Users\harveymei\PycharmProjects\hellopython\venv\Scripts\python.exe C:/Users/harveymei/PycharmProjects/hellopython/hello.py
T0 is 0.0509396
T1 is 0.052513
0.0015733999999999956 seconds process time
0.0005889999999999992 seconds process time

Process finished with exit code 0
10月 222020
 
# -*- coding:utf-8 -*-
# 数据结构,包括列表lists,字典dictionaries,元组tuples,集合sets

# 数据结构中的推导式或列表解析式
# 将10个元素装入列表,普通写法
a = []
for i in range(1, 11):
    a.append(i)
print(a)

# 列表解析式写法(方便,高效)
b = [i for i in range(1, 11)]
print(b)
C:\Users\harveymei\PycharmProjects\hellopython\venv\Scripts\python.exe C:/Users/harveymei/PycharmProjects/hellopython/datastructure.py
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Process finished with exit code 0
10月 222020
 
# -*- coding:utf-8 -*-
# 数据结构,包括列表lists,字典dictionaries,元组tuples,集合sets

# 元组tuples中的元素是固定的,不可以修改,但可以查看索引
letters = ('a', 'b', 'c', 'd', 'e', 'f')
print(letters[0])

# 集合中的元素是无序的,不重复的任意对象
# 集合可以判断数据的从属关系
# 集合可以把数据结构中重复的元素减掉
# 集合不能被切片也不能被索引
a_set = {1, 2, 3, 4}
a_set.add(5)
print(a_set)
a_set.discard(4)
print(a_set)

# 对列表中的元素进行排序
num_list = [6, 2, 7, 4, 1, 3, 5]
print(sorted(num_list))  # 排序函数sorted()
print(sorted(num_list, reverse=True))  # 倒序排序

# 使用zip()函数同时操作多个列表
a = [3, 6, 9]
b = ['x', 'y', 'z']
# zip()函数的参数为迭代器(iterable)即可迭代的对象,可以为一个或多个
c = zip(a, b)  # zip()函数将对象中对应的元素打包成一个个元组tuples,然后返回由这些元组组成的对象
print(c)  # zip函数的返回值是zip类的对象,可以通过list()强制转为list列表
print(list(c))
# 多重循环
for a, b in zip(a, b):
    print(b, 'is', a)
C:\Users\harveymei\PycharmProjects\hellopython\venv\Scripts\python.exe C:/Users/harveymei/PycharmProjects/hellopython/datastructure.py
a
{1, 2, 3, 4, 5}
{1, 2, 3, 5}
[1, 2, 3, 4, 5, 6, 7]
[7, 6, 5, 4, 3, 2, 1]
<zip object at 0x0000029CD11E7080>
[(3, 'x'), (6, 'y'), (9, 'z')]
x is 3
y is 6
z is 9

Process finished with exit code 0
10月 222020
 
# -*- coding:utf-8 -*-
# 数据结构,包括列表lists,字典dictionaries,元组tuples,集合sets

# 字典中的数据必须是以键值对形式出现
# 键(key)不可以重复,而值(value)可以重复
# 键是不可变的,也就是无法修改的
nasdaq_code = {
    'BIDU': 'Baidu',  # 【pycharm:PEP 8: E231 missing whitespace after ':' 键值对冒号右侧有空格】
    'SINA': 'Sina',
    'YOKU': 'Youku'
}
print(nasdaq_code)

# 字典中的键值不会有重复,相同键值只出现一次
a = {'key': 123, 'key': 123}  # 【pycharm:Dictionary contains duplicate keys 'key'】
print(a)

# 与列表不同,字典没有添加单一元素的方法
nasdaq_code['FB'] = 'Facebook'
print(nasdaq_code)

# 字典中添加多个元素的方法
nasdaq_code.update({'AMZN': 'Amazon', 'TSLA': 'Tesla'})
print(nasdaq_code)

# 字典中删除元素使用del方法
del nasdaq_code['AMZN']
print(nasdaq_code)

# 字典使用花括号,但索引内容时使用方括号
b = nasdaq_code['TSLA']
print(b)
C:\Users\harveymei\PycharmProjects\hellopython\venv\Scripts\python.exe C:/Users/harveymei/PycharmProjects/hellopython/datastructure.py
{'BIDU': 'Baidu', 'SINA': 'Sina', 'YOKU': 'Youku'}
{'key': 123}
{'BIDU': 'Baidu', 'SINA': 'Sina', 'YOKU': 'Youku', 'FB': 'Facebook'}
{'BIDU': 'Baidu', 'SINA': 'Sina', 'YOKU': 'Youku', 'FB': 'Facebook', 'AMZN': 'Amazon', 'TSLA': 'Tesla'}
{'BIDU': 'Baidu', 'SINA': 'Sina', 'YOKU': 'Youku', 'FB': 'Facebook', 'TSLA': 'Tesla'}
Tesla

Process finished with exit code 0

10月 222020
 
# -*- coding:utf-8 -*-
# 数据结构,包括列表lists,字典dictionaries,元组tuples,集合sets
# https://docs.python.org/3/tutorial/datastructures.html

Weekday = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(Weekday[0])

# 列表中的每一个元素都是可变的
# 列表中的元素是有序的,也就是每一个元素都有一个位置
# 列表可以容纳Python中的任何对象

all_in_list = [
    1,  # 整数(integer numbers)
    1.0,  # 浮点数(floating point numbers)
    'a word',  # 字符串(strings)
    print(168),  # 函数(functions)
    True,  # 布尔值(boolean value)
    [1, 2],  # 列表中套列表(lists)
    (1, 2),  # 元组(tuples)
    {'key': 'value'}  # 字典(dictionaries)
]

# 列表插入,插入元素(item)的位置(position)是指定元素位置之前的位置
fruit = ['pineapple', 'pear']
fruit.insert(1, 'grape')  # 插入方法method
print(fruit)

# 列表插入的另一种方法
fruit[0:0] = ['Orange']  # 列表最前面,列表索引
print(fruit)

# 列表删除
cars = ['benz', 'bmw', 'audi', 'byd']
cars.remove('bmw')  # 删除方法method
print(cars)

# 替换修改
cars[0] = 'ford'  # 替换第1个元素benz,列表索引
print(cars)

# 列表删除的另一种方法是,使用del关键字
del cars[0:2]  # 删除第1-2个元素ford和audi,列表索引
print(cars)

# 字符串分片和列表索引,都支持正反两种索引方式
# 正向索引编号Positive Index Number和反向索引编号Negative Index Number
# https://www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3

# 元素周期表(列表索引)
periodic_table = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne']
print(periodic_table[0])  # H
print(periodic_table[-2])  # F
print(periodic_table[0:3])  # H He Li
print(periodic_table[-10:-7])  # H He Li
print(periodic_table[-10:])  # 打印全部
print(periodic_table[:9])  # H - F 打印第1-8个元素
C:\Users\harveymei\PycharmProjects\hellopython\venv\Scripts\python.exe C:/Users/harveymei/PycharmProjects/hellopython/datastructure.py
Monday
168
['pineapple', 'grape', 'pear']
['Orange', 'pineapple', 'grape', 'pear']
['benz', 'audi', 'byd']
['ford', 'audi', 'byd']
['byd']
H
F
['H', 'He', 'Li']
['H', 'He', 'Li']
['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne']
['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F']

Process finished with exit code 0
10月 212020
 
# -*- coding:utf-8 -*-
def number_test():  # 定义函数,测试号码所属运营商
    while True:  # 循环提示用户输入号码,在输入长度不匹配或输入号码匹配运营商号段列表时终止循环
        number = input('Enter your number: ')  # 用户输入赋值变量
        china_mobile = [134, 135, 136, 137, 138, 139, 150, 151, 152,
                        157, 158, 159, 182, 183, 184, 187, 188, 147, 178, 1705]
        china_unicom = [130, 131, 132, 155, 156, 185, 186, 145, 176, 1709]
        china_telecom = [133, 153, 180, 181, 189, 177, 1700]
        first_three = int(number[0:3])  # 取用户输入字符串第1-3位转换整数类型并赋值变量
        first_four = int(number[0:4])  # 取用户输入字符串第1-4位转换整数类型并赋值变量

        if len(number) == 11:  # 判断用户输入长度是否为11位

            if first_three in china_mobile or first_four in china_mobile:  # 判断用户输入前三位或前四位是否在移动号段列表中
                print('Operator: China Mobile')
                print('We\'re sending verification code via text to your phone: ', number)
                break  # 匹配则终止判断
            elif first_three in china_telecom or first_four in china_telecom:  # 如果不在移动号段列表,继续判断用户输入前三位是否在电信号段列表中
                print('Operator: China Telecom')
                print('We\'re sending verification code via text to your phone: ', number)
                break  # 匹配则终止判断
            elif first_three in china_unicom or first_four in china_unicom:  # 如果不在移动号段和电信号段列表,继续判断用户输入前三位是否在联通号段列表中
                print('Operator: China Unicom')
                print('We\'re sending verification code via text to your phone: ', number)
                break  # 匹配则终止判断
            else:  # 用户输入不存在于号段列表中则提示没有此运营商
                print('No such a operator')

        else:  # 反之,则提示用户输入长度不足
            print('Invalid length, your number should be in 11 digits')


# 调用函数
number_test()
10月 212020
 
# -*- coding:utf-8 -*-
import random  # 导入内置模块,用以产生随机数【pycharm:行内注释,#号前需空两个字符,#号后需空一个字符】


# 定义摇色子函数,次数参数默认为3,点数参数默认为空
def roll_dice(numbers=3, points=None):  # 【PEP 8: E251 unexpected spaces around keyword / parameter equals】
    print('>>>>> ROLL THE DICE! <<<<<')
    if points is None:  # 判断,如果点数参数值为空,将空列表赋值给该变量
        points = []
    while numbers > 0:  # while循环,直到次数值不在大于0时终止,初始值为3,每循环一次减1
        point = random.randrange(1, 7)  # 在1-6范围内取随机数赋值给点数
        points.append(point)  # 将点数追加写入列表
        numbers = numbers - 1  # 最多循环3次,成功获取3个随机数,跳出循环
    return points  # 返回生成的3个随机数


def roll_result(total):  # 定义比较大小函数
    big = 11 <= total <= 17  # 比较运算的布尔值True赋值给变量【pycharm:变量应当是小写】
    small = 4 <= total <= 10  # 比较运算的布尔值True赋值给变量
    if big:  # 判断,如果big == True 则返回提示Big
        return 'Big'
    elif small:  # 继续判断,如果small == True 则返回Small提示
        return 'Small'


def start_game():  # 定义启动游戏函数
    your_money = 1000  # 初始持有金额并赋值变量【PEP 8: E225 missing whitespace around operator】
    while your_money > 0:  # 循环,游戏重复开始,直到持有金额不再大于0时终止
        print('>>>>> GAME STARTS! <<<<<')
        choices = ['Big', 'Small']  # 定义用户有效输入值列表并赋值变量
        your_choice = input('Big or Small: ')  # 提示用户输入并赋值变量

        if your_choice in choices:  # 执行判断,是否用户输入值,存在于列表中,匹配则继续执行
            your_bet = int(input('How much you wanna bet? '))  # 用户输入下注金额赋值变量
            points = roll_dice()  # 调用函数生成随机数
            total = sum(points)  # 调用函数计算随机数累加值并赋值变量
            win = your_choice == roll_result(total)  # 调用roll_result(total)函数取得实际大小值,与用户输入值布尔运算,取得布尔值赋值变量
            if win:  # 判断,win == True则执行
                print('The points is ', points, ' You Win')  # 打印点数
                print('You gained {}, you have {} now'.format(your_bet, your_money + your_bet))  # 打印下注值和当前持有值
                your_money = your_money + your_bet  # 更新当前持有值
            else:  # 判断,反之,youWin == False则执行
                print('The points is ', points, ' You Lose')
                print('You lose {}, you have {} now'.format(your_bet, your_money - your_bet))
                your_money = your_money - your_bet
        else:  # 反之,提示输入无效字符
            print('Invalid Words')
    else:  # 反之,持有金额小于等于0时,提示游戏结束,退出执行
        print('GAME OVER')


start_game()  # 调用函数启动游戏【PEP 8: E305 expected 2 blank lines after class or function definition, found 1】
10月 212020
 
# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
10月 212020
 
PS D:\Python\mysite> django-admin.exe

Type 'django-admin help <subcommand>' for help on a specific subcommand.

Available subcommands:

[django]
check
compilemessages
createcachetable
dbshell
diffsettings
dumpdata
flush
inspectdb
loaddata
makemessages
makemigrations
migrate
runserver
sendtestemail
shell
showmigrations
sqlflush
sqlmigrate
sqlsequencereset
squashmigrations
startapp
startproject
test
testserver
Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.). 
PS D:\Python\mysite>
10月 192020
 

安装Django(提示已安装)

PS D:\Python> python.exe -m pip install Django
Requirement already satisfied: Django in c:\users\harveymei\appdata\local\programs\python\python39\lib\site-packages (3.1.2)
Requirement already satisfied: asgiref~=3.2.10 in c:\users\harveymei\appdata\local\programs\python\python39\lib\site-packages (from Django) (3.2.10)
Requirement already satisfied: sqlparse>=0.2.2 in c:\users\harveymei\appdata\local\programs\python\python39\lib\site-packages (from Django) (0.4.1)
Requirement already satisfied: pytz in c:\users\harveymei\appdata\local\programs\python\python39\lib\site-packages (from Django) (2020.1)
PS D:\Python> 

查看Django版本信息

import django
print(django.get_version())

PS D:\Python> & C:/Users/harveymei/AppData/Local/Programs/Python/Python39/python.exe d:/Python/hello.py
3.1.2
PS D:\Python>

命令行

PS D:\Python> python.exe -m django --version
3.1.2
PS D:\Python>

PS D:\Python> python.exe -m pip show django
Name: Django
Version: 3.1.2
Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design.
Home-page: https://www.djangoproject.com/
Author: Django Software Foundation
Author-email: foundation@djangoproject.com
License: BSD-3-Clause
Location: c:\users\harveymei\appdata\local\programs\python\python39\lib\site-packages
Requires: sqlparse, pytz, asgiref
Required-by:
PS D:\Python>

创建项目

PS D:\Python> django-admin.exe startproject mysite
PS D:\Python> 

目录结构

mysite/             #根目录可以任意修改
    manage.py       #管理Django项目的命令行工具
    mysite/         #包名
        __init__.py #空文件,告诉Python将该目录当作python包
        settings.py #项目配置文件
        urls.py     #项目URL声明
        asgi.py     #项目运行在ASGI兼容服务器的入口
        wsgi.py     #项目运行在WSGI兼容服务器的入口

启动Django内置轻量级Web服务器

PS D:\Python> cd .\mysite\
PS D:\Python\mysite> python.exe .\manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
October 19, 2020 - 11:43:15
Django version 3.1.2, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/ 
Quit the server with CTRL-BREAK.

指定监听端口

PS D:\Python\mysite> python.exe .\manage.py runserver 8080
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
October 19, 2020 - 11:53:53
Django version 3.1.2, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8080/
Quit the server with CTRL-BREAK.
[19/Oct/2020 11:54:05] "GET / HTTP/1.1" 200 16351
[19/Oct/2020 11:54:06] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[19/Oct/2020 11:54:06] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876
[19/Oct/2020 11:54:06] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 86184
[19/Oct/2020 11:54:06] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692    
Not Found: /favicon.ico
[19/Oct/2020 11:54:06] "GET /favicon.ico HTTP/1.1" 404 1972

指定监听端口和IP(0是0.0.0.0的简写)

PS D:\Python\mysite> python.exe .\manage.py runserver 0:8080