Python Comment是程序员必不可少的工具。注释通常用于解释代码。如果代码有正确的解释,我们可以轻松理解代码。一个好的程序员必须使用这些注释,因为将来任何人都希望修改代码以及实现新模块。然后,可以轻松完成。
在其他编程语言(例如C ++)中,它为单行注释提供// //,为多行注释提供/ * .... * /,但是Python提供了单行Python注释。要在代码中应用注释,我们在语句或代码的开头使用hash(#)。
让我们了解以下示例。
# This is the print statement print("Hello Python")
在这里,我们使用hash(#)对print语句进行了注释。它不会影响我们的印刷声明。
我们必须在每行代码的开头使用hash(#)来应用多行Python注释。考虑以下示例。
# First line of the comment # Second line of the comment # Third line of the comment
示例: strong>
# Variable a holds value 5 # Variable b holds value 10 # Variable c holds sum of a and b # Print the result a = 5 b = 10 c = a+b print("The sum is:", c)
输出 strong>:
The sum is: 15
即使绝对的初学者也可以理解以上代码,因为代码每一行都在发生什么。这是在代码中使用注释的优势。
我们也可以使用三引号('''''')进行多行注释。三重引号还用于字符串格式化。考虑以下示例。
文档字符串注释主要在模块,函数,类或方法中使用。这是一个文档Python字符串。我们将在进一步的教程中解释类/方法。
示例: strong>
def intro(): """ This function prints Hello Joseph """ print("Hi Joseph") intro()
输出 strong>:
Hello Joseph
我们可以使用__doc__属性检查函数的文档字符串。
通常,四个空格用作缩进。缩进量取决于用户,但是在整个块中缩进量必须保持一致。def intro(): """ This function prints Hello Joseph """ print("Hello Joseph") intro.__doc__
输出 strong>:
Output: '\n This function prints Hello Joseph\n '
Python缩进 uses to define the block of the code. The other programming languages such as C, C++, and Java use curly braces {}, whereas Python uses an indentation. Whitespaces are used as indentation in Python.
缩进使用在代码的开头,并以意外行结尾。相同的行缩进定义了代码块(函数的主体,循环等)
通常,四个空格用作缩进。缩进量取决于用户,但是在整个块中缩进量必须保持一致。
for i in range(5): print(i) if(i == 3): break
为了表示代码块,我们在代码块的每一行缩进了相同的空格。
考虑以下示例。
dn = int(input("Enter the number:")) if(n%2 == 0): print("Even Number") else: print("Odd Number") print("Task Complete")
输出 strong>:
Enter the number: 10 Even Number Task Complete
上面的代码 if strong>和 else strong>是两个单独的代码块。两个代码块都缩进了四个空格。 print(" Task Complete")语句没有缩进四个空格,并且不在 if-else strong>块之内。
如果缩进使用不正确,则会导致 IndentationError strong>。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)