亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 python 中沒有響應

在 python 中沒有響應

婷婷同學_ 2023-04-25 17:45:48
我寫了一個簡單的代碼:輸入任意數字和數字并計算數字在數字中的次數。我寫的代碼是:num= int(input("enter a number"))n=numdigit = int(input("enter the digit"))times=0while n > 0 :    d = n%10    if d==digit :        times += 1        continue    else:        continue    n=n//10print ("no. of times digit gets repeated is ", times)當我嘗試這段代碼時,不知何故它什么也沒給我
查看完整描述

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


查看完整回答
反對 回復 2023-04-25
?
慕萊塢森

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


查看完整回答
反對 回復 2023-04-25
?
阿波羅的戰車

TA貢獻1862條經驗 獲得超6個贊

由于前面有 s,該行n=n//10永遠不會執行。continue如果您不打算跳過此循環迭代的剩余部分,則不需要繼續。



查看完整回答
反對 回復 2023-04-25
?
藍山帝景

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))


查看完整回答
反對 回復 2023-04-25
  • 4 回答
  • 0 關注
  • 162 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號