Python中的语句,缩进和注释用法介绍

2021年4月2日10:56:34 发表评论 864 次浏览

语句

用源代码编写的用于执行的指令称为语句。 Python编程语言中有不同类型的语句, 例如Assignment语句, Conditional语句, Looping语句等。所有这些都可以帮助用户获得所需的输出。例如, n = 50是赋值语句。

多行语句:

可以使用括号(), 大括号{}, 方括号[], 分号(;), 连续字符斜杠(\)将Python中的语句扩展为一行。当程序员需要进行长时间的计算而又不能将其语句放在一行中时, 可以使用这些字符。

范例:

Declared using Continuation Character (\):
s = 1 + 2 + 3 + \
    4 + 5 + 6 + \
    7 + 8 + 9

Declared using parentheses () :
n = (1 * 2 * 3 + 7 + 8 + 9)

Declared using square brackets [] :
footballer = ['MESSI', 'NEYMAR', 'SUAREZ']

Declared using braces {} :
x = {1 + 2 + 3 + 4 + 5 + 6 +
     7 + 8 + 9}

Declared using semicolons(;) :
flag = 2; ropes = 3; pole = 4

缩进

块是所有这些语句的组合。块可以视为特定目的的语句分组。大多数编程语言(例如C, C ++, Java)都使用大括号{}来定义代码块。 Python的独特功能之一是它使用缩进来突出显示代码块。空格用于Python中的缩进。所有距离右边相同距离的语句都属于同一代码块。如果必须更深地嵌套一个块, 则只需向右缩进即可。通过查看以下代码行, 你可以更好地理解它:

# Python program showing
# indentation
  
site = 'gfg'
  
if site = = 'gfg' :
     print ( 'Logging on to lsbin...' )
else :
     print ( 'retype the URL.' )
print ( 'All set !' )

输出如下:

Logging on to lsbin...
All set !

行print('loging on to lsbin ...')和print('retype the URL。')是两个单独的代码块。我们的示例if语句中的两个代码块都缩进了四个空格。最终打印("全部已设置!")没有缩进, 因此它不属于else块。

j = 1
while (j< = 5 ):
      print (j)
      j = j + 1

输出如下:

1
2
3
4
5

要在Python中指示代码块, 你必须在代码块的每一行缩进相同的空格。 while循环中的两行代码都缩进了四个空格。指示语句所属的代码块是必需的。例如, j = 1和while(j <= 5):不缩进, 因此不在while块内。因此, Python代码通过缩进进行构造。

注释

Python开发人员经常使用注释系统, 因为如果不使用注释系统, 事情就会变得令人迷惑, 快速。注释是开发人员提供的使读者理解源代码的有用信息。它解释了代码中使用的逻辑或逻辑的一部分。当你不再需要回答有关代码的问题时, 注释通常对维护或增强你代码的人很有帮助。这些通常被认为是有用的编程约定, 它不参与程序的输出, 但是可以提高整个程序的可读性。 Python有两种类型的注释:

单行注释:

Python单行注释以无空格(#)的井号标记符号开始, 一直持续到行尾。如果注释超过一行, 则在下一行放置一个#号标签, 然后继续注释。事实证明, Python的单行注释对于提供变量, 函数声明和表达式的简短说明很有用。请参阅下面的代码片段, 以演示单行注释:

代码1:

# This is a comment
# Print "lsbin !" to console
print ( "lsbin" )

代码2:

a, b = 1 , 3 # Declaring two integers
sum = a + b # adding two integers
print ( sum ) # displaying the output

多行字符串作为注释:Python多行注释是用定界符括起来的一段文本(""")在评论的每一端。同样, 定界符之间不应有空格(""")。当注释文本不适合一行时, 它们很有用;因此需要跨越线。多行注释或段落用作其他阅读你的代码的文档。请参阅以下演示多行注释的代码段:

代码1:

"""
This would be a multiline comment in Python that
spans several lines and describes lsbin.
A Computer Science portal for geeks. It contains 
well written, well thought 
and well-explained computer science 
and programming articles, quizzes and more. 
…
"""
print ( "lsbin" )

代码2:

'''This article on lsbin gives you a 
perfect example of
multi-line comments'''
  
print ( "lsbin" )

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: