Find month number from user input using list - python

I am trying to write a program where the user enters the month number and it will display e.g. September has 30 days. The program must find a number of days from the list.
days = [31,28,31,30,31,30,31,31,30,31,30,31]
I have tried the following code so far and I know the days[counter] is taking 31,28,31... which can't match with user input. I also used for counter in range(len(days)) but couldn't get the possible solution.
def getValidMonth():
userInput = 0
while userInput < 1 or userInput > 12:
userInput = int(input("Please enter the valid number of month: "))
return userInput
def findDays(userInput):
days = [31,28,31,30,31,30,31,31,30,31,30,31]
for counter in range(1,13):
if days[counter] == userInput:
print("Jan has 31 days")
elif days[counter] == userInput:
print("Feb has 28 days")
elif days[counter] == userInput:
print("Mar has 31 days")
elif days[counter] == userInput:
print("April has 31 days")
elif days[counter] == userInput:
print("May has 31 days")
elif days[counter] == userInput:
print("June has 31 days")
elif days[counter] == userInput:
print("July has 31 days")
elif days[counter] == userInput:
print("August has 31 days")
elif days[counter] == userInput:
print("September has 30 days")
elif days[counter] == userInput:
print("October has 31 days")
elif days[counter] == userInput:
print("November has 30 days")
elif days[counter] == userInput:
print("December has 31 days")
def main():
userInput = getValidMonth()
findDays(userInput)
main()
I know there is a solution by importing datetime and calendar but I am trying to do with the list. Is there any way to do it?

Try:
def findDays(userInput):
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
days = [31,28,31,30,31,30,31,31,30,31,30,31]
return f"{months[userInput-1]} has {days[userInput-1]} days."
>>> findDays(4)
'Apr has 30 days.'
Explanation:
If the user enters "1", you are returning the element at the 0th (userInput-1) index

One possibility is using a dictionary:
MONTHS = {
1: ("Jan", 31),
2: ("Feb", 28),
...
}
and then using the user input:
def findDays(userInput):
print(f"{MONTHS[userInput][0]} has {MONTHS[userInput][1]} days.")
Usually using consecutive integers as dictionary keys gives us a hint to use an array, but this might require to manipulate the indices, and a dictionary doesn't need this kind of manipulation.

Here is the code which will work which handles the invalid input as well:
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
days = [31,28,31,30,31,30,31,31,30,31,30,31]
def find_days(month_no):
try:
if int(month_no) < 1 or int(month_no) > 12:
return "Month No. should be in the range 1 to 12"
return months[int(month_no)-1]+ " has " + str(days[int(month_no)-1])+" days"
except ValueError as ex:
return "Input should be integer number"
month = input()
print (find_days(month))

Related

Code only returns if statement, ignores everything else

