python基礎--練習題


計算圓的面積

#encoding=utf-8
#計算圓的面積,並且把面積打印出來,保留小數點后10位。
import math
r=int(input('請輸入圓的半徑:'))
x=(math.pi)*r*r
print('%0.10f'%x)

求N個數字的平均值

N=10
sum=0
count=0
print('input 10 numbers: ')
while count < N:
    number = float(input())
    sum = sum + number
    count = count + 1
average = sum / N
print('N=%s,Sum=%s'%(N,sum))
print('average=%0.2f'%average)

九九乘法表

for i in range(1,10):
    for j in range(1,i+1):
        print('%s*%s=%s' %(i,j,i*j),end=' ')
    print()

隨機生成郵箱

#encoding=utf-8
import string
import random
def email(eamil_counts):#定義一個函數,用來傳生成多少郵箱
    emails=set()#定義一個空集合
    list=['163.com','qq.com','sina.com','126.com']#定義郵箱段列表
    f=0#計數器
    while f < eamil_counts:#集合長度小於實參,則執行下面的代碼,生成郵箱
        end_email = random.choice(list)  # 隨機選擇一個郵箱段
            # 生成6-12位的隨機數,返回一個list
        start_email=random.sample(string.digits+string.ascii_letters+string.punctuation,random.randint(6,12))
            #print(start_email)
            #print(new_startemail)
        start = ''.join(start_email)  # 把生成的隨機數連接起來變成字符串
            #print(start)
        new_startemail = set(start_email)  # 把生成的隨機數轉成集合
            #判斷生成的有限前面的6-12位數是否同時包含大小寫字母、數字、特殊符號,如果包含,則添加到集合里面。
        if (new_startemail & (set(string.digits))) \
                and (new_startemail & set(string.ascii_uppercase)) \
                and (new_startemail & set(string.ascii_lowercase)) \
                and (new_startemail & set(string.punctuation)) :#非空即真
            full = start + '@' + end_email + '\n'  # 拼接成郵箱
            emails.add(full)#數據放到集合里
            f=len(emails)#定義f為集合的長度,f每次都自動加1
    with open('email.txt', 'w') as fw:  # w方式打開文件,如果文件不存在則創建文件
        fw.writelines(emails)  # 把集合里面的數據逐行加入到文件里面
email(100)

隨機生成11位不重復的手機號碼,並存在文件里面。

#encoding=utf-8
import string#導入string模塊
import random#導入隨機數
def phone(nums):#定義一個函數,用來傳入想要生成的號碼數量
    nums_count=set()#定義一個空集合,用來放電話號碼,集合可以自動去重
    list=['132','133','150','155','138','139','180','182','188','189','135']#定義號碼段列表
    f=0#計數器
    while f < nums:#為集合的長度,如果f小於實參,則一直循環生成電話號
        start=random.choice(list)#隨機選擇一個號碼段
        ends=random.sample(string.digits,8)#隨機生成8為數字,返回的是列表
        end=''.join(ends)#列表轉成字符串
        full=start+end +'\n'#拼接電話號碼
        nums_count.add(full)#電話號碼放在集合里面,可以自動去重
        f=len(nums_count)#重新定義f為集合的長度,如果f小於實參,則一直循環生成電話號
    with open('phone.txt','w',encoding='utf-8') as fw:#以寫入的方式打開文件,文件不存在,則會創建文件
        fw.writelines(nums_count)#把集合里面的數據逐行寫入到文件里面
phone(100)#調用函數,傳入一個實參

判斷一個小數是否是合法的小數

def is_float(s):
    s=str(s)
    if s.count('.')==1:
        left,right=s.split('.')
        if left.isdigit() and right.isdigit():
            print('正小數')
            return True
        elif left.startswith('-') and left.count('-') == 1 and left[1:].isdigit() and right.isdigit():
            print('負小數')
            return True
    print('不合法')
    return False

雙色球

