python有趣小代码实例

大家好,小编来为大家解答以下问题,python简单有趣的程序源代码 简单有趣的python程序代码,现在让我们一起来看看吧!

前言

大家好,我是栗子同学啦~

所有文章完整的素材+源码都在👇👇

粉丝白嫖源码小狗,请移步至CSDN社区或文末公众hao即可小狗快码论文

Python 凭借语法的易学性,代码的简洁性以及类库的丰富性,赢得了众多开发者的喜爱。

下面我们来看看,简易的代码能实现那些有趣又实用的效果呢?

大家可以直接复制粘贴即可使用,简单实用,方便快捷,而且可以感受一波Python的强大魅

力,你会越来越发现,Python的强大无处不在~

正文

​一、批量抠图

批量获取指定目录下的图片,然后通过 paddlehub 训练好的模型进行批量抠图处理。

1)代码展示
import os
import paddlehub as hub

# 加载模型
humanseg = hub.Module(name='deeplabv3p_xception65_humanseg')  
path = './heben/'    # 文件目录
# 获取文件列表
files = [path + i for i in os.listdir(path)]  
# 抠图
results = humanseg.segmentation(data={'image': files})  
for result in results:
    print(result)
2)效果展示

二、猜单词游戏

1)代码展示
import random


# 存放单词的列表(可以自己填写需要背诵的单词)
words = ["print", "int", "str", "len", "input", "format", "if","for","def"]

#初始化信息↓↓↓↓↓↓↓
def init():
    # 声明三个全局变量
    global word
    global tips
    global ranList

    #随机获取单词列表里的一个单词
    word = list(words[random.randint(0, len(words) - 1)])

    #随机数列表,存放着与单词长度一致的随机数(不重复)
    ranList = random.sample(range(0, len(word)), len(word))

    #存放提示信息
    tips = list()
    #初始化提示信息
    #存放跟单词长度一致的下划线
    for i in range(len(word)):
        tips.append("_")
    #随机提示两个字母
    tips[ranList[0]] = word[ranList[0]]
    tips[ranList[1]] = word[ranList[1]]

#函数部分↓↓↓↓↓

#展示菜单
def showMenu():
    print("需要提示请输入'?'")
    print("结束游戏请输入'quit!'")


#显示提示信息
def showtips():
    for i in tips:
        print(i, end=" ")
    print()


#需要提示
def needTips(tipsSize):
    #至少有两个未知字母
    if tipsSize <= len(word)-3:
        tips[ranList[tipsSize]] = word[ranList[tipsSize]]
        tipsSize += 1
        return tipsSize
    else:
        print("已没有提示!")


#主要运行函数↓↓↓↓↓↓
def run():
    print("------python关键字版本-------")
    init()
    tipsSize = 2
    showMenu()
    
    while True:
        print("提示:",end="")
        showtips()
        guessWord = input("猜一下这个单词:")
        # ''.join(word)>把word列表的内容转换成字符串
        if guessWord == ''.join(word):
            print("恭喜你,猜对了!就是%s!"%(''.join(word)))
            print("再猜一次")
            init()
            
        elif guessWord == '?':
            tipsSize = needTips(tipsSize)
        elif guessWord == 'quit!':
            break
        else:
            print("猜错了!")
            continue
run()
2)效果展示

三、选择车牌号

1)代码展示
import random import string def selectcar_nums():#打印随机车牌号 str = random.choice(string.ascii_uppercase) int = string.digits + string.ascii_uppercase cpint = random.sample(int, 5) cp = '京' + str + "".join(cpint) car_nums.append(cp) print(i + 1, cp) count = 0 while count < 3: car_nums = [] for i in range(20): selectcar_nums() choice = input("请输入您想选择的车牌号:").strip() if choice in car_nums: print("恭喜您选择了车牌:%s"%choice) exit("Good-Bye~") else: print("不合法的选择") count = count
2)效果展示

四、温度转换器

1)代码展示
val = input("请输入带温度表示符号的温度值(例如:37C):")
if val[-1] in ['C', 'c']:
    f = 1.8 * float(val[0:-1]) + 32
    print("转换后的温度为:%.2fF" % f)
elif val[-1] in ['F', 'f']:
    c = (float(val[0:-1]) - 32) / 1.8
    print("转换后的温度为:%.2fC" % c)
