随笔 - 3  文章 - 0  评论 - 0  阅读 - 40 

task1.py

复制代码
#  字符串的基础操作
#  课堂上没有演示的一些方法

x = 'nba FIFA'
print(x.upper())        # 字符串转大写
print(x.lower())        # 字符串转小写
print(x.swapcase())     # 字符串大小写翻转
print()

x = 'abc'
print(x.center(10, '*'))    # 字符串居中,宽度10列,不足左右补*号
print(x.ljust(10, '*'))     # 字符串居左,宽度10列,不足左右补*号
print(x.rjust(10, '*'))     # 字符串居右,宽度10列,不足左右补*号
print()

x = '123'
print(x.zfill(10))      # 字符串宽度10列,不足左边用0填充
x = 123
print(str(x).zfill(10))  # 把int类型转换成字符串类型后,对字符串对象使用str.zfill()方法
print()

x = 'phone_number'
print(x.isidentifier())   # 判断字符串是否是python合法标识符
x = '222test'
print(x.isidentifier())
print()

x = '  '
print(x.isspace())     # 判断字符串是否是空白符(包括空格、回车、Tab键)
x = '\n'
print(x.isspace())
print()

x = 'python is fun'
table = x.maketrans('thon', '1234')    # 为字符串对象x创建一个字符映射表,字符thon分别映射到字符1234
print(x.translate(table))               # 根据字符映射表table对字符串对象x中的字符进行转换
复制代码

 

task2.py

复制代码
# 基础练习:列表、格式化、类型转换

x = [5, 11, 9, 7, 42]

print('整数输出1:', end = '')
i = 0
while i < len(x):
    print(x[i], end = ' ')
    i += 1


print('\n整数输出2:', end = '')
i = 0
while i < len(x):
    print(f'{x[i]:02d}', end = '-')    # 指定每个整数宽度占2列;不足2列,左边补0
    i += 1


print('\n整数输出3:', end = '')
i = 0
while i < len(x) - 1:
    print(f'{x[i]:02d}', end = '-')
    i += 1
print(f'{x[-1]:02d}')


print('\n字符输出1:', end = '')
y1 = []
i = 0
while i < len(x):
    y1.append(str(x[i]))    # 函数str()用于把其他类型对象转换成字符串对象
    i += 1
print('-'.join(y1))


print('字符输出2:', end = '')
y2 = []
i = 0
while i < len(x):
    y2.append(str(x[i]).zfill(2))    # x[i]是int类型对象,使用str()转换成字符串对象后,处理,然后加入到列表y中
    i += 1
print('-'.join(y2))
复制代码

 

 

对line3换一组测试数据后:

复制代码
# 基础练习:列表、格式化、类型转换

x = [1, 9, 8, 4, 2, 0, 49]

print('整数输出1:', end = '')
i = 0
while i < len(x):
    print(x[i], end = ' ')
    i += 1


print('\n整数输出2:', end = '')
i = 0
while i < len(x):
    print(f'{x[i]:02d}', end = '-')    # 指定每个整数宽度占2列;不足2列,左边补0
    i += 1


print('\n整数输出3:', end = '')
i = 0
while i < len(x) - 1:
    print(f'{x[i]:02d}', end = '-')
    i += 1
print(f'{x[-1]:02d}')


print('\n字符输出1:', end = '')
y1 = []
i = 0
while i < len(x):
    y1.append(str(x[i]))    # 函数str()用于把其他类型对象转换成字符串对象
    i += 1
print('-'.join(y1))


print('字符输出2:', end = '')
y2 = []
i = 0
while i < len(x):
    y2.append(str(x[i]).zfill(2))    # x[i]是int类型对象,使用str()转换成字符串对象后,处理,然后加入到列表y中
    i += 1
print('-'.join(y2))
复制代码

 

 

task3.py

复制代码
# 把姓名转换成大写,遍历分行输出

name_list = ['david bowie', 'louis armstrong', 'leonard cohen', 'bob dylan', 'cocteau twins']

# 方法1
i = 0
while i < len(name_list):
    print(name_list[i].title())
    i += 1

print()

# 方法2
t = []
i = 0
while i < len(name_list):
    t.append(name_list[i].title())
    i += 1

