python中的实用案例


一、字符串

手机号只显示后4位

phone_number = '1386-666-0006'
hiding_number = phone_number.replace(phone_number[:9],'*' * 9)
print(hiding_number)

关于format()的应用

print('{} a word she can get what she {} for.'.format('With','came'))
print('{preposition} a word she can get what she {verb} for'.format(preposition = 'With',verb = 'came'))
print('{0} a word she can get what she {1} for.'.format('With','came'))

关于格式化字符串的应用【%s、%d、%f】

举例

二、应用案例

设计一个重量转换器

设计一个重量转换器,输入以“g”为单位的数字后返回换算成“kg”的结果


#方法一
def weight_converter(g):
    weight = g /1000
    weight = str(weight) + 'kg'
    return weight

kg = weight_converter(1500)
print(kg)

#方法二
def weight_converter(g):
    weight = int(g[:-1] )/1000
    weight = str(weight) + 'kg'
    return weight
    

kg = weight_converter('2500g')    
print(kg)


设计一个求直角三角形斜边长的函数

(两条直角边为参数,求最长边)



敏感词过滤器

def text_create(name, msg):
    text_path = 'E:/tests/2022-01/'
    full_path = text_path + name + '.txt'
    file = open(full_path,'w')
    file.write(msg)
    file.close()
    print('Done')

def text_filter(word,censored_word = 'lame',changed_word = 'Awesome'):
    return word.replace(censored_word, changed_word)

def censored_text_create(name, msg):
    clean_msg = text_filter(msg)
    text_create(name,clean_msg)

censored_text_create('Try','lame!lame!lame!') 

其中:text_create()为创建一个函数,用于新建或打卡txt文件
    text_filter()为需要过滤的字段参数
   执行顺序(先过滤文本,再将过滤后的文本写入打开的txt文件中)

登录密码判断

  • 输入登录密码
def account_login():
    password = input('Password:')
    if password == '12345':
        print('Login success!')
    else:
        print('Wrong password or invalid input!')
        account_login()
    
account_login()
  • 重置密码
#创建一个列表,用于储存用户的密码、初始密码和其他数据
password_list = ['*#*#','12345'] 
def account_login():
    password = input('Password:') #使用input获得用户输入的字符串并储存在变量password 中
    password_correct = password == password_list[-1] 
    password_reset = password == password_list[0] 
    if password_correct: #当用户输入的密码等于密码列表中最后一个元素的时候(即用户最新设定的密码),登录成功
        print('Login success!')
    elif password_reset: #当用户输入的密码等于密码列表中第一个元素的时候((即重置密码的“口令”)触发密码变更,并将变更后的密码储存至列表的最后一个,成为最新的用户密码;
        new_password = input('Enter a new password:')
        password_list.append(new_password)
        print('Your password has changed successfully!')
        account_login()
    else: #一切不等于预设密码的输入结果,全部会执行打印错误提示,并且再次调用函数,让用户再次输入密码
        print('Wrong password or invalid input!') 
        account_login() 

account_login() 
  • 密码三次错误被锁
password_list = ['*#*#','12345'] 
def account_login():
    tries = 3
    while tries > 0:#密码试错三次则不再执行
         password = input('Password:')
         password_correct = password == password_list[-1] 
         password_reset = password == password_list[0] 
   
        if password_correct: 
            print('Login success!')
        elif password_reset:
            new_password = input('Enter a new password:')
            password_list.append(new_password)
            print('Your password has changed successfully!')
            account_login()
        else:
            print('Wrong password or invalid input!') 
            tries = tries - 1
            account_login() 
    else:
        print('Your account has been suspended')

account_login()

九九乘法表

#方法一
for i in range(1,10):
    for j in range(1,i+1):
        print('{} X {} = {}'.format(i,j,i*j),end = "\t")
    print("")
 