# 1、寫一個函數,輸入N產生N條雙色球號碼,
# 紅球 6個  01-33
# 藍球 1個  1-16,
# 產生的雙色球號碼不能重復,寫到一個文件里面,每一行是一條
# 紅球:01 03 04 05 06 19 藍球:16
# 紅球需要升序排序
import random
import string
def nums(count):
    listnum = set()
    while len(listnum)<count:
        redball=random.sample(range(1,34),6)#list
        redball.sort()
        #print(redball)
        redballs=' '.join('%02d' %i for i in redball)#字符串、列表生成式
        blueball = random.sample(range(1,17), 1)
        blueball = ' '.join('%02d' %i for i in blueball)  # 字符串
        full=(redballs + ' '+ blueball+'\n')
        listnum.add(full)
    print(listnum)
    with open('double_ball.txt', 'w', encoding='utf-8') as fw:  # 以寫入的方式打開文件,文件不存在,則會創建文件
        fw.writelines(listnum)  # 把集合里面的數據逐行寫入到文件里面
nums(100)

商品管理

# 2、寫一個商品管理的程序
# 1 添加商品  商品名稱:商品已經存在的話,要提示
#             商品價格: 校驗,是大於0的數字
#             商品數量:校驗,只能是大於0的整數
# 2 刪除商品  商品名稱:商品不存在的話,要提示
# 3 查看商品 for循環 顯示所有的商品信息
# 4 退出
import json
products='test.json'
#讀文件
def read_product(filename):
    f=open(filename,encoding='utf-8')
    content=json.load(f)#json轉成字典
    #print(content)
    return content

#寫入文件
def write_file(dic):
    fw = open('test.json', 'w', encoding='utf-8')
    json.dump(dic, fw, indent=4, ensure_ascii=False)
    fw.close()

#校驗價格
def is_price(s):
    s = str(s)
    if s.count('.') == 1:
        left, right = s.split('.')
        if left.isdigit() and right.isdigit():
            #print('正小數')
            return True
        elif left.startswith('-') and left.count('-') == 1 and left[1:].isdigit() and right.isdigit():
            print('價格不能為負小數')
            return False
    elif s.isdigit():
        s = int(s)
        if s == 0:
            print('價格不能為0')
            return False
        else:
            #print('正數')
            return True
    else:
        print('價格不能為負數或者字母或者符號')
        return False
    print('價格不能為負數或者字母或者符號')
    return False

#校驗數量
def is_counts(c):
    c = str(c)
    if c.isdigit():
        c = int(c)
        if c == 0:
            print('數量不能為0')
            return False
        else:
            #print('正數')
            return True
    else:
        print('數量只能是大於0的正整數')
        return False

#添加商品
def add_product():
    product_dict=read_product(products)#讀文件 字典格式
    print(product_dict)
    name=input('請輸入商品名稱: ').strip()
    price=input('請輸入商品價格:').strip()
    count=input('請輸入商品數量: ').strip()
    if name!='' and price!='' and count!='':
        if name in product_dict:
            print('商品已經存在')
        elif not  is_price(price):
            print('商品價格有誤')
        elif not is_counts(count):
            pass
            #print('商品數量有誤')
        else:
            product_dict[name]={"price":price,"count":count}
            write_file(product_dict)
            print('添加成功')
    else:
        print('商品、價格、數量不能為空')

#刪除商品
def del_product():
    product_dict=read_product(products)#讀文件
    del_name=input('請輸入要刪除商品的名稱: ').strip()
    if del_name!='':
        if product_dict.get(del_name) :
            product_dict.pop(del_name)
            write_file(product_dict)
            print('刪除成功')
        else:
            print('商品名稱不存在')
    else:
        print('商品名稱不能為空')

#查看商品
def show_product():
    product_dict = read_product(products)
    for key in product_dict:
        print(key,product_dict[key])

#退出
def quit_sys():
    message=input('輸入q退出程序: ')
    if 'q':
        exit

choice = input('1、add_product\n'
               '2、del_product\n'
               '3、show_product \n'
               '4、quit_sys \n')
func_map = {"1":add_product,"2":del_product,"3":show_product,"4":quit_sys}
if choice in func_map:
    func_map[choice]()#函數調用
else:
    print('輸入有誤!')

每分鍾監控服務器日志,IP請求超過200次的,加入黑名單

import time
point=0
while True:
    with open('access.log',encoding='utf-8') as fw:
       ips = {}
       fw.seek(point)
       for line in fw.readlines():
           #print(line)
           ip=line.split()[0]
           #print(ip)
           if ip not in ips:
               ips[ip]=1
           else:
               ips[ip]+=1
       point=fw.tell()
       for k,count in ips.items():
            if count>200:
                print('%s加入黑名單'%k)
    time.sleep(60)

 



#、 寫一個函數,傳入一個路徑和一個關鍵字(關鍵字是文件內容),找到文件內容里面有這個關鍵字的txt文件

# 1、去找到這個目錄下面的所有.txt文件
# 2、循環打開所有的txt文件,讀到文件內容
# 3、判斷關鍵字是否存在文件里面
import os

def find_content(path,key_word):
    for cur_path,dirs,files in os.walk(path):
        for file in files:
            if file.endswith('log'):
                print(file)
                abs_file_path = os.path.join(cur_path,file)
                res = open(abs_file_path,encoding='utf-8').read()
                if key_word in res:
                    print('文件內容在',abs_file_path)

#2、刪除3天前的日志文件
    #1、要獲取到所有的日志文件 os.walk()
    #2、先獲取到文件的時間
    #3、要判斷文件的日期是否在三天前    當天的日期的時間戳    - 60*60*24*3

