68 lines
1.7 KiB
Python
68 lines
1.7 KiB
Python
# 三元运算符
|
|
|
|
x = 10
|
|
result = "正数" if x > 0 else "负数"
|
|
# print(result)
|
|
|
|
|
|
# 根据用户输入设置默认值
|
|
|
|
|
|
# def get_user_input():
|
|
# user_input = input("请输入数值1~3:")
|
|
# preference = user_input if int(user_input) in [1, 2, 3] else 1
|
|
# return preference
|
|
|
|
|
|
# preference = get_user_input()
|
|
# print(preference)
|
|
|
|
|
|
# 处理空值
|
|
|
|
user_dict = [{"name": "小明", "age": 18, "id": 1}, {"name": "小红", "age": 20, "id": 2}]
|
|
|
|
filter_user = list(filter(lambda user: user["id"] == 1, user_dict))
|
|
# print(filter_user)
|
|
|
|
# 列表推导式
|
|
|
|
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
|
|
|
processed_numbers = [str(x) if x % 2 == 0 else x for x in numbers]
|
|
print(processed_numbers)
|
|
|
|
scores = [85, 92, 78, 96, 88, 91, 87, 94]
|
|
grade_list = ["优秀" if s >= 90 else "良好" for s in scores]
|
|
print(grade_list)
|
|
|
|
# 处理字符串列表
|
|
words = ["hello", "world", "python", "programming"]
|
|
# 将长度大于5的单词转换为大写,其他保持原样
|
|
processed_word = [w.upper() if len(w) > 5 else w for w in words]
|
|
print(processed_word)
|
|
|
|
|
|
def get_user_role(user_type):
|
|
return "管理员" if user_type == "admin" else "普通用户"
|
|
|
|
|
|
def calculate_discount(amount, is_vip):
|
|
# 计算折扣
|
|
# 如果是VIP用户且金额大于1000,则打8折
|
|
# 否则,不打折
|
|
discoint_rate = 0.8 if amount > 1000 and is_vip else 1
|
|
return amount * discoint_rate
|
|
|
|
|
|
result = calculate_discount(100, True)
|
|
print(result)
|
|
|
|
|
|
def format_phone_number(phone):
|
|
return f"{phone[:3]}-{phone[3:7]}-{phone[7:]}" if len(phone) == 11 else phone
|
|
|
|
|
|
print(f"格式化电话号码:{format_phone_number('13812345678')}")
|
|
print(f"格式化电话号码:{format_phone_number('1234567')}")
|