Getting stuck in Python while loop

73 Views Asked by At

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.

3

There are 3 best solutions below

2
narguis On BEST ANSWER

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      
0
0verflowme On

In the second loop, the line day = int(input('Digite o mês do seu nascimento: ')) contains an error. The variable day is being assigned the value of the user's input, but it should be oday instead.

0
CiaPan On

To add to previous answers, you may also use a while loop to avoid doubling the input statement (DRY rule). It would also prevent the typo you just made. ;-)
Additionally, it saves you the else break part.

This, however, requires initializing the destination variable with a value outside the desired range, so that the loop's body is executed at least once:

# initialize with an invalid value to make sure the condition is not satisfied
omonth = 0

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