import time
def timestampToStr(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
    #時間戳轉格式化好的時間
    if timestamp:
        time1 = time.localtime(timestamp)
        res = time.strftime(format, time1)
    else:
        res = time.strftime(format)
    return res
#20180304153958
def strTotimestamp(str=None,format='%Y%m%d%H%M%S'):
    #格式化的時間轉時間戳
    if str:
        timep = time.strptime(str, format)
        res = time.mktime(timep)
    else:
        res = time.time()
    return int(res)

def clean_log(path,day=3):
    for cur_path, dirs, files in os.walk(path):
        for file in files:
            if file.endswith('log'):
                f_time = file.split('.')[0].split('_')[-1]
                file_timestamp = strTotimestamp(f_time,'%Y-%m-%d')
                cur_timestamp = strTotimestamp(time.strftime('%Y-%m-%d'),'%Y-%m-%d')
                if (cur_timestamp - file_timestamp) >= 60*60*24*day:#判斷文件的時間是否大於3天
                    os.remove(os.path.join(cur_path,file)

 

 

 3、寫一個注冊的功能,要求數據存在數據庫里面

        1、名字為空、已經存在都要校驗

        2、校驗通過之后,密碼要存成密文的。

import pymysql
def my_db(sql):
    conn = pymysql.connect(host='ip',user='jxz',password='123456',
                    db='jxz',port=3306,charset='utf8',autocommit=True)
    cur = conn.cursor(pymysql.cursors.DictCursor)
    cur.execute(sql)
    res = cur.fetchone() #{'username':'nhy'}  {}
    cur.close()
    conn.close()
    return res
import hashlib
def my_md5(s,salt=''):
    s = s+salt
    news = str(s).encode()
    m = hashlib.md5(news)
    return m.hexdigest()

def reg():
    for i in range(3):
        user =input('username:').strip().upper()
        pd = input('password:').strip()
        cpd = input('cpwd:').strip()
        sql='select username from app_myuser where username = "%s";'%user
        if len(user) not in range(6,11) or len(pd) not in range(6,11): # 6 7 8 9 10
            print('賬號/密碼長度錯誤,6-10位之間')
        elif pd != cpd:
            print('兩次輸入密碼不一致')
        elif my_db(sql):
            print('用戶已存在')
        else:
            md5_passwd = my_md5(pd)
            insert_sql= 'insert into app_myuser (username,passwd,is_admin) value ("%s","%s",1);'%(
                user,md5_passwd
            )
            my_db(insert_sql)
            print('注冊成功!')
            break
    else:
        print('失敗次數過多!')

 

 4、登陸的功能

        登錄的賬號密碼從數據庫里面取,

        如果輸入用戶不存在要提示

import pymysql
def my_db(sql):
    conn = pymysql.connect(host='ip',user='jxz',password='123456',
                    db='jxz',port=3306,charset='utf8',autocommit=True)
    cur = conn.cursor(pymysql.cursors.DictCursor)
    cur.execute(sql)
    res = cur.fetchone() #{'username':'nhy'}  {}
    cur.close()
    conn.close()
    return res
import hashlib
def my_md5(s,salt=''):
    s = s+salt
    news = str(s).encode()
    m = hashlib.md5(news)
    return m.hexdigest()

def login():
    for i in range(3):
        username = input('請輸入用戶名:').strip().upper()
        password = input('請輸入密碼:').strip()
        sql='select username,passwd from app_myuser where username = "%s";'%username
        if username =='' or password =='':
            print('賬號/密碼不能為空')
        else:
            res = my_db(sql) # {'username':nhy  'passwd':'xxxxx'}
            if res:
                if my_md5(password) == res.get('passwd'):
                    print('登陸成功!')
                    break
                else:
                    print('密碼錯誤!')
            else:
                print('用戶不存在')

    else:
        print('錯誤次數過多!')

把金牛座.xls中的漢字人名轉成用戶名,寫到后面的單元格中,excel在群文件

        例如:網絡-安求鳳 : wl_anqiufeng

                   現場-楊帆 : xc_yangfan

                  蹭課-張哲: ck_zhangzhe

import xpinyin
import xlrd
import string
from xlutils import copy
book=xlrd.open_workbook('金牛座.xls')
sheet=book.sheet_by_index(0)
p=xpinyin.Pinyin()
new_book = copy.copy(book)
new_sheet = new_book.get_sheet(0)
for i in range (1,sheet.nrows):#sheet.ncols代表總共有多少行
    name=sheet.row_values(i)[0]
    name_pinyin=p.get_pinyin(name,"")
    name_pinyin=name_pinyin.replace('wangluo','wl').replace('xianchang','xc').replace('cengke','ck')
    for n in name_pinyin:
        if n not in string.ascii_lowercase:#判斷如果不是字母的話,就替換
            res=name_pinyin.replace(n,'_')
            xhx_count=res.count('_')#取下划線的個數
            if xhx_count>1:#判斷如果下划線大於1,就把多個下划線替換為一個下划線
                res=res.replace('_'*xhx_count,'_')
    new_sheet.write(i,1,res)
new_book.save('金牛座.xls')

 

下載圖片
import threading
import requests
import time
from hashlib import md5
res = []
def down_load_pic(url):
    #下載圖片的url
    r = requests.get(url)
    file_name = md5(r.content).hexdigest()#把文件md5之后字符串當做文件名
    with open(file_name+'.jpg','wb') as fw:
        fw.write(r.content)
    print('%s下載完成'%file_name)
    res.append(file_name)

urls = [
    'http://www.nnzhp.cn/wp-content/uploads/2018/12/110405th7jtus7gjjlywnl.jpg',
    'http://www.nnzhp.cn/wp-content/themes/QQ/images/thumbnail.png',
    'http://www.nnzhp.cn/wp-content/uploads/2018/08/f38a12137574f4333f7686f7e75a06fb8bd9fed537ea59-pRwNuK_fw658.jpeg',
    'http://www.nnzhp.cn/wp-content/uploads/2018/08/c1bba9a47cfe8fe7000f137f020ad623.png',
]
start_time = time.time()
#單線程
# for url in urls:
#     down_load_pic(url)

#多線程
for url in urls:
    t = threading.Thread(target=down_load_pic,args=(url,) )
    t.start()
while threading.active_count()!=1:#等待子線程運行完成
    pass
print(res)
end_time = time.time()
print('下載完成,下載時間是 %s'% (end_time-start_time))

判斷一個IP是否是合法的IP地址

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM