2017-09-08 208 views
-1

我可能會不斷地用Python來詢問我的項目(因爲我已經有3個幫助請求了),但我只是想盡可能做到這一點。這次我想製作一個if語句來檢查用戶是否輸入了一個整數(數字)而不是別的,因爲當他們沒有輸入數字時,程序就會崩潰,我不喜歡那樣,我喜歡提示他們發出一條消息,說他們需要輸入一個數字,而不是別的。如何檢查用戶是否輸入了一個整數(Python)

這裏是我的代碼:

def main(): 
    abc = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz' 
    message = input("What's the message to encrypt/decrypt? ") 
    key = int(input("What number would you like for your key value? ")) 
    choice = input("Choose: encrypt or decrypt. ") 
    if choice == "encrypt": 
     encrypt(abc, message, key) 
    elif choice == "decrypt": 
     encrypt(abc, message, key * (-1)) 
    else: 
     print("Bad answer, try again.") 

def encrypt(abc, message, key): 
    text = "" 
    for letter in message: 
     if letter in abc: 
      newPosition = (abc.find(letter) + key * 2) % 52 
      text += abc[newPosition] 
     else: 
      text += letter 
    print(text) 
    return text 

main() 

我猜if聲明必須在def encrypt(abc, message, key)方法的地方,但我可能是錯的,你可以請幫我找出如何解決這個問題,我將非常感謝您的時間來幫助我。

謝謝!!!

回答

0

使用try .. except

try: 
    key = int(input('key : ')) 
    # => success 
    # more code 
except ValueError: 
    print('Enter a number only') 

在您的代碼:

def main(): 
    abc = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz' 
    message = input("What's the message to encrypt/decrypt? ") 
    choice = input("Choose: encrypt or decrypt. ") 
    def readKey(): 
     try: 
     return int(input("What number would you like for your key value? ")) 
     except ValueError: 
     return readKey() 
    key = readKey() 
    if choice == "encrypt": 
     encrypt(abc, message, key) 
    elif choice == "decrypt": 
     encrypt(abc, message, key * (-1)) 
    else: 
     print("Bad answer, try again.") 

def encrypt(abc, message, key): 
    text = "" 
    for letter in message: 
     if letter in abc: 
      newPosition = (abc.find(letter) + key * 2) % 52 
      text += abc[newPosition] 
     else: 
      text += letter 
    print(text) 
    return text 

main() 
+0

你有沒有在代碼中的任何想法,我可以把這個?你認爲我應該把它放在'如果在ABC的信中:'??? – Kieran

+0

@基蘭我更新了我的答案。 –

+0

非常感謝你的幫助! – Kieran

相關問題