PYTHON学习总结

PYTHON基础总结

学习python已经有一段时间了,由于一些知识点容易忘或者其他的只是容易想不起来,这边整理一下自己的代码记录一下学习内容。

PYTHON基础语法部分

  1. pycharm常用快捷键
# Ctrl + / 注释
# Ctrl + Alt + L 格式化
# Ctrl + D 复制一行
# Ctrl + Y 删除一行
# Alt + Shift 批量操作多行
# Ctrl + Shift + Z 前进
# Ctr + Shift +Up/Down 移动代码
# Shift + Enter 自动换行
  1. python值得注意的简单事项
#格式化输出中固定int长度输出方式
num = 12
print('学号为%06d' % num)

#去除print()默认的换行
print(num , end='')

#input()接受的信息为字符串,年龄等变量需要强制转化
>>> num = input()
23
>>> type(num)
<class 'str'>

# 在程序的逻辑判断中,通常0:False,非0:True
>>> a = 0
>>> print(not a)
True

# 简单的登录验证,主要注意点为While True: 死循环的应用,和循环中有关else的作用。
real_pass_word = 'afyz'
account = 'admin'
password = 'admin'
pass_word = input("请输入验证码:")
if pass_word == real_pass_word:
    while True:
        account_name = input("用户名:")
        user_password = input("密码:")
        if account_name == account and user_password == password:
            print("登陆成功!")
            break
        else:
            print("用户名或密码错误!请重新输入:")
else:
    print("验证码错误!")

# 随机数的引用与使用
from random import randint

randint(0,2)  随机返回0 or 1 or 2

# 经典九九乘法表
i = 1
while i <= 9:
    j = 1
    while j <= i:
        print(f"{j}*{i}={i * j}", end='\t')
        j += 1
    print()
    i += 1

# 经典逢7过游戏
num = int(input("请输入数字"))
sum = 0
sum1 = 0
for i in range(1, num + 1):
    # if i % 7 == 0 or i % 10 == 7 or i // 10 == 7:
    #     i += 1
    #     sum1 += 1
    #     continue
    # else:
    #     sum += 1
    if i % 7 != 0 and i % 10 != 7 and i // 10 != 7:
        i += 1
        sum1 += 1
        continue
    else:
        sum += 1
    i += 1
else:
    print(f"共{sum}个学生不报数,{sum1}个同学报数")
 
# python中对个位、十位、百位上数字获取的方法
# 个位
num % 10
# 十位
num // 10
# 百位
num // 100 % 10

# pyhotn中可以利用''或者""或者""""""标注字符串内容,标注内有相同标识符可通过\转义
str1 = '鲁迅说:\'我没有说过这句话\'')

# 字符串下标查找可以用index()或者find(),区别在于# index()没有返回值会报错,find()返回-1

# 字符串为不可变类型容器,其方法产生的结果赋值于新的字符串,不对原字符串产生改变。
# replace替换
str2 = str1.replace('and', 'he', 1)
print(f'str1是{str1},str2是{str2}')
# split切片
str3 = str1.split('and', 1)
print(str3)
# jion拼接字符串
str4 = ['i', 'am', 'man']
str5 = ''.join(str4)
print(str5)
# str.startwith('str1',fristnum,endnum)
str1 = 'i am ll'
print(str1.startswith('i'))

# str.endswith('str1',fristnum,endnum)
print(str1.endswith('p'))

# str.isalpha()是否都是字母
print(str1.isalpha())
# str.isdigit()是否都是数字
print(str1.isdigit())
# str.isalnum()是否都是数字字母组合
print(str1.isalnum())
# str.isspace()是否都是空格
print(str1.isspace())
#str1 = "    i am Liang Suo    "
print(str1.capitalize())  # 首字母转换大写
print(str1.title())  # 全部首字母转换成大写
print(str1.upper())  # 全部转换成大写
print(str1.lower())  # 全部转换成小写
print(str1.lstrip())  # 删除左侧空白
print(str1.rstrip())  # 删除右侧空白
print(str1.strip())  # 删除两侧空白
# 左对齐。右对齐。居中
str2 = 'liangsuo'
print(str2.ljust(15))  # 左对齐
print(str2.rjust(15))  # 右对齐
print(str2.center(15))  # 居中对齐