I know this is simple but I can't get this code to work. No matter the order I put the variables or if/elif statements in, it only returns the if statement regardless of the month.
months = input("Enter a month to find out how many days are in that month, or enter 'exit' to quit the program\n")
months_28 = "February"
months_30 = "April", "June", "September", "November"
months_31 = "January", "March", "May", "July", "August", "October", "December"
if months or months.casefold() in months_28:
print("There are 28 days in", months.capitalize())
elif months or months.casefold() in months_30:
print("There are 30 days in", months.capitalize())
elif months or months.casefold() in months_31:
print("There are 31 days in", months.capitalize())
else:
print("That's not a month")
I also am trying to work a while loop into this too (as reflected in the beginning) and any help there would be greatly appreciated.
You can Fabricate your code even more, with
Python's one of the strongest data structures - Dictionaries
Exception handling usage instead of if-else
F-strings, to increase readability of code
These Changes not only optimises your code, but also reduces time and space complexity
I've recoded it for you --
months = input("Enter a month to find out how many days are in that month, or enter 'exit' to quit the program")
Month_Days = {
'February': 28,
'April': 30, 'June': 30, 'September': 30, 'November': 30,
'January': 31, 'March': 31, 'May': 31, 'July': 31, 'August': 31, 'October': 31, 'December': 31
}
try: print(f"There are {Month_Days[months.title()]} days in", months.capitalize())
except Exception: print("That's not a month")
With this, you not even have to add additional condition for exit, that'll be handled by try/except
Your months_* need to be lists.
months = input("Enter a month to find out how many days are in that month, or enter 'exit' to quit the program\n")
months_28 = ["february"]
months_30 = ["april", "june", "september", "november"]
months_31 = ["january", "march", "may", "july", "august", "october", "december"]
if months and months.casefold() in months_28:
print("There are 28 days in", months.capitalize())
elif months and months.casefold() in months_30:
print("There are 30 days in", months.capitalize())
elif months and months.casefold() in months_31:
print("There are 31 days in", months.capitalize())
else:
print("That's not a month")
Just using your code with the minor changes. There are obviously different ways of printing what you want out.
Few mistakes in your code:
months_28 is just a string. To convert that to a tuple add a , at the end
Instead of using casefold(), I suggest using title() as the months names start with a Capital letter
You must use and and not or in the if conditions because you want both the conditions to be True.
Below code will do what you require.
months = input("Enter a month to find out how many days are in that month, or enter 'exit' to quit the program\n")
months_28 = "February",
months_30 = "April", "June", "September", "November"
months_31 = "January", "March", "May", "July", "August", "October", "December"
if months and months.title() in months_28:
print("There are 28 days in", months.capitalize())
elif months and months.title() in months_30:
print("There are 30 days in", months.capitalize())
elif months and months.title() in months_31:
print("There are 31 days in", months.capitalize())
else:
print("That's not a month")
This fixes your problem and adds the loop you need.
months_28 = ["February"]
months_30 = ["April", "June", "September", "November"]
months_31 = ["January", "March", "May", "July", "August", "October", "December"]
another = True
while another:
choice = input("[1] Enter a month to find out how many days are in that month\n[2] Enter 'exit' to quit\n")
while True:
if choice == '1':
month = input("Enter month: ").capitalize().strip()
if month in months_28:
print("There are 28 days in", month)
elif month in months_30:
print("There are 30 days in", month)
elif month in months_31:
print("There are 31 days in", month)
else:
print("Invalid entry.")
elif choice == '2':
print('Buh bye!')
break
another = input("Try another month? Y/N: ").capitalize().strip()
if another == 'Y':
anpther = True
elif another == 'N':
print("Good bye!")
break
break

