Give a quiz 2 right answers - python

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]

Related

Find month number from user input using list

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))

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

Converting a month name to the corresponding number. (Python)

I am extremely new to coding and I'm currently working with this.
print("What month were you born?")
m = input()
print("What day were you born?")
d = input()
print("What year were you born?")
y = input()
print("Your birthday is " + m + "/" + d + "/" + y)
If I input January 1 2000 for my birthday I get January/1/2000 but the output I want is 1/1/2000. Any advice?
You need a way to map the month name to the number representing the month. This can be done with a list or dictionary. Below we have a list of months. The number representing that month is simply the index of the month in the list + 1:
print("What month were you born?")
m = input()
print("What day were you born?")
d = input()
print("What year were you born?")
y = input()
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
print("Your birthday is " + str(months.index(m)+1) + "/" + d + "/" + y)
You can build upon this and add code to make the input case-insensitive and catch exceptions if the user enters the wrong value.
print("What month were you born?")
m = input()
newm = 'lol'
if m == "January" or "january":
newm = '1'
if m == "February" or "february":
newm = '2'
#KEEP GOING TILL DECEMBER
print("What day were you born?")
d = input()
print("What year were you born?")
y = input()
print("Your birthday is " + newm + "/" + d + "/" + y)
The other comments here are suggesting things that aren't on your level of skill. I think this answers your question in a way that you can understand what is happening.
When you get better, there are better ways to go about doing this, such what the other comments have suggested. There are even better ways of doing this code lol such as ignoring case on January/january.

Why doesn't my else statement run? [python] [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 3 years ago.
cont = "y"
while cont == "y":
day = input("Enter today's day: ")
if day == "monday" or "Monday":
day = day.upper()
if day in my_class:
print ("You have ",my_class[day], " today")
elif day == "tuesday" or "Tuesday":
day = day.upper()
if day in my_class:
print ("You have ",my_class[day], " today")
elif day == "wednesday" or "Wednesday":
day = day.upper()
if day in my_class:
print ("You have ",my_class[day], " today")
elif day == "thursday" or "Thursday":
day = day.upper()
if day in my_class:
print ("You have ",my_class[day], " today")
elif day == "friday" or "Friday":
day = day.upper()
if day in my_class:
print ("You have ",my_class[day], " today")
else:
print ("Enter a valid day")
cont = input("Type y to continue: ")
I want it to print what the else says if an invalid date is put in but it skips over to printing "Type y to continue: "
The problem is with your use of the or operator:
if day == "monday" or "Monday":
Is translated as "is day == "monday" truthy, or is "Monday" truthy?" Since "Monday" is always truthy (since it is a non-empty string), you will always get this if block. Your ifs and elifs should look more like:
if day == "monday" or day == "Monday":
One way to shorten it would be:
if day in ["monday","Monday"]:
However, a cleaner way to do this same check would be:
if day.lower() == "monday":
This will make your check case insensitive. The rest of your elif statements should do the same.

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