Difference between revisions of "Calculate days in a month"

From CompSciWiki
Jump to: navigation, search
Line 29: Line 29:
 
{{CodeBlock
 
{{CodeBlock
 
|Code=#############################################################
 
|Code=#############################################################
#This program is used to disply th number of day in a month
+
#This program is used to display the number of days in a month
  
 
## Get input from the user
 
## Get input from the user

Revision as of 22:37, 3 April 2012

COMP 1010 Home > Back to Extra Labs

Introduction

In this program, you will be taught how to use if, elseif and else conditional statements in Python.

if/else/elseif syntax in Python:

if (expression):

  Statement(s)

elif (expression):

  Statement(s)

else:

  Statement(s)

As you may have noticed, Python uses elif in place of elseif in Java. Also, Python is a little picky about indentation; hence it is recommended that you use the if, elif and else syntax as shown above.

Problem:

Write a Python program that displays the days in a month.

Step 1: Get input(s) needed to solve the problem.

You will need the following in order to solve this problem.

  • input - Used to get input from the user.
  • month - The month to be used for the computation

    Step 2: Write the program.

     #############################################################
    #This program is used to display the number of days in a month
    
    ## Get input from the user
    month = input("Please enter a month in number format (1-12):  ")
    		
    #Display the appropriate number of days contained in the selected months
    #If the month is invalid, display appropriate message
    if(month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 8 or month == 10 or month == 12):
        print "This month has 31 days."
    elif( month == 4 or  month == 6 or month == 9 or month == 11 ):  #Months that have 30 days
        print "This month has 30 days."
    elif( month == 2 ):  #February has 28 days
        print "This month has 28 days."
    else:               #Not a valid month
        print "Invalid Month." 

    Step 4: Contrast with Days in a month program in Program a Day

    This Python program performs exactly the same function as the Java WindChill program in Program a Day.

  • What this program does: Given a month ie., a number in the range (1 - 12), it prints out the number of days contained in that month. If the month is not in the valid range, it also prints out an appropriate message to the user indicating that the month is invalid.