第二章 2.4 可以复用的代码 p43_2_4_match.py

代码:

def match_num(num):
    f=[6,2,5,5,4,5,6,3,7,6]
    if num==0:
        total=f[0]
    else:
        total=0
    while num>0:
        x=num%10
        total=total+f[x]
        num=num//10
    return total

snum=6
print("Six matches can spell the numbers:")
for i in range(112):
    if match_num(i)==snum:
        print(i)

  

效果:

0
6
9
14
41
77
111

  

总结:

函数的定义要放在上面,调用函数在下面,否则NameError: name 'match_num' is not defined;

0-9//10 都是0,0-9%10都是本身,110以上整除10将十位数变成了个位数,整除是取整数,舍去小数点后面的;

原文地址:https://www.cnblogs.com/scholarly/p/15450165.html