DEV Community

Pratik Kinage
Pratik Kinage

Posted on

Python Program to Get the Month Name When Number is Entered By User

Python Program to Get the Month Name When Number is Entered By User

Code:

while True:
    try:
        num = int(input("Enter month number : "))
        break
    except:
        print("Invalid input")

if num == 1:
    print("Month is January")
elif num == 2:
    print("Month is February")
elif num == 3:
    print("Month is March")
elif num == 4:
    print("Month is April")
elif num == 5:
    print("Month is May")
elif num == 6:
    print("Month is June")
elif num == 7:
    print("Month is July")
elif num == 8:
    print("Month is August")
elif num == 9:
    print("Month is September")
elif num == 10:
    print("Month is October")
elif num == 11:
    print("Month is November")
elif num == 12:
    print("Month is December")
else:
    print('Invalid number')
Enter fullscreen mode Exit fullscreen mode

Output:

Enter month number : 5
Month is May

Explanation:

In the above Program to Get the Month Name When Number is Entered By User Input. We have used the while loop. And to manage the exceptional handling we have used the try-except block.
try-except block is also used here because if the user entered something else rather than integer number it will print Invalid input.

In the try block, we are taking the input of type integer as the program is to Get the Month Name When Number is Entered By User.

After the end of the while loop, we will get a valid input. Then we further process the input with the conditional statements. The if-elif-else statements are the conditional statements in Python.

So First we check if the input is equal to 1. In Python to check the statement we use ‘==’. And to assign we use ‘=’.

If the user has inputted 1 then the output will be Month is January and the program will terminate. And if the inputted number is not 1 it will go to the second elif statement. The process will go on till the input integer matched with the conditional statement.

If none of the inputted integers matched it will return Invalid Number.

Top comments (0)