09_Python语法示例(数据类型)

1.买苹果,计算金额并保留两位小数

price = int(input("苹果的单价: "))
weight = float(input("苹果的重量: "))
money = price * weight
print("买了%d斤苹果, 每斤%.2f元, 需要付%.2f元" % (weight, price, money))

2.人机猜拳小游戏设计

import random

def finger_guessing():
    while True:
        player = input("请输入您要出的拳 石头(1) 剪刀(2) 布(3):")
        computer = random.choice("123")
        print("玩家出拳是: %s VS 电脑出的拳是: %s" % (player, computer))
        # 比较胜负(玩家 VS 电脑) 1 石头胜剪刀 2 剪刀胜布 3 布胜剪刀
        # 满足其中一项胜利规则,玩家胜利
        if ((player == '1' and computer == '2')
                or (player == '2' and computer == '3')
                or (player == '3' and computer == '1')):
            print("玩家player胜利")
        else:
            if player == computer:
                print("双方平局!")
            # 玩家出拳和电脑不一样,电脑胜利
            else:
                print("电脑computer胜利")


finger_guessing()

3.一行代码实现一个简易人工智能对话问答

while True: print(input("问:").strip("吗??") + "!")

4.写一个程序,对输入的内容做加法识别并计算

content = input("请输入加法运算式: ")
a_list = content.partition("+")
a_int = int(a_list[0]) + int(a_list[2])
print("%s + %s = %s" % (a_list[0], a_list[2], a_int))

5.写一个程序,对输入的字符串统计字母和数字出现的次数

xs_int = 0
zm_int = 0
zf_str = input(">>>")
for i_int in zf_str:
    if i_int.isalpha()==True:
        zm_int += 1
    elif i_int.isdecimal()==True:
        xs_int += 1
print(zm_int, xs_int)

6.随机生成验证码

def check_code(num=4):
    """随机生成验证码"""
    import random
    checkcode = ""
    for i in range(num):
        current = random.randrange(0, num)
        if current != i:
            temp = chr(random.randint(65, 90))
        else:
            temp = random.randint(0, 9)
        checkcode += str(temp)
    return checkcode


cdoe = check_code(6)
print(cdoe)

7.循环输入字符串,q退出输入,格式化表格形式输出添加的元素

    '''
        fgadfgdas           dsfcvar             dasfsa
        dasfdsaew           dfsd                hggfhty
        fgd                 gfdgvb              hhbdfsfafadfafd
        dfd                 cdsafewaf           da
        dafw                dsfaf               dadfq
    '''
    s1 = ""
    while True:
        v1 = input("v1>>>")
        v2 = input("v2>>>")
        v3 = input("v3>>>")
        if v1=="q" or v2=="q" or v3=="q":
            break
        v4 = "{0}	{1}	{2}
".format(v1, v2, v3)
        s1 = s1 + v4
    print(s1.expandtabs(20))  # 指定以几个字符以断句,遇到制表符用空格补全几个字符

8.输入一个字符串,判断输入的字符串是否是整数或小数

s = input(">>>")
s1 = s.replace("-", "")  # 替换掉负号
if s1.isdigit():
    print("字符串%s是整数" % s)
else:
    if s1.count(".")==1 and not s1.startswith(".") and not s1.endswith("."):
        print("字符串%s是小数" % s)
    else:
        print("字符串%s是不是小数" % s)

9.校验⽤用户输⼊入的验证码是否合法,并忽略首尾空格

verify_code = "Coco"
user_verify_code = input("请输入验证码: ")
if verify_code.upper() == user_verify_code.upper().strip():
    print("验证成功")
else:
    print("验证失败")

10.公鸡5文钱一只,母鸡3文钱一只,小鸡3只1文钱,用100文钱买100只鸡,必须要有公鸡母鸡小鸡,公鸡母鸡小鸡各多少只

s1_int = range(1, 21)  # 100文钱可以买20只公鸡
s2_int = range(1, 34)  # 100文钱可以买33只母鸡
s3_int = range(1, 301)  # 100文钱可以买300只小鸡
for i in s1_int:
    for j in s2_int:
        for v in s3_int:
            if i + j + v == 100 and 5 * i + 3 * j + v / 3 == 100:
                print("公鸡%s只,母鸡%s只,小鸡%s只" % (i, j, v))

11.从列表中找到人名coco