else:
    print("输入错误")
2)效果展示

五、汇率转换器

​1)代码展示
# @File      :  汇率实时计算.py

import requests
from lxml import etree

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
}
url = ""


def Get_huilv(url, headers1):
    res = (url=url, headers=headers1, timeout=2)
    # print(res.status_code)#打印状态码
    html = ()
    USD_VS_RMB_0 = html.xpath('//div[@id="main"]/div[1]/div[2]/span[1]/text()')
    for a in USD_VS_RMB_0:
        b = a
    USD_VS_RMB_1 = float(b)
    print("实时汇率为:{}".format(USD_VS_RMB_1))

    currency_str_value = 0
    while currency_str_value != "":
        USD_VS_RMB = float(str(USD_VS_RMB_1))
        # 输入带单位的货币金额
        currency_str_value = input('请输入带单位货币的金额: ')
        # 获取货币单位
        unit = currency_str_value[-3:].upper()  # 第一次判断
        if unit == 'CNY':
            exchange_rate = 1 / USD_VS_RMB
            string = "美元"
        elif unit == 'USD':
            exchange_rate = USD_VS_RMB
            string = "元"
        else:
            exchange_rate = -1
        if exchange_rate != -1:
            in_money = eval(currency_str_value[0:-3])
            # 使用lambda定义函数
            convert_currency2 = lambda x: x * exchange_rate
            # 调用lambda函数
            out_money = convert_currency2(in_money)
            print('转换后的金额是:{} {} '.format(out_money, string))
        else:
            print('无法计算')

Get_huilv(url, headers)

六、飞花令诗词

1)代码展示
import re
import requests

word=input("请输入四字成语:")
style=input("请输入诗的类型(藏头诗或藏字诗):")
base_url = ""
app_id = "5bfd118f1afd942b66b36b30"
input_dic = {"Chinese_word": {"val": word, "type": "str"}, "style": {"val": style, "type": "str"}}
output_dic = {"Poetry": {"type": "str"}}
app_version = "0-0-12"
payload = {"app": {"input": input_dic, "output": output_dic}, "version": app_version}
response = (base_url + app_id, json=payload)
chinese_word=re.split('[,。]',().get('response').get('Poetry'))
print("   诗句")
for i in chinese_word:
    print(i)
2)效果展示

七、人脸关键点检测

1)代码展示
face_landmark = hub.Module(name="face_landmark_localization")

image = ''
result = face_landmark.keypoint_detection(images=[cv2.imread(image)],visualization=True)
print(result)
2)效果展示

八、动图二维码

1)代码展示
from MyQR import myqr
url = ";hid=3&sn=8de42d87b2c51284acd519a1dab21ef2&scene=18#wechat_redirect"
(words=url,version=3,
         picture="4.gif",colorized=True,save_name="",
         save_dir="./")
2)效果展示

​二维码展示不了,so 就不展示啦!

总结

好了,这就是今天分享的内容,感兴趣的小伙伴,可以自己去实践下~

万水千山总是情,点个赞行不行蛮~

✨完整的素材源码等:可以滴滴我吖!或者点击文末hao自取小狗拿的哈~

 🔨推荐往期文章——

项目4.4 【Pygame实战】这两款脑洞大开的文字剧情版游戏,99% 的人打了五星好评-《巨龙之洞》-《太空矿工》

项目4.5  【Pygamre实战】2023人气超高的模拟经营类游戏:“梦想小镇“代码版火爆全场,小狗体验分享下载哦~

项目1.5  Pygame小游戏:植物大战僵尸游戏真的有“毒”?戒不掉啊~

项目1.6 【Pygame小游戏】斗地主我见多了,BUT 这款开源欢乐斗地主,最让人服气~

项目0.5   重温经典:Python版飞机大战源码,装逼神器。玩游戏就玩自己开发的~

项目0.6 【Python实战项目】做一个 刮刮乐 案例,一不小心....着实惊艳到我了。

🎁文章汇总——

Python文章合集 | (入门到实战、游戏、Turtle、案例等)

(文章汇总还有更多你案例等你来学习啦~源码找我即可小狗!)    


原文地址1:https://blog.csdn.net/xy258009/article/details/129087408
参考资料:python中用turtle画一个圆形 https://blog.csdn.net/SXIAOYAN_/article/details/140061099

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值