Python中的递增和递减运算符

如果您熟悉Python,就会知道它不允许使用递增和递减运算符(前置和后置)。

null

Python的设计目的是保持一致性和可读性。在使用++和-运算符的语言中,新手程序员的一个常见错误是混淆了递增/递减运算符前后的差异(优先级和返回值)。简单的递增和递减运算符不像其他语言那样需要。

你不会写这样的东西:

for (int i = 0; i < 5; ++i)

对于正常使用,如果要增加计数,可以使用

i+=1 or i=i+1

相反,在Python中,我们编写如下,语法如下:

for variable_name in range(start, stop, step)
  • 开始:可选。一个整数,指定从哪个位置开始。默认值为0
  • 停止:指定结束位置的整数。
  • 步骤:可选。指定递增的整数。默认值为1

Python3

# A sample use of increasing the variable value by one.
count = 0
count + = 1
count = count + 1
print ( 'The Value of Count is' ,count)
# A Sample Python program to show loop (unlike many
# other languages, it doesn't use ++)
# this is for increment operator here start = 1,
# stop = 5 and step = 1(by default)
print ( "INCREMENTED FOR LOOP" )
for i in range ( 0 , 5 ):
print (i)
# this is for increment operator here start = 5,
# stop = -1 and step = -1
print ( " DECREMENTED FOR LOOP" )
for i in range ( 4 , - 1 , - 1 ):
print (i)


输出

INCREMENTED FOR LOOP01234 DECREMENTED FOR LOOP43210

Output-1: INCREMENTED FOR LOOP01234Output-2: DECREMENTED FOR LOOP43210

本文由巴萨瓦拉贾撰稿。如果你喜欢Geeksforgek并想投稿,你也可以使用contribute写一篇文章。极客。组织或邮寄你的文章进行评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享