li = ["Tom ", "ale  xC", "AbC   ", "
Coco
", " ri  TiAn", "Coc", "  aqc", "coco	"]
lst = []
for el in li:
    el = el.replace(" ", "").strip()
    if (el.startswith("C") or el.startswith("c")) and el.endswith("o"):
        lst.append(el)
print(lst)

12.打码评论中的敏感词汇

lst = []
li = ["苍老师", "东京热", "武藤兰", "波多野结衣"]
content = input("请输入你的评论: ")
for el in li:
    if el in content:
        content = content.replace(el, "*" * len(el))
lst.append(content)
print(lst)

13.遍历嵌套列表

li = [1, 3, 4, "coco", [3, 7, 8, "Angles"], 5, "Cat"]
for e in li:
    if type(e) == list:  # 判断e的数据类型
        for ee in e:
            if type(ee) == str:
                print(ee.lower())
            else:
                print(ee)
    else:
        if type(e) == str:
            print(e.lower())
        else:
            print(e)

14.把学生成绩录入到一个列表中,并求平均值,示例: 张三_44

lst = []
while 1:
    stu = input("请输入学生的姓名和成绩(姓名_成绩), 输入Q退出录入: ")
    if stu.upper() == "Q":
        break
    lst.append(stu)
sum = 0
for el in lst:
    li = el.split("_")
    sum += int(li[1])
print(sum / len(lst))

15.有如下值li= [11,22,33,44,55,66,77,88,99,90],完善字典{'k1': 大于66的所有值列表, 'k2': 小于66的所有值列表}

li= [11,22,33,44,55,66,77,88,99,90]
# 方法一
dic = {}
for el in li:
    if el > 66:
        dic.setdefault("k1", []).append(el)  # 1.新增, 2.查询
    else:
        dic.setdefault("k2", []).append(el)  # 1.新增, 2.查询
print(dic)
# 方法二
result = {}
for row in li:
    if row < 66:
        l = result.get("k1")    # 上来就拿k1
        if l == None:   # k1不存在. 没有这个列表
            result["k1"] = [row]    # 创建一个列表扔进去
        else:   # k1如果存在
            result['k1'].append(row)    # 追加内容
    else:
        l = result.get("k2")  # 上来就拿k2
        if l == None:  # k1不存在. 没有这个列表
            result["k2"] = [row]  # 创建一个列表扔进去
        else:  # k1如果存在
            result['k2'].append(row)  # 追加内容
print(result)  # {'k1': [11, 22, 33, 44, 55], 'k2': [77, 88, 99, 90]}

16.购物,列表套字典实现

goods = [
        {"name": "电脑", "price": 1999},
        {"name": "鼠标", "price": 10},
        {"name": "游艇", "price": 20},
        {"name": "手机", "price": 998}
    ]
for i in range(len(goods)):
    good = goods[i]
    print(i+1, good['name'], good['price'])
while 1:
    content = input("请输入你要买的商品: ")
    if content.upper() == "Q":
        break
    index = int(content) - 1  # 索引
    if index > len(goods) - 1 or index < 0:  # 调试
        print("输入有误. 请重新输入: ")
        continue
    print(goods[index]['name'], goods[index]['price'])

17.用户输入页码翻页输出列表

li_list = []
for i in range(1, 301):
    item = {"k" + str(i):"value" + str(i)}
    li_list.append(item)
# print(li_list)
while True:
    s1 = input("请输入页码1-30: ")
    if s1.isdigit():
        s1 = int(s1)
        for i in li_list[(s1 - 1) * 10:s1 * 10]:  # 切片遍历
            print(i)
    else:
        print("不能输入1-30的其他内容")

18.实现一个整数加法计算器,如用户输入: 5+8+7最少输入两个数相加,将最后的计算结果添加到此字典中替换None

dic={'最终计算结果': None}
content = input('请输入内容: ').strip()   # 5+8+7
lst = content.split("+")
sum = 0
for el in lst:
    sum = sum + int(el.strip())
dic['最终计算结果'] = sum
print(dic)

19.字典的嵌套运用

'''数据结构示意
    db_dict = {'广东省': {'广州市': {'天河区': {}}, '佛山市': {}}, '四川省': {}}
    db_dict = {
        '广东省': {
            '广州市': {'天河区': {}}, 
            '佛山市': {}
            }, 
        '四川省': {}
    }
'''
db_dict = {}
path_list = []
while True:
    temp_dict = db_dict
    for item in path_list:
        temp_dict = temp_dict[item]
    print("当节点的所有子节点: ", list(temp_dict.keys()))

    choice = input("1:添加节点;2:查看节点(q退出/b返回上一级)
>>>")
    if choice == "1":
        name = input("请输入要添加节点名称: ")
        if name in temp_dict:
            print("节点已存在")
        else:
            temp_dict[name] = {}
    elif choice == "2":
        name = input("请输入要查看节点名称: ")
        if name in temp_dict:
            path_list.append(name)
        else:
            print("你输入的节点名称不正确")
    elif choice.lower() == "b":
        if path_list:
            print(path_list)
            path_list.pop()
    elif choice.lower() == "q":
        break
    else:
        print("你输入的不正确")

20.数据处理列表字典集合运用

    user_list=[
        {"name": "coco", "hobby": "动漫"},
        {"name": "coco", "hobby": "音乐"},
        {"name": "coco", "hobby": "学习"},
        {"name": "angels", "hobby": "看书"},
        {"name": "angels", "hobby": "游戏"},
    ]


    def hobby(name):
        hobby_set = set()
        for i_dic in user_list:
            if i_dic["name"] == name:
                hobby_set.add(i_dic["hobby"])
        return hobby_set


    def main(user_list):
        name_set = set()
        user_dic = dict()
        for i in user_list:
            name_set.add(i["name"])
        print(name_set)  # {'coco', 'angels'}
        for name in name_set:
            user_dic[name] = hobby(name)
        print(user_dic)  # {'coco': {'音乐', '学习', '动漫'}, 'angels': {'游戏', '看书'}}


    main(user_list)
原文地址:https://www.cnblogs.com/tangxuecheng/p/11216317.html