![](/img/trans.png)
[英]Two different files giving same output despite having different codes - PyQT5 and 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)
Output:
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)
Output:
Enter the number to be reversed: 1568
The reversed number is: 8651
在每次迭代中再次評估while
循環中的條件。 因為您的第一個版本評估num2
的當前長度並且您更改了循環內的值,所以您有一個錯誤。 如果您出於某種原因更喜歡此公式,請更改代碼,使其在循環內使用不同的變量(初始化為num2
的副本); 但是代碼的第二個版本是恕我直言,更清晰也更正確。
但是,還要注意 Python 已經知道如何反轉字符串。
rev_num = int(str(num2)[::-1])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.