[英]Try/Except error Python?
我的代碼輸出應該看起來像:
加密器:
Enter 1 to encipher or 2 to decipher: 1
Enter text you wish to encipher: My dog has fleas.
Enter the number of characters to shift: 7
The encrypted text is: Fr whz atl yextl.
解碼:
Enter 1 to encipher or 2 to decipher: 2
Enter text you wish to decipher: Fr whz atl yextl.
The most likely shift is: 7
My dog has fleas.
到目前為止,我有這個,而且我一直在獲取無效的語法。 我對如何在輸出中鍵入答案感到困惑。 應該使用try / except並加上while循環,因為這是學校的作業。
while True:
try:
num = int(raw_input('Enter 1 or 2:'))
if num in [1,2]:
break
print "You have to enter 1 or 2, try again"
if (num == 1):
num = int(raw_input('Enter a number:'))
num = int(raw_input('encipher'))
print "Enter text to encipher"
print "Enter the number of characters you want to shift"
elif (num == 2):
num = int(raw_input('Enter a number:'))
num = int(raw_input('decipher'))
print "Enter text to decipher"
print "Enter the number of characters you want to shift"
您不一定需要使用try / except,但是如果您想立即在該處進行到整數的轉換,則可以。 主要問題是您在任何地方都沒有except塊。
while True:
try:
num = int(raw_input('Enter 1 or 2:'))
if num in [1,2]:
break
except ValueError as e:
print "You didn't enter a number. Try again"
您沒有正確使用try-except
。 這個想法是嘗試代碼的一部分。 但是如果遇到錯誤/異常,請執行其他操作。
while True:
try:
num = int(raw_input('Enter 1 or 2:'))
if num in [1,2]:
break
print "You have to enter 1 or 2, try again"
在腳本中,您嘗試采用數組中的int,並且正在處理方案,該方案不在您的預定義選項列表中。 但是,如果它們是該代碼塊的例外,則您什么也不做。
要使用try-except
請執行以下操作:
while True:
try:
num = int(raw_input('Enter 1 or 2:'))
if num in [1,2]:
break
print "You have to enter 1 or 2, try again"
except Exception, e:
print e
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.