4 回答

TA貢獻1793條經驗 獲得超6個贊
刪除elseandcontinue語句,因為循環總是命中 thecontinue而永遠不會到達n=n//10
num= int(input("enter a number"))
n=num
digit = int(input("enter the digit"))
times=0
while n > 0 :
d = n%10
if d==digit :
times += 1
n=n//10
print ("no. of times digit gets repeated is ", times)
輸出:
enter a number1111222233344567433232222222
enter the digit2
no. of times digit gets repeated is 12

TA貢獻1810條經驗 獲得超4個贊
if d==digit :
times += 1
continue
else:
continue
n=n//10
無法到達上面除以 10 的代碼行,因為 true 和 false 分支都以 重新啟動循環,因此永遠不會更改值并且您將永遠循環(對于非零數字輸入)。ncontinuen
您應該continue從兩個分支中刪除,事實上,您不需要該部分else,因為它不執行任何操作:
if d == digit:
times += 1
n = n // 10

TA貢獻1843條經驗 獲得超7個贊
其他答案指出了您的continue
誤用,但有幾種 Pythonic 方法可以做到這一點。
divmod()
在一次操作中巧妙地進行除法和取模:
num = int(input("enter a number"))
digit = int(input("enter the digit"))
times = 0
while num > 0:
? ? num, d = divmod(num, 10)
? ? if d == digit:
? ? ? ? times += 1
print("no. of times digit gets repeated is ", times)
您也可以更簡單地不對數字做任何事情,而是對字符串做任何事情,然后使用str.count:
num = input("enter a number")
digit = input("enter the digit")
print("no. of times digit gets repeated is ", num.count(digit))
添加回答
舉報