Как выйти из цикла - PullRequest
       1

Как выйти из цикла

0 голосов
/ 16 ноября 2018

В настоящее время я выполняю свое задание. Требуется проверить формат студенческого билета. Интересно, почему мой цикл while не работает должным образом? Моя проверка правильности приведена ниже:

def isValidStudentIDFormat(stid):

# studentID must have a length of 9
if(len(stid) != 9):
    # return the invalid reason
    return "Length of Student ID is not 9"

# studentID must starts with a letter S
if(stid[0] != 'S'):
    # return the invalid reason
    return "First letter is not S"

# studentID must contains 7 numbers between the two letters
for i in range(1,8):
    # anything smaller than 0 or bigger than 9 would not be valid.
    # so does a character, will also be invalid
    if((stid[i] < '0') or (stid[i] > '9')):
        # return the invalid reason
        return "Not a number between letters"

if((stid[8] < 'A') or (stid[8] > 'Z')):
    # return the invalid reason
    return "Last letter not a characer"

# return True if the format is right
return True

Моя функция для вставки записи студента ниже:

def insert_student_record():
#printing the message to ask user to insert a new student into the memory
print("Insert a new student \n")
fn = input("Enter first name: ")

#check if user entered space
#strip() returns a copy of the string based on the string argument passed
while not fn.strip():      
    print("Empty input, please enter again")
    fn = input("Enter first name: ")  

ln = input("Enter last name: ")
while not ln.strip():      
    print("Empty input, please enter again")
    ln = input("Enter last name: ")   

stid = input("Enter student id: ")
while not stid.strip():      
    print("Empty input, please enter again")
    stid = input("Enter student id: ") 

result = isValidStudentIDFormat(stid) 
while (result != True):
    print("Invalid student id format. Please check and enter again.")
    stid = input("Enter student id: ")
    result == True

#append the student details to each list
#append first name
fName.append(fn)

#append last name
lName.append(ln)

#append student id
sid.append(stid)

#to check if the new student is in the lists
if stid in sid:
    if fn in fName:
        if ln in lName:
            #then print message to tell user the student record is inserted
            print("A new student record is inserted.")

Однако, я получаю бесконечный цикл, даже если я ввожу правильный формат для идентификатора студента. Кто-нибудь может помочь?

Ответы [ 2 ]

0 голосов
/ 16 ноября 2018

?

def validateStudentIDFormat(stid):
    if len(stid) != 9:
        raise RuntimeError("Length of Student ID is not 9")

    if stid[0] != 'S':
        raise RuntimeError("First letter is not S")

    for char in stid[1:-1]:
        if char.isnumeric(): 
            raise RuntimeError("Not a number between letters")

    if not stid[-1].isalpha():
        raise RuntimeError("Last letter not a characer")

....

while True:
    stid = input("Enter student id: ")
    try:
        validateStudentIDFormat(stid) 
    except RuntimeError as ex:
        print(ex)
        print("Invalid student id format. Please check and enter again.")
    else:
        break
0 голосов
/ 16 ноября 2018

Вы сравниваете result == True, когда вам нужно назначить. Тем не менее, вы не проверяете новый идентификатор студента на достоверность, что можно сделать следующим образом:

while (result != True):
    print("Invalid student id format. Please check and enter again.")
    stid = input("Enter student id: ")
    result = isValidStudentIDFormat(stid)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...