"NameError: name 'day_time' is not defined" error in Python3.8 [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I am making a program which tells the part of the day by the time entered.
My code:
user_day = input("What's the time? ")
if user_day >= 20 and user_day <= 24:
day_time = "Night"
elif user_day >= 24 and user_day <= 12:
day_time = "Morning"
elif user_day >= 12 and user_day >= 17:
day_time = "Noon"
elif user_day >= 17 and user_day >= 20:
day_time = "Evening"
But I am getting this error:
if day_time == 1 and user_weather == plus:
NameError: name 'day_time' is not defined
Please help me out.
You need to declare day_time outside the context of if blocks if you wish to use it later on.
Like so, for example:
user_day = input("What's the time? ")
day_time = None
if user_day >= 20 and user_day <= 24:
day_time = "Night"
elif user_day >= 24 and user_day <= 12:
day_time = "Morning"
elif user_day >= 12 and user_day >= 17:
day_time = "Noon"
elif user_day >= 17 and user_day >= 20:
day_time = "Evening"
The issue is, user_day is a string when entered as an input.
Because it's a string, it doesn't meet any of the conditions, and therefore, day_time remains undefined.
Wrap the input in a try-except block to check that the input is a proper data type. In this case, str type that can be converted to an int or float.
It must be converted to a int or float depending on if you're going to accept only hours or fractional hours.
user_day should be in a while True loop to continue asking for a time until a valid numeric input is received.
Finally, the code can be written more efficiently, by properly ordering the conditions from smallest to largest, for this case.
user_day will trickle down to the correct condition.
while True:
try:
user_day = int(input("What's the hour on a 24-hour scale? "))
except ValueError: # checks for the correct data type; maybe someone will spell the hour
print('Please enter the hour as a numeric value')
if (user_day >= 24) or (user_day < 0): # 24 and over or less than 0 are invalid times
print('Please enter a valid time')
else:
break # break when there's valid input
if user_day < 12:
day_time = 'Morning'
elif user_day < 17:
day_time = 'Noon'
elif user_day < 20:
day_time = 'Evening'
else:
day_time = 'Night'
print(day_time)
Use np.digitize
Return the indices of the bins to which each input value belongs.
Use the value returned by np.digitize to index the correct value from day_time
import numpy as np
while True:
try:
user_day = int(input("What's the hour on a 24-hour scale? "))
except ValueError: # checks for the correct data type; maybe someone will spell the hour
print('Please enter the hour as a numeric value')
if (user_day >= 24) or (user_day < 0): # 24 and over or less than 0 are invalid times
print('Please enter a valid time')
else:
break # break when there's valid input
day_time = ['Morning', 'Evening', 'Noon', 'Night']
idx = np.digitize(user_day, bins=[12, 17, 20])
print(day_time[idx])
You need to define day_time in an else statement so that when neither of the existing conditions meet, day_time will still have a value.
Also, you need to convert the user's input into an integer before you can use the <, >, etc operator on it with a string:
user_day = int(input("What's the time? "))
if user_day >= 20 and user_day <= 24:
day_time = "Night"
elif user_day >= 24 and user_day <= 12:
day_time = "Morning"
elif user_day >= 12 and user_day >= 17:
day_time = "Noon"
elif user_day >= 17 and user_day >= 20:
day_time = "Evening"
else:
day_time = "Unknown"

How would I make this code run completely without error so that age is assigned correctly according to the date they enter?

from random import randint
def main():
dob = int(input("Please enter the year you were born"))
if dob > (2005):
main()
elif dob < (2004):
main()
else:
def mob():
if dob == (2004):
month = input("Please enter the first three letters of the month you were born")
if month == ("Jan","JAN","jan","Feb","FEB","feb","Mar","MAR","mar","Apr","APR","apr","May","MAY","may","Jun","JUN","jun","Jul","JUL","jul"):
age = 12
elif month == ("Aug","AUG","aug"):
day = int(input("Please input the day you were born"))
if day < 28:
age = 12
elif day == ("29","30","31"):
age = 11
else:
age = 12
else:
age = 11
if dob == (2005):
age = 11
mob()
main()
If I were to enter 2004 and then 'aug', it would not ask the day of birth.The code would stop. I also want the code to run so that if I were to enter 2005, it would assign age to 11
Something like this does what you need, I think, though you could tidy it further to give the actual age, by using datetime.
def main():
yob = int(input("Please enter the year you were born"))
if yob > 2005:
return "Under 11"
elif yob < 2004:
return "Over 12"
elif yob == 2004:
return 12
else:
mob = input("Enter a three letter abbreviation for your month of birth: "
if mob.lower() in ("jan", "feb", "mar", "apr", "may", "jun", "jul"):
return 12
elif mob.lower() == "aug":
dob = int(input("Enter your day of birth"))
if dob < 28:
return 12
elif dob > 28:
return 11
else:
return 11
age = main()
Better alternative, covers most eventualities I think
from datetime import datetime
def give_age():
today = datetime.today()
dob = input("Enter your date of birth (DD/MM/YYYY): ")
try:
dob_datetime = datetime.strptime(dob, "%d/%m/%Y")
age = (today - dob_datetime).days / 365
return age
except ValueError:
print("Your date of birth was not in the required format")
give_age()
age = give_age()

Give a quiz 2 right answers

For the month of February I am trying to make it so it has 3 correct answers for the number of days in the month 28,29 29 28 but it doesn't seem to be working when I try to change
user = int(input(""))
if month == "January":
answer = 31
elif month == "Feburary":
answer = 28
to
user = int(input(""))
if month == "January":
answer = 31
elif month == "Feburary (use comma to seperate two numbers)":
answer = 28,29 or 28 or 29
I realise that there is a problem with using integer in the input but I am not sure how to fix that with the comma and it won't let me put a space in between the 28 and 29 .
This is the rest of the code:
import random
import shelve
from tkinter import *
result = []
highscore = []
root = Tk()
highscore = 0
correct = 0
d = shelve.open('highscore.txt')
d['highscore'] = highscore
d.close()
name = input("What is your name: ")
print ("Hello there",name,"!")
for count in range(12):
month = random.choice(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"])
while month in result:
month = random.choice(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"])
result.append(month)
print ("How many Days in?", month)
user = int(input(""))
if month == "January":
answer = 31
elif month == "February":
answer = 28,29 or 29 or 28
elif month == "March":
answer = 31
elif month == "April":
answer = 30
elif month == "May":
answer = 31
elif month == "June":
answer = 30
elif month == "July":
answer = 31
elif month == "August":
answer = 31
elif month == "September":
answer = 30
elif month == "October":
answer = 31
elif month == "November":
answer = 30
elif month == "December":
answer = 31
if user == answer:
print("Correct!")
correct = correct + 1
else:
print ("Wrong, the correct answer was", answer)
if correct > highscore:
highscore = correct
print (name,", You Beat The Highscore and got",highscore,"Out Of 12")
photo = PhotoImage(file='/Users/HoneyCentaur/Desktop/Approval.gif')
photo_label = Label(image=photo)
photo_label.grid()
photo_label.image = photo
text = Label(text=" ")
text.grid()
root.deiconify()
root.mainloop()
else:
print (name, ", You Got", correct, "Out Of 12")
d = shelve.open('highscore.txt')
d['highscore'] = highscore
d.close()
You will likely want to use a list to check if the user answer was in the list of possible answers for the number of days in a month. you can then use the in keyword in python check if user is in the possible answers list.
The code would look a bit like the following:
if month == "Janurary":
answer=[31]
elif month == "Feburary":
answer=[28,29]
if user in answer:
print("Correct!")
correct = correct + 1
EDIT #1
Keep in mind there are many other options for going at this. To have a single element in a list kind of defeats the purpose and hinders understandability.
A better option might be to just cast the users answer from 28 to 29 or vice-a-versa if you're just using it to count points:
if month == "Janurary":
answer=31
elif month == "Feburary":
if(user == 28):
user = 29
answer=29
if user in answer:
print("Correct!")
correct = correct + 1
I believe "or" is only used for boolean or comparison operations.
i.e.
if month == "Janurary" or month == "Feburary":
do_something
if the quiz is looking for the possible "last days" of a month, I'm assuming the function would want a list of options.
if month == "Janurary":
answer=[31]
elif month == "Feburary":
answer=[28,29]

Calendar program help (string variables)

I recently signed up on this site because I am really stuck on the assignment in which I am required to create a program where the user inputs a month and the program displays how many days there are in that month. The user must also input the year so the program can check if it is a leap year in case the user inputs the month of february.
This is the coding I've come up with so far:
def get_year():
year = raw_input("Please enter the year: ")
return year
def get_month():
month = raw_input("Please enter the month: ")
return month
def leap_year(year):
if year % 4 == 0:
return true
else:
return false
def get_days(month):
if month == "january":
print "31 days"
elif month == "february" and leap_year == true:
print "29 days"
else:
print "28 days"
if month == "march":
print "31 days"
elif month == "april":
print "30 days"
elif month == "may":
print "31 days"
elif month == "june":
print "30 days"
elif month == "july":
print "31 days"
elif month == "august":
print "31 days"
elif month == "september":
print "30 days"
elif month == "october":
print "31 days"
elif month == "november":
print "30 days"
elif month == "december":
print "31 days"
else:
print
def main():
user_year = get_year()
user_month = get_month()
leap_year(user_year)
get_days(user_month)
main()
Anyways it's clear that there is an error in my get_days function its just I'm not sure
how to write the code so that the program knows that the user inputs a month such as
january or march. I'm guessing that the input has to be a variable and that since each
month is a string, a variable string is needed. But I could be completely wrong about this.
I'm very new to python (exactly 2 weeks now of off and on programming for school work) so I'm not too sure on many of the specifics of python programming so if anybody could assist me in the proper direction, it would be much appreciated!
You were kinda close. I made some changes which I commented. And as Raymond Hettinger points out, your get_days(month) is completely broken.
def get_year():
year = raw_input("Please enter the year: ")
return int(year) #otherwise it is a string!
def get_month():
month = raw_input("Please enter the month: ")
return month
def leap_year(year):
if year % 4 == 0:
return True
else:
return False
def get_days(month,leap_year): #leap_year must be passes to this function
#This checks for "january" and "february" with leap years
#and falls back to last option on EVERYTHING ELSE like a feb without a leap year or even a "march"
if month == "january":
print "31 days"
elif month == "february" and leap_year == True:
print "29 days"
else:
print "28 days"
#this is a separate block that runs AFTER the previous block
if month == "march":
print "31 days"
elif month == "april":
print "30 days"
elif month == "may":
print "31 days"
elif month == "june":
print "30 days"
elif month == "july":
print "31 days"
elif month == "august":
print "31 days"
elif month == "september":
print "30 days"
elif month == "october":
print "31 days"
elif month == "november":
print "30 days"
elif month == "december":
print "31 days"
else:
print "invalid input" #so that it doesnt fail silently when I enter 2
def main():
user_year = get_year()
user_month = get_month()
leap_status = leap_year(user_year) #store the leap_year status to a variable
get_days(user_month, leap_status) #and then pass it to a function
main()
The if-elif was being broken in February. The minor change is to continue with an uninterrupted pattern of if-elif logic:
def get_days(month):
if month == "january":
print "31 days"
elif month == "february" and leap_year:
print "29 days"
elif month == "february" and not leap_year:
print "28 days"
elif month == "march":
print "31 days"
elif month == "april":
print "30 days"
elif month == "may":
print "31 days"
elif month == "june":
print "30 days"
elif month == "july":
print "31 days"
elif month == "august":
print "31 days"
elif month == "september":
print "30 days"
elif month == "october":
print "31 days"
elif month == "november":
print "30 days"
elif month == "december":
print "31 days"
else:
print 'unknown month'
I would suggest you to using dictionary which a build-in data type in python.
def get_days(year, month):
"""
take year and month ,return the days in that month.
"""
#define a dictionary and the month is key which value is days
daydict = dict()
daydict = ['january'=31, 'february'=28, 'februaryinleapyear'=29,
'march'=31, 'april'=30,
'may'=31, 'june'=30,
'july'=31, 'august'=31,
'september'=30, 'october'=31,
'november'=30, 'december'=31 ]
try:
if month in daydict:
if month == 'february' and leap_year(year):
print daydict[februaryinleapyear]
else:
print daydict[month]
else:
print 'The year or month you input is invalid !'
except:
print 'error!'
n=int(input('enter no of days in a month= '))
#0=sunday
#1=moday
#2=tuesday
#3=wednesday
#4=thursday
#5=friday
#6=saturday
d=int(input('enter the starting day of month= '))
print('sun','mon','tue','wed','thu','fri','sat',sep='\t')
for j in range(d):
print (' ',end='\t')
i=1
while(i<=n):
print (i,end='\t')
if(i+d)%7==0:
print('\t')
i=i+1
This code ask for user inputs( more simple codes)
#python calendar days in month.
month= input ("Enter the month('January', ...,'December'): ") # ask for inputs from user
start=input ("Enter the start day ('Monday', ..., 'Sunday'): ")
if start== "Monday" :
num=1
elif start== "Tuesday" :
num=0
elif start== "Wednesday" :
num=-1
elif start== "Thursday" :
num=-2
elif start== "Friday" :
num=-3
elif start== "Sartday" :
num=-4
elif start=="Sunday":
num=-5
print(month)
print("Mo Tu We Th Fr Sa Su") #the header of the Calender
if month== "January" or month=="March" or month=="May" or month=="July" or month=="August" or month=="October" or month=="December" :
#for month with 31 days
for num_ in range (num,num+41,7):
for i in range(7):
if num<1:
print (' ',end="")
elif num>31:
print("",end="")
else:
print ("{0:>2}".format(num),end="")
if i<6 and num<31:
print(" ",end="")
num +=1
print()
elif month== "April" or month=="June" or month=="Septemmber" or month=="November":
#for month with 30 days
for num_ in range (num,num+41,7):
for i in range(7):
if num<1:
print (' ',end="")
elif num>30:
print("",end="")
else:
print ("{0:>2}".format(num),end="")
if i<6 and num<30:
print(" ",end="")
num +=1
print()
elif month== "February" :
# february is an exception : it has 28 days
for num_ in range (num,num+41,7):
for i in range(7):
if num<1:
print (' ',end="")
elif num>28:
print("",end="")
else:
print ("{0:>2}".format(num),end="")
if i<6 and num<28:
print(" ",end="")
num +=1
print()
else:
print("invalid entry")

Categories

Resources