Basic Python programming code exercises (4)

1. Traverse the list

Enter 3 personal information through input, each person has a name and age, store the information in a dictionary, and store the dictionary in a list.

Traverse the list and print everyone's information in the following format:

  • Zhang San 20
  • Li Si 22
  • Wang Wu 23

1. Enter the information of three people (input input('prompt information') can consider using loop)

2. Everyone has a name and age, (need to use input input, cycle two inputs at a time)

3. Store the name and age information in the dictionary {"name": xxx, "age": xxx}/ {entered name: age}

4. And store the dictionary into a list. list.append(data)

The implementation code is as follows:

name_age_dict = dict()

for idx in range(3):
        name_age = input("请输入[姓名,年龄][{}]:".format(idx+1))
        name = name_age.split(",")[0]
        age = name_age.split(",")[1]
        name_age_dict[name] = age
        i = 1
        for name, age in name_age_dict.items():
           print("{} {} {}".format(i, name, age))
           i += 1
           print("-" * 100)

operation result:

 

2. Judging the ID odd and even numbers in the dictionary

my_list = [{'id': 1,'money': 10}, {'id': 2, 'money': 20}, {'id': 3, 'money': 30}, {'id'
           : 4, 'money': 40}]
1. If the value of ID in the dictionary is odd, add 20 to the value of money
2. If the value of ID in the dictionary is even, add 10 to the value of money
3. Print out the list , see the final result

The implementation code is as follows:

my_list = [{'id': 1, 'money': 10}, {'id': 2, 'money': 20}, {'id': 3, 'money': 30}, {'id': 4, 'money': 40}]

def func():
    for i in my_list:
        if i.get('id') % 2 == 1:
            i['money'] = i.get('money') + 20
        else:
            i['money'] = i.get('money') + 10
    print(my_list)
func()

operation result:

 

3. Extract data from the log information of program operation

my_dict = {'login': [{'desc': 'correct username and password', 'username': 'admin', 'password': '123456', 'expect': 'login successful'}, {'
                    desc ': 'Wrong username', 'username': 'root', 'password': '123456', 'expect': 'Login failed'}, {'desc': 'Wrong password', 'username'
                    : 'admin', 'password': '123123', 'expect': 'Login failed'},
                    {'desc': 'Wrong username and password', 'username': 'aaaa', 'password': '123123' , 'expect': 'login failed'}],
           'register': [{'desc': 'register1', 'username': 'abcd', 'password': '123456'},
                    {'desc': 'Registration 1', 'username': 'xyz', 'password': '123456'}]}

Simulation scenario: Extracting data from the log information of program operation
1. Customize the program to achieve the following requirements
2. Be able to obtain the information input by the tester (login/test)
3. Need to form the extracted data into a tuple type (definition tuple)
4. Need to add the tuple to a new list append()
5. Print the extracted data on the console

The implementation code is as follows:

my_dict = {
  "登录": [
    {
      "desc": "正确的用户名密码",
      "username": "admin",
      "password": "123456",
      "expect": "登录成功"
    },
    {
      "desc": "错误的用户名",
      "username": "root",
      "password": "123456",
      "expect": "登录失败"
    },
    {
      "desc": "错误的密码",
      "username": "admin",
      "password": "123123",
      "expect": "登录失败"
    },
    {
      "desc": "错误的用户名和密码",
      "username": "aaaa",
      "password": "123123",
      "expect": "登录失败"
    }
  ],
  "注册": [
    {
      "desc": "注册1",
      "username": "abcd",
      "password": "123456"
    },
    {
      "desc": "注册1",
      "username": "xyz",
      "password": "123456"
    }
  ]
}

def ceshiinform():
    inform=[]
    mytuple=()
    opt=input("请输入需要获取的信息:")
    print(f"想要获取的信息为{opt}")
    if opt=='注册':
        print('获取注册信息如下:')
        for i in my_dict.get('注册'):
                    mytuple=(i.get('username'),i.get('password'))
                    inform.append(mytuple)
        print(inform)
    elif opt=='登录':
        print ('获取登录信息如下:')
        for i in my_dict.get('登录'):
            mytuple=((i.get('username')),i.get('password'))
            inform.append(mytuple)
        print(inform)
