python大一基础题_python基础练习题
# 利用pip, 安裝第三方模塊requests, 描述你用什么方法來確認(rèn)安裝是成功的。
print('進(jìn)入python環(huán)境,導(dǎo)入requests模塊,導(dǎo)入成功.')
# 把2.918 轉(zhuǎn)化為整形
a = 2.918
print(int(a))
# 把10 進(jìn)制數(shù) 18 轉(zhuǎn)化為2進(jìn)制數(shù)
print(bin(18))
# 用java 替換字符串:”Python is popular” 里面的Python,并 把java 變換成JAVA
print('Python is popular'.replace('Python','java'.upper()))
# 把列表 [1, 2, 3,4 5,6,7,8]里面的2, 4, 6,8 打印出來
list = [1, 2, 3,4,5,6,7,8]
print([x for x in list if x%2==0])
# 創(chuàng)建一個字典,字典的key分別是name, sex, province , 修改原始province 的值 為新值”江蘇”
dicts = {'name':'zhangsan', 'sex':'man', 'province':'shanghai'}
dicts['province'] = 'jiangsu'
print(dicts)
Test_str="Python was created in 1989, Python is using in AI, big data, IOT."
#按下列要求對上面文字做出處理。
# ? 把上面文字中的所有大寫轉(zhuǎn)化為小寫
print(Test_str.lower())
# ? 把這段話每個單詞放到列表里面,不能包含空格。
new_str = Test_str.replace(',','').replace(' ','|')
print(new_str.split('|'))
# ? 把列表最中間的一個單詞打印出來。
print(new_str[int(len(new_str)/2)])
# 2.List1=[“python”, 5,6, 8], list2=[“python”,”5”, 6, 8,10], 對list1和list2做出如下處理:
# ? 把上面2個list的內(nèi)容合并成一個
List1=["python",5,6,8]
List2=["python","5",6,8,10]
print(List1+List2)
# ? 利用set里面的方法,對合并后的list, 去除重復(fù)元素。最 后輸出是還是list =“python”, 5,6, 8,”5”,10
set1=set(List1+List2).difference()
print(str(set1))
# 實(shí)現(xiàn)一個函數(shù),要求對一個列表里面所有數(shù)字求和,如果里 面含有非數(shù)字的元素。直接跳過。比如[1,2,3] 輸出是5, 如果 是[1,2,4,”a”] 輸出是7。 并在另外一個包(目錄)里面調(diào)用這個 函數(shù)
def fo(*args):
sum = 0
if len(args)>=1:
for arg in args:
if type(arg) == int:
sum = sum+arg
else:
continue
else:
print("無參數(shù)")
print(sum)
fo(1,2,3,'qwe')
# 實(shí)現(xiàn)一個不定長參數(shù)的函數(shù)def flexible(aa, *args, **kwargs):,
# 把傳入的參數(shù)和值打印出來。比如傳入?yún)?shù)是
def flexible(*args, **kwargs):
print(args,kwargs)
flexible(2, 3, x = 4, y = 5, *[1, 2, 3], **{'a':1,'b': 2})
# 輸出結(jié)果:(2, 3, 1, 2, 3),{'a': 1, 'y': 5, 'b': 2, 'x': 4}
# 面試題:*args, **kwargs 有什么作用print('*args, **kwargs主要用于將不定長參數(shù)傳遞給函數(shù)。*args將傳遞的參數(shù)打包成元組形式, **kwargs將傳遞的參數(shù)打包成字典形式')
通過當(dāng)前時間和函數(shù)名生成測試報告名稱,隨機(jī)字符串(大小寫字母和數(shù)字)生成測試數(shù)據(jù)
import random
import time
import string
def generate_report_name(ext='.html'):
now_time = time.strftime("%Y%m%d_%H%M%S", time.localtime())
method_name = generate_report_name.__name__
report_name = "%s_%s%s" % (method_name, now_time, ext)
return report_name
def generate_random_data(num=6):
base_data = string.ascii_uppercase + string.ascii_lowercase + string.digits
random_data = ''.join(random.SystemRandom().choice(base_data) for _ in range(num))
return random_data
print(generate_report_name())
print(generate_random_data())
----------------------------
使用logger設(shè)置日志,將日志保存到文件。
import os, logging
current_path = os.path.abspath(os.path.dirname(file))
file_path = os.path.join(current_path, "TestLog.txt")
file_name = os.path.basename(file).split('.')[0]
time_format = logging.Formatter('[%(asctime)s %(name)s_%(levelname)s] %(message)s')
log_file = logging.FileHandler(file_path)
log_file.setFormatter(time_format)
logger = logging.getLogger(str(file_name))
logger.setLevel(logging.INFO)
logger.addHandler(log_file)
logger.info("=== info")
logger.error("=== error")
logger.warning("=== warning")
----------------------------
3、查找/tomcat/log/ 目錄下的log文件,如果文件最后修改時間是在1小時之前,把次文件打包壓縮,備份到
/home/back/log 目錄下
import os
import datetime
import zipfile
def zip_log_file(src, dest):
if not os.path.exists(src) and not os.path.isdir(src):
print("源路徑不存在 或 源路徑不是目錄")
return
if not os.path.exists(dest):
os.makedirs(dest)
files = list(filter(lambda f: os.path.isfile(f) and f.endswith(".log"), os.listdir(src)))
if not files:
print("%s 目錄下無 .log 文件" % src)
for file in files:
file_full_path = os.path.join(src, file)
delay_time = datetime.timedelta(hours=1)
now_time = datetime.datetime.now()
modify_time = datetime.datetime.fromtimestamp(os.path.getmtime(file_full_path))
zip_file_full_path = os.path.join(dest, file + ".zip")
if modify_time < (now_time - delay_time):
z = zipfile.ZipFile(zip_file_full_path, 'w', zipfile.ZIP_DEFLATED)
z.write(file)
z.close()
zip_log_file("/tomcat/log/", "/tomcat/back/log")
----------------------------
在Linux下每隔1分鐘檢查一下tomcat進(jìn)程是不是在運(yùn)行,如果tomcat進(jìn)程退出了,立即啟動tomcat進(jìn)程
搜索目錄/home/tools/下所有已test開頭,py結(jié)尾的文件(包括子目錄的), 把文件全路徑輸出到一個列表里面打印出來
import os
files_list = []
def find_files(src):
if not os.path.exists(src) and not os.path.isdir(src):
print("源路徑不存在 或 源路徑不是目錄")
return
for f in os.listdir(src):
if os.path.isfile(f) and f.startswith('test') and f.endswith('.py'):
full_path = os.path.join(src, f)
files_list.append(full_path)
elif os.path.isdir(f):
son_src = os.path.join(src, f)
find_files(son_src)
find_files("/home/tools/")
print(files_list)
快速添加數(shù)據(jù)的小技巧:
ls = [1,2,3,4]
list1=[i for i in ls if i>2]
tuple1=(2,4,6)
dict1= {x: x**2 for x in tuple1}
dict2= {x: 'item'+str(x**2) for x in tuple1}
set1 = {x for x in 'hello world' if x not in 'low level'}
實(shí)戰(zhàn)分析:
寫一個函數(shù),接受一個參數(shù),如果是文件,就執(zhí)行這個文件,如果是文件夾,就執(zhí)行這個文件夾下所有的py文件
def func(path):
# 先判斷這個path是文件還是文件夾,isdir isfile
# 如果是文件,.py結(jié)尾的
if os.path.isfile(path) and path.endswith('.py'):
# 執(zhí)行這個文件 :
os.system('python %s'%path) # 模擬了在cmd中執(zhí)行代碼的過程
# 如果是文件夾
elif os.path.isdir(path):
# 查看這個文件夾下的所有內(nèi)容 listdir
for name in os.listdir(path):
abs_path = os.path.join(path,name)
# 如果是文件 .py結(jié)尾的
if abs_path.endswith('.py'):
# 執(zhí)行這個文件 : os.system('python %s'%abs_path)
os.system('python %s' % abs_path)
總結(jié)
以上是生活随笔為你收集整理的python大一基础题_python基础练习题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PHP创建圆柱体的类,创建一个类
- 下一篇: 实战!阿里神器 Seata 实现 TCC