30天学会Python编程:2. Python基础语法结构
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
|
student_name | ||
MAX_COUNT | ||
ClassName | ||
module_name.py |
name
≠ Name
1var
❌class = 5
❌str = "hello"
❌函数原型:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
参数说明:
objects:要输出的对象,多个用逗号分隔
sep:分隔符,默认空格
end:结束字符,默认换行
file:输出目标,默认标准输出
flush:是否立即刷新缓冲区
实用示例:
# 格式化输出
name = "Alice"
age = 25
print(f"{name} is {age} years old") # f-string (Python 3.6+)
# 多参数输出
print("Value:", 10, "Type:", type(10), sep="|", end="!\n")
# 输出:Value:|10|Type:|<class 'int'>!
函数原型:
input(prompt='') -> str
使用示例:
name = input("请输入你的名字:")
print(f"你好,{name}!")
# 类型转换
age = int(input("请输入年龄:"))
注意事项:
Python 3.10共有35个关键字:
import keyword
print(keyword.kwlist)
表2 主要关键字分类
# 条件判断示例
if age >= 18:
print("成年人")
elif age >= 12:
print("青少年")
else:
print("儿童")
# 循环控制示例
for i inrange(5):
if i == 3:
continue
print(i)
# 用户登录系统
MAX_ATTEMPTS = 3
correct_password = "python123"
attempts = 0
while attempts < MAX_ATTEMPTS:
password = input("请输入密码:")
if password == correct_password:
print("登录成功!")
break
else:
attempts += 1
print(f"密码错误,还剩{MAX_ATTEMPTS - attempts}次机会")
else:
print("账户已锁定,请联系管理员")
def celsius_to_fahrenheit(celsius):
"""摄氏温度转华氏温度
Args:
celsius (float): 摄氏温度值
Returns:
float: 华氏温度值
"""
return celsius * 9/5 + 32
# 用户交互
try:
temp_c = float(input("请输入摄氏温度:"))
temp_f = celsius_to_fahrenheit(temp_c)
print(f"{temp_c}℃ = {temp_f:.1f}℉") # 保留1位小数
except ValueError:
print("请输入有效的数字!")
缩进错误:
def func():
print("缩进错误") # IndentationError
语法缺失:
if True # 缺少冒号
print("Hello")
命名冲突:
import = 10 # 使用关键字作为变量名
print()
输出中间值python -i script.py
)
核心要点:
实践建议:
进阶方向:
常见陷阱:
阅读原文:原文链接