# 给定一个列表,首先删除以s开头的元素,删除后,修改第一个元素为"joke",并且把最后一个元素复制一份,放在joke的后边
my_list = ["spring", "look", "strange", "curious", "black", "hope"]
for str1 in my_list:
    if str1.startswith('s'):
        my_list.remove(str1)
else:
    my_list[0] = "joke"
    new_str1 = my_list[-1]
    my_list.insert(1, new_str1)
    print(my_list)

# 列表,字典为可变类型容器,其方法作用于原列表。
增:list.append()  list.extend()  dict["new_key"]= "new_value" dict.get("new_key")="new_value":list.pop()  list.remove()  dict.pop()
改:直接赋值
查:list.index()  dict.items()
# 排序,默认升序(reverse=False)
list1.sort(reverse=False)
list1.sort(reverse=True)
# 冒泡排序和拆包
# temp = 0
for j in range(len(list1)):
    i = j
    while i < len(list1):
        if list1[i] <= list1[j]:
            # temp = list1[j]
            # list1[j] = list1[i]
            # list1[i] = temp
            list1[j], list1[i] = list1[i], list1[j]
        i += 1
print(list1)

  1. 基础知识总结,内存版学生管理系统
# * 使用函数, 完成学生名片管理系统案例:增、删、改、查
"""
1、学生名片包含姓名、年龄,可通过dict储存
2、学生选择对应的数字,执行相应的功能,利用if判断
3、功能用函数封装
4、学生总名片用元组储存 (问题:元组不可更改,想要删除学生信息只能赋值为None,如果不对其处理会使None变多)
5、解决方法:可以利用列表进行改进
"""
import sys


def select_students(student_card):
    for i in student_card:
        print(i)
    return student_card

def add_student(name, age, student_card):
    for i in student_card:
        if i.get("name") == name and int(i.get("age")) == age:
            print("此同学已存在!")
            break
    else:
        # for j in student_card:
        #     if i.get("name") == 'None' and i.get("age") == 'None':
        #         i["name"] = name
        #         i["age"] = str(age)
        #         break
        # else:
        list_user = {"name": name, "age": str(age)}
        student_card.append(list_user)
    return student_card


def remove_student(name, age, student_card):
    for i in student_card:
        if i.get("name") == name and int(i.get("age")) == age:
            student_card.remove(i)
            # for j in i:
            #     i[j] = 'None'
            # break
    else:
        print("查无此人!")
    return student_card


def change_student(name, age, student_card):
    for i in student_card:
        if i.get("name") == name and int(i.get("age")) == age:
            print("请输入要修改的信息:")
            name, age = input_student()
            i["name"] = name
            i["age"] = str(age)
            break
    else:
        print("查无此人!")
    return student_card


def check_student(name, age, student_card):
    for i in student_card:
        if i.get("name") == name and int(i.get("age")) == age:
            print(i)
            break
    else:
        print("查无此人!")
    return student_card


def students(student_card):
    for i in student_card:
        print(i)


def input_student():
    name = input("请输入姓名:")
    age = int(input("请输入年龄:"))
    return name, age


def show_menu():
    print('=' * 20)
    print("=1、查询所有用户信息!")
    print("=2、查询指定用户信息!")
    print("=3、添加用户信息!")
    print("=4、删除用户信息!")
    print("=5、修改用户信息!")
    print("=6、退出系统!")
    print('=' * 20)


def choose_function(student_card):
    show_menu()
    command = int(input("请选择相应的功能:"))
    function(command, student_card)


def function(command, student_card):
    if command == 1:
        student_card = select_students(student_card)
        choose_function(student_card)
    if command == 2:
        name, age = input_student()
        student_card = check_student(name, age, student_card)
        choose_function(student_card)
    elif command == 3:
        name, age = input_student()
        student_card = add_student(name, age, student_card)
        students(student_card)
        choose_function(student_card)
    elif command == 4:
        name, age = input_student()
        student_card = remove_student(name, age, student_card)
        students(student_card)
        choose_function(student_card)
    elif command == 5:
        name, age = input_student()
        student_card = change_student(name, age, student_card)
        students(student_card)
        choose_function(student_card)
    elif command == 6:
        sys.exit()
    else:
        input("请按任意键退出!")