print('\n'.join(t))
复制代码

 

task4.py

复制代码
name_list = ['david bowie', 'louis armstrong', 'leonard cohen', 'bob dylan', 'cocteau twins']

# 将姓名中的姓和名首字母转换成大写
name_list = [name.title() for name in name_list]

# 将姓名列表按字典序排序
name_list.sort()

# 打印排序后的姓名列表及其对应的字典序编号
for i, name in enumerate(name_list, 1):
    print(f"{i}. {name}")
复制代码

task5.py

复制代码
text = '''The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!'''

# 统计行数
line_count = len(text.splitlines())

# 统计单词数
word_count = len(text.split())

# 统计字符数
char_count = len(text)

# 统计空格数
space_count = text.count(' ')

# 输出结果
print(f"行数: {line_count}")
print(f"单词数: {word_count}")
print(f"字符数: {char_count}")
print(f"空格数: {space_count}")
复制代码

task6.py

复制代码
# 图书列表中每行信息: 书名、作者、译者、出版社 
# 如果是国内作者,则译者字段为空串
book_list = [['静静的顿河','肖洛霍夫','金人', '人民文学出版社'],
             ['大地之上','罗欣顿.米斯特里','张亦琦', '天地出版社'],
             ['夜航西飞', '柏瑞尔.马卡姆', '陶立夏', '人民文学出版社'],
             ['来自民间的叛逆', '袁越', '','新星出版社'],
             ['科技与恶的距离', '珍妮.克里曼', ' 詹蕎語', '墨刻出版社'],
             ['灯塔','克里斯多夫.夏布特','吕俊君','北京联合出版公司'],
             ['小行星掉在下午','沈大成', '', '广西师范大学出版社']]

# 增加标题行"图书信息",居中显示
title = "图书信息".center(30, "*")
print(title)

# 对图书编号输出,输出信息和形式诸如 编号. 《书名》|作者|出版社 (忽略译者列)
for i, book in enumerate(book_list, start=1):
    book_info = f"{i}. 《{book[0]}》|{book[1]}|{book[3]}"
    print(book_info)
复制代码

task7.py

复制代码
data = ['99 81 75', '30 42 90 87', '69 50 96 77 89 93', '82 99 78 100']

# 将字符串列表转换为浮点数列表
data = [list(map(float, s.split())) for s in data]

# 计算均值
total = 0
count = 0
for lst in data:
    total += sum(lst)
    count += len(lst)
mean = total / count

# 输出结果
title = "*** Remote Interpreter Reinitialized ***"
width = 40
left_width = (width - len(title)) // 2
right_width = width - len(title) - left_width
print(f"{'*' * left_width}{title}{'*' * right_width}")
print(f"{mean:.2f}")
复制代码

task8.py

复制代码
words_sensitive_list = ['张三', 'V字仇杀队', '']
comments_list = ['张三因生命受到威胁正当防卫导致过失杀人,经辩护律师努力,张三不需负刑事责任。',
                 '电影<V字仇杀队>从豆瓣下架了', '娱乐至死']

for comment in comments_list:
    for word in words_sensitive_list:
        if word in comment:
            comment = comment.replace(word, '*' * len(word))
    print(comment)
复制代码

task9_1.py

复制代码
"""
家用电器销售系统
v1.1
"""

#欢迎信息
print('欢迎使用家用电器销售系统!')

