how to go back to a specific line of the code?

2

Hi, I'm working on the following menu, in which when option 1 is chosen and the patient identifier that is entered is> 3500, that error will be printed on the screen and a new identifier will be requested again

I tried to do it with label and goto but I think that python has not implemented it and I do not know how to do something similar so that it is asked to enter a new identifier until it is correct

while True:
        print('1)Datos del paciente')
        print('2)Resumen de variable')
        print('3)Volver')

        opc=input('Elija una opción: ')
        if opc=='1':

            identificador_paciente=int(input('Introduzca un identificador de paciente: '))
            if 1<=identificador_paciente<=3500:
                print ('hola')

            else:
                print('Lo siento, el identificador de paciente introducido no es válido')
    
asked by roberto 06.01.2018 в 11:33
source

1 answer

2

The use goto in the vast majority of cases is considered a bad practice in the languages that support it as C. It is an instruction of the first programming languages that from the appearance of structured programming happened to be considered "evil" in general. The main cause is that the minimum that the program is something extensive makes it very difficult to follow the flow of this and being easy to end with inconsistent codes, complicated to maintain and very little readable.

Python as a high-level language that advocates the legibility of the code as a foundation does not implement the goto instruction as is logical. Combining for / while , conditional, try / except and functions can achieve at least the same with a code much more readable and easy to maintain. You can use another cycle while :

while True:
    print('1)Datos del paciente')
    print('2)Resumen de variable')
    print('3)Volver')

    opc = input('Elija una opción: ')
    if opc == '1':
        identificador_paciente = int(input('Introduzca un identificador de paciente: '))
        while not 1 <= identificador_paciente <= 3500:
            print('Lo siento, el identificador de paciente introducido no es válido')
            identificador_paciente = int(input("Introduzca un identificador de paciente válido: "))
        print("Hola")

Or using break :

while True:
    print('1)Datos del paciente')
    print('2)Resumen de variable')
    print('3)Volver')

    opc = input('Elija una opción: ')
    if opc == '1':
        while True:
            identificador_paciente = int(input('Introduzca un identificador de paciente: '))
            if 1 <= identificador_paciente <= 3500:
                print('hola')
                break
            else:
                print('Lo siento, el identificador de paciente introducido no es válido')
    
answered by 06.01.2018 / 12:46
source