1、字符类型的转换
"""把输入的字符串转换为数字"""
score = input("请输入字符串:")
print(type(score))
score_int = int(score)
print(type(score_int))
"""把输入的字符串转化为浮点数"""
score_str = input("请输入字符串:")
print(type(score_str))
score_int = int(score_str)
print(type(score_int))
score_float = float(score_int)
print(type(score_float))
"""字符串小数直接转为整数类型"""
score_str = input("请输入字符串小数:")
print(type(score_str))
score_str = float(score_str)
print(type(score_float))
score_int = int(score_float)
print(type(score_int))
输出结果:
D:\Study\test1121\venv\Scripts\python.exe D:/Study/test1121/test001.py
请输入字符串:123124
<class 'str'>
<class 'int'>
请输入字符串:12345345634645
<class 'str'>
<class 'int'>
<class 'float'>
请输入字符串小数:12232345.56457
<class 'str'>
<class 'float'>
<class 'int'>
Process finished with exit code 0
2、if....else的使用语法:
"""if....else关系"""
"""举例:如果分数为60分以上,则为合格,如果分数为70分以上,则为良好,如果分数为80分以上,则为优秀,如果分数为90分以上,则为精英。否则成绩不合格,淘汰"""
score = input("请输入笔试成绩:")
score_int = int(score)
if 60 <= score_int < 70:
print(f"成绩为{score_int}分,合格!")
elif 70 <= score_int < 80:
print(f"成绩为{score_int}分,良好!")
elif 80 <= score_int < 90:
print(f"成绩为{score_int}分,优秀!")
elif score_int >= 90:
print(f"成绩为{score_int},精英!")
else:
print("成绩不合格,您已被淘汰!")
输出结果:
D:\Study\test1121\venv\Scripts\python.exe D:/Study/test1121/test001.py
请输入笔试成绩:89
成绩为89分,优秀!
Process finished with exit code 0
3、while 语法结构:
示例一、
"""while循环语句"""
"""输出10位数"""
num = 1
while num <= 10:
print(f"输出数:{num}")
num += 1
print("打印完成")
输出结果:
D:\Study\test1121\venv\Scripts\python.exe D:/Study/test1121/test001.py
输出数:1
输出数:2
输出数:3
输出数:4
输出数:5
输出数:6
输出数:7
输出数:8
输出数:9
输出数:10
打印完成
Process finished with exit code 0
示例二、
users = []
user_id = 1
while True:
print("\n=== 用户管理系统 ===")
print("1. 添加用户")
print("2. 查看用户")
print("3. 退出系统")
choice = input("请选择操作 (1/2/3): ")
# 输入验证
if choice not in ["1", "2", "3"]:
print("无效选择,请重新输入!")
continue # 跳过本次循环剩余代码,重新显示菜单
if choice == "3":
print("系统退出,再见!")
break # 退出整个循环,结束程序
if choice == "1":
name = input("请输入用户名: ").strip()
# 用户名验证
if not name:
print("用户名不能为空!")
continue
if len(name) < 2:
print("用户名至少2个字符!")
continue
# 添加用户
users.append({"id": user_id, "name": name})
print(f"用户 '{name}' 添加成功!ID: {user_id}")
user_id += 1
elif choice == "2":
if not users:
print("当前没有用户!")
continue # 跳过空的用户列表显示
print("\n当前用户列表:")
for user in users:
print(f"ID: {user['id']}, 姓名: {user['name']}")
输出结果:
D:\Study\test1121\venv\Scripts\python.exe D:/Study/test1121/test001.py
=== 用户管理系统 ===
1. 添加用户
2. 查看用户
3. 退出系统
请选择操作 (1/2/3): 4
无效选择,请重新输入!
=== 用户管理系统 ===
1. 添加用户
2. 查看用户
3. 退出系统
请选择操作 (1/2/3): 3
系统退出,再见!
Process finished with exit code 0

被折叠的 条评论
为什么被折叠?



