
当你第一次学习编程时,python 因一个特殊原因而脱颖而出:它的设计目的几乎像英语一样阅读。与使用大量符号和括号的其他编程语言不同,python 依赖于简单、干净的格式,使您的代码看起来像组织良好的文档。
将 python 的语法视为语言的语法规则。正如英语有关于如何构造句子以使含义清晰的规则一样,python 也有关于如何编写代码以便人类和计算机都能理解的规则。
让我们从最简单的 python 语法元素开始:
# this is a comment - python ignores anything after the '#' symbol
student_name = "alice" # a variable holding text (string)
student_age = 15 # a variable holding a number (integer)
# using variables in a sentence (string formatting)
print(f"hello, my name is {student_name} and i'm {student_age} years old.")
在此示例中,我们使用了 python 的几个基本元素:
python可以像计算器一样进行计算和比较:
# basic math operations
total_score = 95 + 87 # addition
average = total_score / 2 # division
# comparisons
if student_age >= 15:
print(f"{student_name} can take advanced classes")
这就是 python 真正独特的地方:python 使用缩进,而不是使用括号或特殊符号将代码组合在一起。乍一看这可能看起来很奇怪,但它使 python 代码异常清晰易读。
立即学习“Python免费学习笔记(深入)”;
将缩进想象为组织详细大纲的方式:
def make_sandwich():
print("1. get two slices of bread") # first level
if has_cheese:
print("2. add cheese") # second level
print("3. add tomatoes") # still second level
else:
print("2. add butter") # second level in else block
print("4. put the slices together") # back to first level
每个缩进块都告诉 python“这些行属于一起”。这就像在大纲中创建一个子列表 - “if has_cheese:”下缩进的所有内容都是该条件的一部分。
让我们看看python缩进的关键规则:
def process_grade(score):
# rule 1: use exactly 4 spaces for each indentation level
if score >= 90:
print("excellent!")
if score == 100:
print("perfect score!")
# rule 2: aligned blocks work together
elif score >= 80:
print("good job!")
print("keep it up!") # this line is part of the elif block
# rule 3: unindented lines end the block
print("processing complete") # this runs regardless of score
随着您的程序变得更加复杂,您通常需要多级缩进:
def check_weather(temperature, is_raining):
# first level: inside function
if temperature > 70:
# second level: inside if
if is_raining:
# third level: nested condition
print("it's warm but raining")
print("take an umbrella")
else:
print("it's a warm, sunny day")
print("perfect for outdoors")
else:
print("it's cool outside")
print("take a jacket")
让我们看一个更复杂的示例,它展示了缩进如何帮助组织代码:
def process_student_grades(students):
for student in students: # first level loop
print(f"checking {student['name']}'s grades...")
total = 0
for grade in student['grades']: # second level loop
if grade > 90: # third level condition
print("outstanding!")
total += grade
average = total / len(student['grades'])
# back to first loop level
if average >= 90:
print("honor roll")
if student['attendance'] > 95: # another level
print("perfect attendance award")
# good: clear and easy to follow
def check_eligibility(age, grade, attendance):
if age < 18:
return "too young"
if grade < 70:
return "grades too low"
if attendance < 80:
return "attendance too low"
return "eligible"
# avoid: too many nested levels
def check_eligibility_nested(age, grade, attendance):
if age >= 18:
if grade >= 70:
if attendance >= 80:
return "eligible"
else:
return "attendance too low"
else:
return "grades too low"
else:
return "too young"
class student:
def __init__(self, name):
self.name = name
self.grades = []
def add_grade(self, grade):
# notice the consistent indentation in methods
if isinstance(grade, (int, float)):
if 0 <= grade <= 100:
self.grades.append(grade)
print(f"grade {grade} added")
else:
print("grade must be between 0 and 100")
else:
print("grade must be a number")
# wrong - inconsistent indentation
if score > 90:
print("great job!") # error: no indentation
print("keep it up!") # error: inconsistent indentation
# right - proper indentation
if score > 90:
print("great job!")
print("keep it up!")
# wrong - mixed tabs and spaces (don't do this!)
def calculate_average(numbers):
total = 0
count = 0 # this line uses a tab
for num in numbers: # this line uses spaces
total += num
尝试编写这个程序来练习缩进和语法:
def grade_assignment(score, late_days):
# Start with the base score
final_score = score
# Check if the assignment is late
if late_days > 0:
if late_days <= 5:
# Deduct 2 points per late day
final_score -= (late_days * 2)
else:
# Maximum lateness penalty
final_score -= 10
# Ensure score doesn't go below 0
if final_score < 0:
final_score = 0
# Determine letter grade
if final_score >= 90:
return "A", final_score
elif final_score >= 80:
return "B", final_score
elif final_score >= 70:
return "C", final_score
else:
return "F", final_score
# Test the function
score = 95
late_days = 2
letter_grade, final_score = grade_assignment(score, late_days)
print(f"Original Score: {score}")
print(f"Late Days: {late_days}")
print(f"Final Score: {final_score}")
print(f"Letter Grade: {letter_grade}")
现在您已经了解了 python 的基本语法和缩进:
记住:良好的缩进习惯是成为熟练python程序员的基础。花点时间掌握这些概念,剩下的就会水到渠成!
以上就是Python 基本语法和缩进:完整的初学者指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号