I want to make a function what must have 2 loops:
- must check that at least 2 characters (letters) are inserted
- if the two characters are in the form that the variable must receive at the end, the variable receives the correct orthographic form.
Here is my code (but it throws me in infinite loop) [Please be indulgent im a begginer (: ] :
def sede(): while True: import re var_sede_0 = input("Sede : ") if re.match("([a-zA-Z]+.*?){2,}", var_sede_0): while True: if var_sede_0.lower() in 'torino (to)': var_sede_0 = 'Torino (TO)' break elif var_sede_0.lower() in 'reggio calabria (rc)': var_sede_0 = 'Reggio Calabria (RC)' break else: print("sbagliato") continue break else: print("formato sbagliato") continue return var_sede_0 var_sede = sede()
Advertisement
Answer
Your inner loop is the problem:
while True: if var_sede_0.lower() in 'torino (to)': var_sede_0 = 'Torino (TO)' break elif var_sede_0.lower() in 'reggio calabria (rc)': var_sede_0 = 'Reggio Calabria (RC)' break else: print("sbagliato") continue
Consider that nowhere in this loop do you take in new input, so var_sede_0
can never possibly change. Given that, if the first two predicates (if statements) evaluate to false, then you will be in an infinite loop printing out sbagliato
. You can probably simply remove the while True
(the inner one) and get to what you want.
It is key to note that break
and continue
really only affect the immediate while
context that they are in – they will not ‘speak to’ the outer while
loop.
You also probably do not want to be importing re
on every loop. Move import re
to the top of your file.