2015-10-20 192 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

相關問題