📜  Python中的递增和递减运算符

📅  最后修改于: 2022-05-13 01:55:03.807000             🧑  作者: Mango

Python中的递增和递减运算符

如果您熟悉Python,您就会知道其中不允许使用 Increment 和 Decrement运算符(包括 pre 和 post)。

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

你不写这样的东西:

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

对于正常使用,而不是 i++,如果要增加计数,则可以使用

i+=1 or i=i+1

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

for variable_name in range(start, stop, step)
  • 开始:可选。一个整数,指定从哪个位置开始。默认为 0
  • stop:一个整数,指定在哪个位置结束。
  • 步骤:可选。指定增量的整数。默认为 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("\n DECREMENTED FOR LOOP")
for i in range(4, -1, -1):
   print(i)


输出
INCREMENTED FOR LOOP
0
1
2
3
4

 DECREMENTED FOR LOOP
4
3
2
1
0
Output-1: INCREMENTED FOR LOOP
0
1
2
3
4
Output-2: DECREMENTED FOR LOOP
4
3
2
1
0