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
10 月 152020
 
import random #引用
#定义函数
def roll_dice(number=3, points=None): #指定参数默认值
    print('>>>>> ROLL THE DiCE! <<<<<')
    if points is None: #判断,如果point为空,默认赋值为空
        points = [] #空列表赋值变量
    while number > 0: #循环,number大于0则执行
        point = random.randrange(1,7) #生成随机数赋值变量
        points.append(point) #将变量写入列表
        number = number - 1 #每次将number减1,循环3次,为0时退出循环
    return points #调用函数,返回已赋值变量(3个随机数)

#定义函数
def roll_result(total):
    isBig = 11 <= total <= 18 #11-18之间的值赋值变量
    isSmall = 3 <= total <=10 #3-10之间的值赋值变量
    if isBig: #判断,返回大或小
        return 'Big'
    elif isSmall:
        return 'Small'

#定义函数
def start_game():
    print('>>>>> STARTS! <<<<<')
    choices = ['Big', 'Small'] #列表赋值变量
    your_choice = input('Big or Small: ') #用户输入赋值变量
    you_have = 1000 #初始金额
    you_bet = input('How much you wanna bet? ') #输入下注金额
    if your_choice in choices: #判断用户输入是否存在于列表中
        points = roll_dice() #调用函数获得随机数并赋值变量
        total = sum(points) #计算随机数的和
        youWin = your_choice == roll_result(total) #用户输入与函数计算结果比较返回True并赋值变量

        if youWin: #if True 打印成功
            print('The points are ', points, 'You win!')
            
            #重新计算持有金额并打印金额信息
            you_have = you_have + int(you_bet)
            print('You gained ', you_bet,', you have ', you_have, 'now')
        else: #反之为False,打印失败
            print('The points are ', points, 'You lose!')
            
            #重新计算持有金额并打印金额信息
            you_have = you_have - int(you_bet)
            #判断,持有金额大于0的情况和小于0的情况
            if you_have > 0: #打印信息并继续
                print('you lose ', you_bet,', you have ', you_have,' now')
            else: #反之,游戏结束
                print('you lose ', you_bet,', you have ', you_have,' now')
                print('GAME OVER')
                exit(0)

    else: #其他情况(用户输入与列表中元素不一致),提示用户输入无效字符
        print('Ivalid Words')
        start_game() #再次调用函数

#调用函数,执行
start_game()
10 月 152020
 
import random #引用
#定义函数
def roll_dice(number=3, points=None): #指定参数默认值
    print('>>>>> ROLL THE DiCE! <<<<<')
    if points is None: #判断,如果point为空,默认赋值为空
        points = [] #空列表赋值变量
    while number > 0: #循环,number大于0则执行
        point = random.randrange(1,7) #生成随机数赋值变量
        points.append(point) #将变量写入列表
        number = number - 1 #每次将number减1,循环3次,为0时退出循环
    return points #调用函数,返回已赋值变量(3个随机数)

#定义函数
def roll_result(total):
    isBig = 11 <= total <= 18 #11-18之间的值赋值变量
    isSmall = 3 <= total <=10 #3-10之间的值赋值变量
    if isBig: #判断,返回大或小
        return 'Big'
    elif isSmall:
        return 'Small'

#定义函数
def start_game():
    print('>>>>> STARTS! <<<<<')
    choices = ['Big', 'Small'] #列表赋值变量
    your_choice = input('Big or Small: ') #用户输入赋值变量
    if your_choice in choices: #判断用户输入是否存在于列表中
        points = roll_dice() #调用函数获得随机数并赋值变量
        total = sum(points) #计算随机数的和
        youWin = your_choice == roll_result(total) #用户输入与函数计算结果比较返回True并赋值变量

        if youWin: #if True 打印成功
            print('The points are ', points, 'You win!')
        else: #反之为False,打印失败
            print('The points are ', points, 'You lose!')
    else: #其他情况,提示用户输入无效字符
        print('Ivalid Words')
        start_game() #再次调用函数

#调用函数,执行
start_game()
PS D:\Python> & C:/Users/harveymei/AppData/Local/Programs/Python/Python39/python.exe d:/Python/hello.py
>>>>> STARTS! <<<<<
The points are  [3, 5, 2] You win!
PS D:\Python> & C:/Users/harveymei/AppData/Local/Programs/Python/Python39/python.exe d:/Python/hello.py
>>>>> STARTS! <<<<<
Big or Small: haha
Ivalid Words
>>>>> STARTS! <<<<<
Big or Small: Big
>>>>> ROLL THE DiCE! <<<<<
The points are  [6, 4, 5] You win!
PS D:\Python> & C:/Users/harveymei/AppData/Local/Programs/Python/Python39/python.exe d:/Python/hello.py
>>>>> STARTS! <<<<<
Big or Small: Small
>>>>> ROLL THE DiCE! <<<<<
The points are  [5, 3, 6] You lose!
PS D:\Python>
10 月 132020
 
import random #引入random库

#在指定起始值范围内随机取值
point1 = random.randrange(1,7)
point2 = random.randrange(1,7)
point3 = random.randrange(1,7)

#
def points():
    return str(point1), str(point2), str(point3) #返回三个变量值

#累加计算三个随机数并判断大小
def calc():
    values = point1 + point2 + point3 #累加计算
    if 11 <= values <= 18:
        return 'Big'
    elif 3 <= values <= 10:
        return 'Small'

#执行
print('>>> START <<<')
choose = input('Input Big or Small: ') #用户输入大小赋值变量
abc = points() #调用函数返回三个随机数并赋值变量
print('The points are {}'.format(abc)) #使用格式化字符串打印变量值

#定义状态列表,并判断状态
status = ['You are win!', 'You are lose!']
if choose == calc(): #判断,用户输入与函数计算返回值比较运算,一致返回成功
    print(status[-2])
else: #反之,不一致返回失败
    print(status[-1])
PS D:\Python> & C:/Users/harveymei/AppData/Local/Programs/Python/Python39/python.exe d:/Python/hello.py
>>> START <<<
Input Big or Small: Big
The points are ('5', '6', '3')
You are win!
PS D:\Python>