Python has a number of differences with C + +, some of which are easily overlooked and cause program errors. Here is a list of some for your reference. Continuous update ... Python does not have a self-decrement operator
There are ++i, i++ 、--i and I--。 in C + + Python, however, does not have those operators. A common loop for C/s + + is:
for (int i = 0; i < ++i)
{
std::cout << i << Endl;
}
and Python's corresponding loop is:
For I in range:
print (i)
Perhaps this is one of the important reasons Python does not provide a self-decrement operator: there is no such common use case. If you really want to, in most cases you can use i + = 1,i = to replace.
Note that although Python does not support the + + operator, ++i does not complain. ++i is interpreted as + (+ (i)).
>>>> i = 3
>>> ++i
3
>>> i++
syntaxerror:invalid syntax
python functions always have return values A common error in C + +: "Not all control paths return a value". If any of the paths do not return a value, an error occurs.
Error:not all control paths returns
int f (BOOL flag)
{
if (flag)
{return
1;
}
}
But the corresponding Python program doesn't have any problems:
def f (flag):
If flag: Return
1
>>> print (f (True))
>>> 1
>>> print (f (False))
>>> None
Although Python does not complain, it is recommended that you return None in the event that the function has a returned value. In this way, others will not be confused when they see this code: Does the author really want to rely on implicit return to go back to none or to leave a value.
Scope The scope of the For Loop loop variable in c/n + + is limited to for and corresponding to {} itself, and the scope disappears after the for end.
for (int i = 0; i < ++i)
{
.
}
V---undeclared variable "i"
if (i = =)
.
In Python, for statements (and while, if, and so on) do not have a separate scope of their own. The scope of the loop variable i is the scope of the function f that contains it.
def f (): For
I in Range (a):
..
ok!
if i = =:
..
Look at one more example. The scope of a is the {} that contains it, the closing parenthesis, and the scope disappears. This is an obvious mistake.
if (condition)
{
int a = 1;
}
error!
Std::cout << A;
Python, as a dynamic language, fully supports such use. In fact, a name can be used only if it has been assigned a value before it is used.
If condition:
a = 1
//ok!
Print (a)
The last value of the For loop often encounters a situation where the end of a loop requires a look at how it ends. One method is to see what the last value of the loop variable i is. If equal to 10, indicates that the condition found did not occur. You can do this because C + + will ++i at the end of each loop, even if it is the last cycle.
int i;
for (i = 0; i < ++i)
{
.
if (found)
break
}
//not found
if (i = =)
...
And because Python has different loops, the final value of a loop variable is the maximum valid value of 9, not 10, in range.
For I in range:
if found: Break
Else:
# not found
.
Print (i) # 9
In update ...