这个编程有什么问题?

时间:2014-04-12 12:36:49

标签: python

这让我误以为,我将在最后说明错误:

import math
# Target:
# Enter an input and it will convert into GB, MB and KB with the leftover bytes in it
def start():
print ''
print ''
# 10 = 1 billion
byte = input("Bytes: ")
tw = int(math.log10(byte))+1
tw = tw - 7
gb = byte // 10**9
byte = str(byte)
a = len(byte) - 6
b = len(byte) - 3
if b > 0:
    if a > 0:
        kb = int(str(byte)[a:b])

    else:
        kd = int(str(byte)[0:b])
else:
    kb = 0
c = len(byte) - 6
if c > 1:   
    mb = int(str(byte)[0:c])
    if int(mb) > 999:
        if int(mb) < 10000:
            mb = mb // 10**3
            byte = str(byte)
            if len(byte) <= 3:
                mb = 0
                kb = 0
else:
    mb = 0 

d = len(byte) - 6
byte = int(byte)
lob = int(str(byte)[d:])
byte = str(byte)
if int(kb) > 1000:
    dmb = mb // 10**3
    mb = mb + dmb
    kb = kb // 10**3 
print ''
print ''
print ''
print('     GB: %s MB: %s KB: %s') % (gb, mb, kb)
print('     Bytes: %s') % lob
print ''
print ''
print ''
start()

这有什么问题? 它一直在说:

Traceback (most recent call last):
File "bytes.py", line 53, in <module>
start()
File "bytes.py", line 39, in start
if int(kb) > 1000:
UnboundLocalError: local variable 'kb' referenced before assignment

出了什么问题?!一世 我不断将第39行改为不同的地方,但我不知道如何修复它? 使用UnboundLocalError,我无法弄清楚局部变量&#39; kb&#39;在分配之前引用。救命啊!

1 个答案:

答案 0 :(得分:1)

除了几个丑陋的反模式之外,还有一个明显的错误/错字:好好看看

if a > 0:
    kb = int(str(byte)[a:b])

else:
    kd = int(str(byte)[0:b])

您现在看到错误的来源吗?