if __name__ == '__main__':
    student_card = [{"name": "张三", "age": "17"}, {"name": "李四", "age": "18"}, {"name": "丽丽", "age": "18"}]
    choose_function(student_card)

完缮版:

# include utf-8
# 判断int()强制转化异常方法
def int_age_error():
    # 循环失败的输入
    while True:
        try:
            age = int(input("请输入年龄:"))
        except ValueError:
            print("请输入数字!")
        else:
            break
    return age


# 查询所有学生信息
def check_user():
    # 判断当前系统是否存在信息
    if user_list:
        # 遍历,格式化打印学生信息
        print("序号\t\t姓名\t\t年龄\t\t电话")
        for i, user_dict in enumerate(user_list):
            print(f'{i + 1}\t\t{user_dict["name"]}\t\t{user_dict["age"]}\t\t{user_dict["tel"]}')
    else:
        print("暂无信息!")


# 查询指定学生信息
def find_user():
    # 判断当前系统是否存在信息
    if user_list:
        tel = input("请输入电话:")
        # 判断是否存在此学生
        for i, user_dict in enumerate(user_list):
            if user_dict["tel"] == tel:
                # 格式化打印学生信息
                print("序号\t\t姓名\t\t年龄\t\t电话")
                print(f'{i + 1}\t\t{user_dict["name"]}\t\t{user_dict["age"]}\t\t{user_dict["tel"]}')
                break
        else:
            print("查无此人!")
    else:
        print("暂无信息!")


# 添加学生信息
def add_user():
    # 死循环判断学生信息是否存在,存在重新输入
    while True:
        name = input("请输入姓名:")
        age = int_age_error()
        tel = input("请输入电话:")
        # 遍历学生信息,判断是否存在学生信息
        for i, user_dict in enumerate(user_list):
            if user_dict["tel"] == tel:
                print("此人已存在")
                break
        else:
            # 添加学生信息
            new_dict = {"name": name, "age": age, "tel": tel}
            user_list.append(new_dict)
            print("添加成功!")
            break


# 删除学生信息
def remove_user():
    # 判断当前系统是否存在信息
    if user_list:
        tel = input("请输入电话:")
        # 遍历系统,判断学生是否存在
        for i, user_dict in enumerate(user_list):
            if user_dict["tel"] == tel:
                # 删除学生信息
                del user_list[i]
                print("删除成功")
                break
        else:
            print("查无此人!")
    else:
        print("暂无信息!")


# 修改学生信息
def change_user():
    # 判断当前系统是否存在信息
    if user_list:
        tel = input("请输入电话:")
        # 遍历系统,判断学生是否存在
        for i, user_dict in enumerate(user_list):
            if user_dict["tel"] == tel:
                print("请输入需要修改的信息:")
                name = input("请输入姓名:")
                age = int_age_error()
                tel = input("请输入电话:")
                # 修改学生信息
                user_dict["name"], user_dict["age"], user_dict["tel"] = name, age, tel
                print("修改成功")
                break
        else:
            print("查无此人!")
    else:
        print("暂无信息!")


# 菜单函数
def show_menu():
    print('=' * 20)
    print("=1、查询所有用户信息!")
    print("=2、查询指定用户信息!")
    print("=3、添加用户信息!")
    print("=4、删除用户信息!")
    print("=5、修改用户信息!")
    print("=6、退出系统!")
    print('=' * 20)


# 开始函数
def start():
    # 死循环返回菜单
    while True:
        show_menu()
        # 抛出int()强制转化不合法异常
        try:
            command = int(input("请选择相应的功能:"))
        except ValueError:
            print("请输入数字!")
        else:
            if command == 1:
                check_user()
            elif command == 2:
                find_user()
            elif command == 3:
                add_user()
            elif command == 4:
                remove_user()
            elif command == 5:
                change_user()
            elif command == 6:
                print("欢迎下次使用!")
                break
            else:
                print("请重新输入1-6:")


# 程序入口
if __name__ == '__main__':
    user_list = []
    start()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值