2015-10-20 154 views
0

我是新来的Python,制作一个不错的小加密程序。取3个数字并将它们吐出每个数字+7,并交换第一个和最后一个数字。在底部它不会打印我的加密变量。 NameError:全局名称'encrypted'未定义...但它是?除非你给他们打电话NameError:全局名称未定义帮助

def main(): 
    global unencrypted, encrypted 
    unencrypted = int (input("Enter a 3-digit number: ")) 

    def isolate_digits():     # separate the 3 digits into variables 
     global units, tenths, hundreths 
     units = unencrypted % 10 
     tenths = (unencrypted/10) % 10 
     hundreths = (unencrypted/100) % 10 

    def replace_digits():     # perform the encryption on each digit 
     global encrypted_unit, encrypted_tenths, encrypted_hendreths 
     encrypted_unit = ((units + 7) % 10) 
     encrypted_tenths = ((tenths + 7) % 10) 
     encrypted_hendreths = ((hundreths + 7) %10) 

    def swap_digit_1_with_digit_3(): 
     temp = encrypted_unit 
     encrypted_unit = encrypted_hundreths 
     encrypted_hundreths = temp 

    def recompose_encrypted_number():  # create the encrypted variable 
     global encrypted 
     encrypted = encrypted_unit * 1 + encrypted_tenths * 10 + encrypted_hundreths * 100 

    print("Unencrypted: ", unencrypted) 
    print("Encrypted: ", encrypted) 

main() 

回答

0
  1. 功能没有做任何事情。
  2. 您在swap_digit_1_with_digit_3中缺少global声明。
  3. 您以两种不同的方式拼写encrypted_hundreths

 

def main(): 
    global unencrypted, encrypted 
    unencrypted = int (input("Enter a 3-digit number: ")) 

    def isolate_digits():     # separate the 3 digits into variables 
     global units, tenths, hundreths 
     units = unencrypted % 10 
     tenths = (unencrypted/10) % 10 
     hundreths = (unencrypted/100) % 10 

    def replace_digits():     # perform the encryption on each digit 
     global encrypted_unit, encrypted_tenths, encrypted_hundreths 
     encrypted_unit = ((units + 7) % 10) 
     encrypted_tenths = ((tenths + 7) % 10) 
     encrypted_hundreths = ((hundreths + 7) %10) 

    def swap_digit_1_with_digit_3(): 
     global encrypted_unit, encrypted_hundreths 
     temp = encrypted_unit 
     encrypted_unit = encrypted_hundreths 
     encrypted_hundreths = temp 

    def recompose_encrypted_number():  # create the encrypted variable 
     global encrypted 
     encrypted = encrypted_unit * 1 + encrypted_tenths * 10 + encrypted_hundreths * 100 

    isolate_digits() 
    replace_digits() 
    swap_digit_1_with_digit_3() 
    recompose_encrypted_number() 
    print("Unencrypted: ", unencrypted) 
    print("Encrypted: ", encrypted) 

main() 

结果:

Enter a 3-digit number: 123 
Unencrypted: 123 
Encrypted: 101.23 
+0

感谢您的回复迅速,有什么简单的错误作出。我遇到的另一个问题是应该输出+7到每个第一个数字,然后将第一个数字与最后一个数字交换。 例如111将成为888 或314将成为180(10)8(11) 它只是给我随机浮点数 – outram88

+0

哦,在你需要整数除法在'isolate_digits'这种情况下。用''替换每个'/'。这将导致结果为整数而不是浮点数。 – Kevin

+0

我在isolate_digits中没有使用/它在哪里? – outram88

相关问题