为什么我无法获得此代码的输出?
def armstrong(lower,higher):
for num in range(lower, higher+1):
order=len(str(num))
sum=0
temp = num
while temp >0:
digit=temp%10
sum += digit**order
temp//=10
if num == temp:
return num
lower=int(input('lower number: '))
higher=int(input('higher number: '))
armstrong(lower,higher)
答案 0 :(得分:0)
代码中几乎没有逻辑错误,我已经修复了它们,并添加了注释以确切显示位置。
def armstrong(lower,higher):
result_list = [] # define a result list
for num in range(lower, higher+1):
order=len(str(num))
total = 0 # Do not use sum as it is python keyword
temp = num
while temp != 0:
digit=temp%10
total += digit**order # change the variable name
temp//=10
if num == total: # Check with total instead of temp
result_list.append(num) # append to a list instead of returning
return result_list # return the total list after all results are collected.
lower=int(input('lower number: '))
higher=int(input('higher number: '))
output = armstrong(lower,higher) # store the output of the function
print(output)
输出:
lower number: 100
higher number: 500
[153, 370, 371, 407]