ceshiinform()

operation result:

 

4. Calculate the average score and total score

  1. Receive the scores of three courses from the keyboard, calculate the average score and total score of the three courses, and write a function to realize the function

 

The implementation code is as follows:

a1=input("请输入java成绩:")
a2=input("请输入C#成绩:")
a3=input("请输入DB成绩:")
b1=int(a1)
b2=int(a2)
b3=int(a3)
print("总成绩为:%d"%(b1+b2+b3))
print("均分:%d"%((b1+b2+b3)/3))

operation result:

 

5. Add and display customer name

  1. Create a function to add and display customer names

    Implementation code:
name1 = input('请输入客户姓名:')
name2 = input('请输入客户姓名:')
name3 = input('请输入客户姓名:')
name4 = input('请输入客户姓名:')

students = [
    {'name1': name1, 'name2': name2, 'name3': name3, 'name4': name4},
]


print('*******************')
print('客户姓名列表:')
print('*******************')

print(students)

operation result:

 

6. Modify the customer name

  1. Modify the student's name, enter the new and old name, modify and display whether the modification is successful

The implementation code is as follows:

import pprint

name1 = input('请输入客户姓名:')
name2 = input('请输入客户姓名:')
name3 = input('请输入客户姓名:')
name4 = input('请输入客户姓名:')

students = [
    {'name1': name1, 'name2': name2, 'name3': name3, 'name4': name4},
]


print('*******************')
print('客户姓名列表:')
print('*******************')

print(students)


students = [
    {'name1': name1, 'name2': name2, 'name3': name3, 'name4': name4},

    ]

name1 = input('请输入你要修改学生的姓名:')

for stu in students:

    if name1 == stu['name1']:
        print('(如果不想修改,直接回车!)')
        name1 = input('请重新输入学生的姓名:')

        if name1:
            stu['name1'] = name1
            break
else:
    print('该学生不存在, 请检查名字是否输入正确!')

pprint.pprint(students)

operation result:

 

7. Simulate bank account business

  1. Simulate bank account business
  2. Add function with parameters to realize deposit and withdrawal business
      • The initial amount of the account at the time of deposit is 0 yuan
      • Give a reminder if the balance is insufficient when withdrawing money

The implementation code is as follows:

import datetime


class Bank(object):
    account_log = []

    def __init__(self, name):
        self.name = name

    def deposit(self, amount):      # 存钱
        user.balance += amount
        self.write_log('存钱', amount)

    def withdrawal(self, amount):   # 取钱
        if amount > user.balance:
            print("余额不足")
        else:
            user.balance -= amount
            self.write_log('取钱', amount)

    def write_log(self, type, amount):  # 写日志
        now = datetime.datetime.now()
        ct = now.strftime("%Y-%m-%d %H:%M:%S")
        data = [self.name, user.name, ct, type, amount, f"{user.balance:.2f}"]
        Bank.account_log.append(data)


class User(object):
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance

    def print_log(self):
        for item in Bank.account_log:
            print(item)


def show_menu():
    menu = '''
    0: 退出
    1: 存款
    2: 取款
    '''
    print(menu)


bank = Bank("贵阳银行")
user = User('lxw-pro', 520)

while True:
    show_menu()
    num = int(input("请输入菜单编号:"))
    if num == 0:
        print("谢谢使用!")
        break
    elif num == 1:
        print("存款")
        amount = float(input("请输入存款金额:"))
        bank.deposit(amount)
        print(f"当前金额是{user.balance:.2f}")
    elif num == 2:
        print("取款")
        amount = float(input("请输入取款金额:"))
        bank.withdrawal(amount)
        print(f"当前金额是{user.balance:.2f}")
    else:
        print("输入有误!")

0

 operation result:

 

Guess you like

Origin blog.csdn.net/qq_63010259/article/details/130612053