NameError:未定义全局名称需要帮助

时间:2015-10-20 14:47:15

标签: python python-3.x

我是Python的新手,制作了一个不错的小加密程序。取3个数字并将它们吐出+ 7到每个数字并交换第一个和最后一个数字。在底部它不会打印我的加密变量。 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()

1 个答案:

答案 0 :(得分:0)

  1. 除非您打电话,否则功能不会执行任何操作。
  2. 您在global
  3. 中缺少swap_digit_1_with_digit_3声明
  4. 您以两种不同的方式拼写encrypted_hundreths
  5. 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