Это решит вашу проблему
interface
TArrayStr = Array Of string;
implementation
function SplitString(Text: String): TArrayStr;
var
intIdx: Integer;
intIdxOutput: Integer;
const
Delimiter = ';';
begin
intIdxOutput := 0;
SetLength(Result, 1);
Result[0] := '';
for intIdx := 1 to Length(Text) do
begin
if Text[intIdx] = Delimiter then
begin
intIdxOutput := intIdxOutput + 1;
SetLength(Result, Length(Result) + 1);
end
else
Result[intIdxOutput] := Result[intIdxOutput] + Text[intIdx];
end;
end;
def files(a):
pass
while True:
try:
i = int(input('Select: '))
if i in range(4):
files(i)
break
except:
pass
print '\nIncorrect input, try again'
Ваш подход кажется очень длинным способом достичь чего-то довольно простого:
def Release() :
while True :
print 'Please select one of the following?\nCompletion = 0\nRelease ID = 1\nVersion ID = 2\nBuild ID = 3\n'
a = int(input("Please select the type of release required: "))
if 0 <= a < 4 :
files(a)
break
else :
print('Try Again')
Вы одновременно бросаете и ловите исключение в одном и том же простом блоке кода - это не совсем то, в чем заключается обработка исключений. Вы можете сделать это лучше, либо выйдя из цикла, либо сохранив условие. Например:
def isNumberCorrect(x):
return x in range(4)
def Release():
num = None # incorrect
while not isNumberCorrect(num):
print 'Please select one of the following?\nCompletion = 0\nRelease ID = 1\nVersion ID = 2\nBuild ID = 3\n'
num_str = raw_input("Please select the type of release required: ")
try:
num = int(num_str)
except ValueError:
num = None
if not isNumberCorrect(num):
print 'Incorrect!'
# work with num here; it's guaranteed to be correct.
if __name__ == '__main__':
try:
Release()
except:
print 'Error!'
EDIT: Добавлена проверка ошибок при разборе int.
def Release():
while 1:
print """Please select one of the following?
Completion = 0
Release ID = 1
Version ID = 2
Build ID = 3
Exit = 4 """
try:
a = int(raw_input("Please select the type of release required: "))
except Exception,e:
print e
else:
if a==4: return 0
files(a)
Вместо использования исключений вы можете сделать что-то вроде этого:
...
a = raw_input("Please select the type of release required:")
while a not in ['0','1','2','3']: a = raw_input("Try again: ")
files(int(a))
...
Современные исключения Python - это классы; используя поднять 'неверный'
, вы используете устаревшую языковую функцию, называемую исключениями строк. Раздел Ошибки и исключения учебного курса Python был бы хорошим местом для начала с базовой обработки исключений в Python.
В общем, исключения в любом случае не идеальны для вашей ситуации - простого цикла while
должно быть достаточно. Исключения должны быть зарезервированы для исключительных ситуаций, и неправильный ввод пользователя не является исключением, это ожидаемо.
Версия выпуска
на основе цикла будет выглядеть примерно так:
def Release():
a = None
while a not in (0, 1, 2, 3):
print 'Please select one of the following?\nCompletion = 0\nRelease ID = 1\nVersion ID = 2\nBuild ID = 3\n'
try:
a = int(input("Please select the type of release required: "))
except ValueError:
pass # Could happen in face of bad user input
files(a)
P.S. a
- неправильное имя переменной; вам, вероятно, следует изменить его на selected_option
или что-то в этом роде.