#产品信息列表
print('产品和价格信息如下:')
print('*****************************************************')
print('%-10s' %'编号', '%-10s' %'名称', '%-10s' %'品牌', '%-10s' %'价格', '%-10s' %'库存数量')
print('--------------------------------------------------------')
print('%-10s' %'0001', '%-10s' %'电视机', '%-10s' %'海尔', '%10.2f' %5999.00, '%10d' %20)
print('%-10s' %'0002', '%-10s' %'冰箱', '%-10s' %'西门子', '%10.2f' %6998.00, '%10d' %15)
print('%-10s' %'0003', '%-10s' %'洗衣机', '%-10s' %'小天鹅', '%10.2f' %1999.00, '%10d' %10)
print('%-10s' %'0004', '%-10s' %'空调', '%-10s' %'格力', '%10.2f' %3900.00, '%10d' %0)
print('%-10s' %'0005', '%-10s' %'热水器', '%-10s' %'美的', '%10.2f' %688.00, '%10d' %30)
print('%-10s' %'0006', '%-10s' %'笔记本', '%-10s' %'联想', '%10.2f' %5699.00, '%10d' %10)
print('%-10s' %'0007', '%-10s' %'微波炉', '%-10s' %'苏泊尔', '%10.2f' %480.50, '%10d' %33)
print('%-10s' %'0008', '%-10s' %'投影仪', '%-10s' %'松下', '%10.2f' %1250.00, '%10d' %12)
print('%-10s' %'0009', '%-10s' %'吸尘器', '%-10s' %'飞利浦', '%10.2f' %999.00, '%10d' %9)
print('--------------------------------------------------------')

#商品数据
products=[
    ['0001', '电视机', '海尔', 5999.00, 20],
    ['0002', '冰箱', '西门子', 6998.00, 15],
    ['0003', '洗衣机', '小天鹅', 1999.00, 10],
    ['0004', '空调', '格力', 3900.00, 0],
    ['0005', '热水器', '格力', 688.00, 30],
    ['0006', '笔记本', '联想', 5699.00, 10],
    ['0007', '微波炉', '苏泊尔', 480.00, 33],
    ['0008', '投影仪', '松下', 1250.00, 12],
    ['0009', '吸尘器', '飞利浦', 999.00, 9],
]

#用户输入信息
product_id=input('请输入您要购买的产品编号:')
count=int(input('请输入您要购买的产品数量'))

#获取编号对应商品的信息
product_index=len(product_id)-1
product=products[product_index]

#计算金额
print('购买成功,您需要支付', product[3]*count, '')

#退出系统
print('谢谢您的光临,下次再见!')
复制代码

task9_2.py

复制代码
# 家用电器销售系统
# v1.2

# 欢迎信息
print('欢迎使用家用电器销售系统!')

# 产品信息列表
products = [
    {'编号': '0001', '名称': '电视机', '品牌': '海尔', '价格': 5999.00, '库存数量': 20},
    {'编号': '0002', '名称': '冰箱', '品牌': '西门子', '价格': 6998.00, '库存数量': 15},
    {'编号': '0003', '名称': '洗衣机', '品牌': '小天鹅', '价格': 1999.00, '库存数量': 10},
    {'编号': '0004', '名称': '空调', '品牌': '格力', '价格': 3900.00, '库存数量': 0},
    {'编号': '0005', '名称': '热水器', '品牌': '美的', '价格': 688.00, '库存数量': 30},
    {'编号': '0006', '名称': '笔记本', '品牌': '联想', '价格': 5699.00, '库存数量': 10},
    {'编号': '0007', '名称': '微波炉', '品牌': '苏泊尔', '价格': 480.50, '库存数量': 33},
    {'编号': '0008', '名称': '投影仪', '品牌': '松下', '价格': 1250.00, '库存数量': 12},
    {'编号': '0009', '名称': '吸尘器', '品牌': '飞利浦', '价格': 999.00, '库存数量': 9},
]

# 产品信息列表表头
header = '{:<10}{:<10}{:<10}{:<10}{:<10}'.format('编号', '名称', '品牌', '价格', '库存数量')
print('产品和价格信息如下:')
print('*****************************************************')
print(header)
print('--------------------------------------------------------')

# 打印商品信息
for product in products:
    row = '{:<10}{:<10}{:<10}{:<10.2f}{:<10}'.format(
        product['编号'], product['名称'], product['品牌'], product['价格'], product['库存数量'])
    print(row)

# 用户输入信息
product_id = input('请输入您要购买的产品编号:')
count = int(input('请输入您要购买的产品数量:'))

# 获取编号对应商品的信息
product_index = int(product_id) - 1
product = products[product_index]

# 计算金额
total_price = product['价格'] * count
print(f'购买成功,您需要支付{total_price:.2f}元')

# 退出系统
print('谢谢您的光临,下次再见!')
复制代码

 

posted on   张瀚予  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示