#方法二
row = 1 # 定义起始行
# 最大打印 9 行
while row <= 9:
   col = 1  # 定义起始列
   # 最大打印 row 列
   while col <= row:
       # end = "",表示输出结束后,不换行
       # "\t" 可以在控制台输出一个制表符,协助在输出文本时对齐
       print("%d * %d = %d" % (col, row, row * col), end="\t")
       # 列数 + 1
       col += 1
   # 一行打印完成的换行
   print("")
   # 行数 + 1
   row += 1
     

利用break跳出while循环

#count作为计数工具,可以记录循环执行了几次
count = 0
while True:
    print('Repeat this line !',count)
    count = count + 1
    if count == 5:
        break

设计一个摇色子猜大小游戏


import random

#摇色子
def roll_dice(numbers=3, points=None):
    print('<<<<< ROLL THE DICE! >>>>>')
    if points is None:
        points = []
    while numbers > 0:
        point = random.randrange(1,7)
        points.append(point)
        numbers = numbers - 1
    return points

#色子的大小点数
def roll_result(total):
    isBig = (11 <= total <=18) #括号内为布尔型,返回值为true、false
    isSmall = (3 <= total <=10)
    if isBig:
        return 'Big'
    elif isSmall:
        return 'Small' 

#猜大小
def start_game():
    print('<<<<< GAME 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、false
        if youWin:
            print('The points are',points,'You win !')
        else:
            print('The points are',points,'You lose !')
    else:
        print('Invalid Words')
        start_game()

start_game()

词频统计

  • 方法一

path = 'E:/tests/2022-01/Walden.txt'
with open(path,'r',encoding = 'utf-8') as text:
    words = text.read().split() #分词
    print(words)
    for word in words:
        print('{}-{} times'.format(word,words.count(word)))       
'''
可能出现的问题
1.有一些带标点符号的单词被单独统计了次数;
2.有些单词不止一次地展示了出现的次数;
3.由升Python对大小写敏感,开头大写的单词被单独统计了。
'''

#为解决以上问题的干扰,对单词进行预处理
import string
path = 'E:/tests/2022-01/Walden.txt'
with open(path,'r',encoding = 'utf-8') as text:
    words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()]
    words_index = set(words) #将分词过滤后的单词保存在集合中(去重)
    counts_dict = {index:words.count(index) for index in words_index} #创建一个以单词为键,出现频率为值的字典
    for word in sorted(counts_dict,key=lambda x: counts_dict[x],reverse=True):
        print('{} -- {} times'.format(word,counts_dict[word]))
        

注:
words.count(word) 统计words中word的数量
words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()]对分词后的单词进行过滤(去掉标点符号)
string.punctuation表示标点符合,如!"#$%&'()*+,一./:;<=>?@[]^_`{\}~
key=lambda x: counts_dict[x]为lambda表达式,以字典中的值为排序的参数

  • 方法二

'''
建立一个以单词为键、单词出现次数为值得字典
每次查到一个单词,如果字典中存在这个词,就在该词的计数上增加 1,如果字典中没有这个词,就把这个词增加到这个字典中
'''

word_counts = {}
for word in document:
    if word in word_counts:
        word_counts[word] += 1
    else:
        word_counts[word] = 1

'''
当查找缺失值碰到异常报出时,处理异常
'''
word_counts = {}
for word in document:
    try:
        word_counts[word] += 1
    except KeyError:
        word_counts[word] = 1

'''
使用get函数
'''
word_counts = {}
for word in document:
    previous_count = word_counts.get(word, 0)
    word_counts[word] = previous_count + 1

判断一个输入的数是否为素数

判断13是不是素数,如果是,则输出yes,如果不是,则输出no;结果保留到q1中

q1 = []
start = int(input("输入要判断的数"))
if start <= 2:
    if start <2:
        result = "no"
    else:
        result = "yes"
else:
    for i in range(2,start):
        if start%i == 0:
            result = "no"
            break
    else:
        result = "yes"
q1.append(result)
q1


提示:本文是《编程小白的第一本python入门书》读后总结

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值