pythonpython-3.xloopswhile-loop

Getting stuck in Python while loop


One of my python loops is working perfectly while the other one is completely broken:

omonth = int(input('Digite o mês do seu nascimento: '))
while True:
    if int(omonth) not in (1,12):
        omonth = int(input('Digite o mês do seu nascimento: '))
    else:
        break

oday = int(input('Digite o dia do seu nascimento: '))
while True:
    if int(oday) not in (1,31):
        day = int(input('Digite o mês do seu nascimento: '))
    else:
        break        

I'm trying to use a while loop to keep asking for an input when incorrect information is typed, and the first loop (omonth) is working perfectly, however the second loop (oday) repeats the input no matter what I type and never breaks.


Solution

  • Hello from a fellow brazilian!

    That's happening because on this part of the code

    while True:
    if int(oday) not in (1,31):
        day = int(input('Digite o mês do seu nascimento: '))
    

    You're attributing a value to the variable day instead of oday inside your if conditional.

    But besides that, your code has a bunch of flaws and will not work correctly.

    First of all, this condition

    if int(omonth) not in (1,12):
    

    checks if omonth is equal to 1 or 12, not if it's in between them. The same logic applies to the oday loop.

    Second, the int function in int(omonth) is redundant since you're already using int(input())

    A better (and correct) implementation of your code would be:

    omonth = int(input('Digite o mês do seu nascimento: '))
    while True:
        if not (1 <= omonth <= 12):
            omonth = int(input('Digite o mês do seu nascimento: '))
        else:
            break
    
    oday = int(input('Digite o dia do seu nascimento: '))
    while True:
        if not (1 <= oday <= 31):
            oday = int(input('Digite o mês do seu nascimento: '))
        else:
            break