两个几乎相同的代码在 Python 中给出了不同的输出。任何人都可以解释原因吗?

Two nearly same codes are giving different output in Python. Can anyone explain the reason?

我一直在尝试编写一个程序来反转 Python 中的数字,但它没有按预期工作,而仅将条件分配给变量,它使代码工作正常。请解释为什么会发生这种情况,或者这是否是错误。

我正在使用 Python 3.10.4。代码如下。

这个不起作用,因为我猜问题出在 while 循环及其条件中。

num2 = int(input("Enter the number to be reversed: "))
c = 0
rev = 0
while c!=len(str(num2)):
    n = num2%10
    rev=rev*10+n
    num2=num2//10
    c+=1
print("The reversed number is:",rev)

输出:

Enter the number to be reversed: 1568
The reversed number is: 86

这只通过将条件的一部分分配给变量就可以按预期工作

num2 = int(input("Enter the number to be reversed: "))
c = 0
rev = 0
length = len(str(num2))
while c!=length:
    n = num2%10
    rev=rev*10+n
    num2=num2//10
    c+=1
print("The reversed number is:",rev)

输出:

Enter the number to be reversed: 1568
The reversed number is: 8651

while 循环中的条件在每次迭代中再次计算。因为您的第一个版本评估了 num2current 长度并且您更改了循环内的值,所以您有一个错误。如果您出于某种原因更喜欢这种公式,请更改代码,使其在循环内使用不同的变量(初始化为 num2 的副本);但代码的第二个版本更清晰正确。

但是,还要注意 Python 已经知道如何反转字符串。

rev_num = int(str(num2)[::-1])

我认为您也可以使用简单的字符串切片来获得相同的结果

num_to_rev = 1568
rev_num = str(num_to_rev)[::-1]
print(rev_num)