このループがどのように機能するかを説明していただけますか?最初のループの後、2番目のループの後などに何が起こっているのか。
def sum(n):
s = 0
while n:
s += n % 10
n /= 10
return s
>>> print sum(123)
6
def sum(n):
s = 0
while n:
s += n % 10
n /= 10
return s
このように書き直す方がよい(理解しやすい):
def sum(n):
s = 0 // start with s = 0
while n > 0: // while our number is bigger than 0
s += n % 10 // add the last digit to s, for example 54%10 = 4
n /= 10 // integer division = just removing last digit, for example 54/10 = 5
return s // return the result
n > 0
Pythonでは次のように簡単に書くことができますn
が、初心者には悪い習慣だと思います
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加