Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need help ending a while loop

So I’m having a problem where I can’t figure out how to end a specific while loop.

one = [1, 3, 5, 7, 8, 10, 12]
thirty = [4, 6, 9, 11]

while True:
    try:
        month = int(input("Enter the number of the month: "))
    except month == "":
        print("Program ending")
        break
    except ValueError:
        print("Please enter a number")
        continue
    else:
        def days(month): 
            if month in one:
                return 31
            elif month in thirty:
                return 30
            elif month == 2:
                return 28
        
    if days(month) == None:
            print("The number has to be between 1-12")
    else:
        print("This month has", days(month) ,"days.")

So the program is supposed to tell you how many days are in the specified month and pretty much what I want to achieve is that the loop goes on and asks the question again until the user leaves a blank input (presses enter). I have searched google for quite some time but just can’t seem to find the solution for my exact problem. I found out that you can’t take the value of something in except: if the value was given in try:, which is the case in the code at the moment.
Thanks in advance 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A few little mistakes

As Chris said defining a function inside a while loop is of no use
so define the function above you while loop

Secondly you shouldnt try to convert your input to an int before chehing if its ” so you wont get a ValueError

Here is the code fixed

one = [1, 3, 5, 7, 8, 10, 12]
thirty = [4, 6, 9, 11]

def days(month):
    if month in one:
        return 31
    elif month in thirty:
        return 30
    elif month == 2:
        return 28


while True:
    month = input("Enter the number of the month: ")
    if month == '':
        break
    else:
        try:
            month = int(month)
        except ValueError:
            print("Please enter a number")
            continue

    if days(month) == None:
        print("The number has to be between 1-12")
    else:
        print("This month has", days(month), "days.")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading