Formatting, not printing incorrect format? - python

Hey I'm having an issue getting the last bit of my code to run.
I am unable to get the values at the end and believe it may have to do with my formatting, although I'm not entirely sure. Instead of stabbing in the dark I thought I'd ask around here as the fastest way to improve is with help from the more experienced.
I'm new, and not seasoned. Haven't been programming for a full 2 months yet.
import math
def month():
month = input(' # of month born ')
if month == '1':
print ("January")
return "January"
elif month == '2':
print ("February")
return "February"
elif month == '3':
print ("March")
return "March"
elif month == '4':
print ("April")
return "April"
elif month == '5':
print ("May")
return "May"
elif month == '6':
print("June")
return ("June")
elif month == '7':
print ("July")
return "July"
elif month == '8':
print("August")
return "August"
elif month == '9':
print("september")
return "September"
elif month == '10':
print("October")
return "October"
elif month == '11':
print ("November")
return "November"
elif month == '12':
return "December"
print ("December")
else:
return month()
month()
print('day born')
day=input(' input day # ')
print ('{}'.format (day))
if month==1 and day<20:
print ('Capricorn')
elif month ==1 and day>22:
print ('aquarius')
It does everything fine except return aquarious or capricorn.
How may I format it correctly so it prints these values?

You run the function month(), right after the definition of it, but you do not store the return value. You should do this:
m = month()
if m == "October":
# ...
But instead, you're comparing the function month to 1, which will result to False.
def month(): pass # month is a function
month == 1 # is month equal to 1? no! this is False
Also, the function month actually returns string by your design, so you should not compare it to 1, but to "January", for example. Also, there's a very handy builtin package for this, you can use datetime here, see https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior.
In [3]: import datetime
In [4]: datetime.datetime(2000, 1, 1).strftime('%B')
Out[4]: 'January'
In [5]: datetime.datetime(2000, 12, 1).strftime('%B')
Out[5]: 'December'
So in a function:
def convert_number_to_month_name(i):
return datetime.datetime(2000, i, 1).strftime('%B')

Related

Using both OR, AND in an IF-statement - Python

def alarm_clock(day, vacation):
if day == 0 or day == 6 and vacation != True:
return "10.00"
else:
return "off"
print(alarm_clock(0, True))
Why does this return "10.00"? In my mind it should return "off". Yes, day is equal to 0, but vacation is True, and the IF-statements first line states that it should only be executed if vacation is not True.
In Python and binds tighter than or. So your statement is equivalent to this:
if day == 0 or (day == 6 and vacation != True):
To get the correct result you must parenthesize the precedence yourself:
if (day == 0 or day == 6) and vacation != True:
What you probably want is this:
def alarm_clock(day, vacation):
if (day == 0 or day == 6) and vacation != True:
return "10.00"
else:
return "off"
print(alarm_clock(0, True))

Need assistance solving this issue in a function

I have an assignment in my computer science class and need help fixing a function but I have no clue what's wrong! The function is called 'days_left'. This function takes in three variables, Day, Month, and Year. It is supposed to output how many total days are left in that year. I have tried my best but cannot figure it out! Any help will be greatly appreciated. Here's the script:
def leap_year(year):
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
return True
else:
return False
else:
return True
else:
return False
def number_of_days(month, year):
days31 = [1, 3, 5, 7, 8, 10, 12]
days30 = [4, 6, 9, 11]
if month in days31:
return 31
elif month in days30:
return 30
else:
if not leap_year(year):
return 28
else:
return 29
def days_left(month, day, year):
days = 0
for i in range(1, month):
days += number_of_days(i, year)
days += day
for x in range(year):
if leap_year(year):
return 366 - days
else:
return 365 - days
if __name__ == '__main__':
print("Please enter a date: \n")
d = int(input("Day: "))
m = int(input("Month: "))
y = int(input("Year: "))
print("\nMenu:")
print("1) Calculate the number of days in the given month.")
print("2) Calculate the number of days left in the given year.")
selection = int(input())
if selection == 1:
print(number_of_days(m, y))
elif selection == 2:
print(days_left(d, m, y))
else:
print('')
def days_left(day, month, year):
It should be 'day, month' instead 'month, day' since you are calling function with days_left(d, m, y)

Program not working for tuesday but working for sunday

I am learning python using a book called How to think like a computer scientist. There they gave an exercise:
Write a function that helps answer questions like “‘Today is Wednesday.
I leave on holiday in 19 days time. What day will that be?”’
So the function must take a day name and a delta argument — the number of days
to add — and should return the resulting day name:
test(day_add("Monday", 4) == "Friday")
test(day_add("Tuesday", 0) == "Tuesday")
test(day_add("Tuesday", 14) == "Tuesday")
test(day_add("Sunday", 100) == "Tuesday")
Hint: use the first two functions written above to help you write this one
Can your day_add function already work with negative deltas? For example, -1 would be yesterday, or -7 would be a week ago:
test(day_add("Sunday", -1) == "Saturday")
test(day_add("Sunday", -7) == "Sunday")
test(day_add("Tuesday", -100) == "Sunday")
I have written this program
import sys
def test(did_pass):
'''prints result of test at last'''
linenum=sys._getframe(1).f_lineno #gets call line
if did_pass:
msg='Test at line {0} PASS'.format(linenum)
else:
msg=('Test at line {0} FAIL.'.format(linenum))
print(msg)
def day_name(x):
'''converts day number to day'''
if x==0:
return 'Sunday'
elif x==1:
return 'Monday'
elif x==2:
return 'Tuesday'
elif x==3:
return 'Wednesday'
elif x==4:
return 'Thursday'
elif x==5:
return 'Friday'
elif x==6:
return 'Saturday'
else:
return
def day_num(y):
'''converts day to day number'''
if y=='Sunday':
return 0
elif y=='Monday':
return 1
elif y=='Tuesday':
return 2
elif y=='Wednesday':
return 3
elif y=='Thursday':
return 4
elif y=='Friday':
return 5
elif y=='Saturday':
return 6
else:
return
def day_add(today, stay):
'''input day name and remaining days to print day name'''
result=(stay)%7
answer=(result)+(day_num(today))
return day_name(answer)
def test_suite():
test(day_add("Sunday", -1) == "Saturday")
test(day_add("Sunday", -7) == "Sunday")
test(day_add("Tuesday", -100) == "Sunday")
test_suite()
so the first function is to test my program for bugs. The problem is first two tests are clear but last test fails even if it has the same negative value as the first two. I want to know what is the mistake which makes the first two tests pass but later fail. Im beginner so kindly use some easy statements.
Your calculations are wrong. Following How to debug small programs Change your code to
def day_add(today, stay):
'''input day name and remaining days to print day name'''
result = stay % 7
answer = result + day_num(today)
print(result, day_num(today), day_name(answer)) # DEBUG your code
return day_name(answer)
Output:
6 0 Saturday
Test at line 34 PASS
0 0 Sunday
Test at line 35 PASS
5 2 None # analyze this and fix it.
Test at line 36 FAIL.

Printing the number of days in a given month and year [Python]

I've been trying to work out a way to accomplish what's in the title, without using any imported calendar/datetime libs from Python. There's little function at the top for checking whether or not the year is a leap year, which I want to be able to reference when printing the number of days in a given February, however I'm not too sure how to do so. (I've guessed with something like output. bla bla)
So far I've come up with something like this, which should make clear what I want to do, but I'm still a bit new to Python, so I would love a few tips/help on fixing up my code for the task.
# A function to determine if a year is a leap year.
# Do not change this function.
def is_leap_year (year):
return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)
# You should complete the definition of this function:
def days_in_month(month, year):
if month == 'September' or month == 'April' or month == 'June' or month == 'November'
print 30
elseif month == 'January' or month == 'March' or month == 'May' or month== 'July' or month == 'August' or month == 'October'\
or month== 'December'
print 31
elseif month == 'February' and output.is_leap_year = True
print 29
elseif month == 'February' and output.is_leap_year = False
print 28
else print 'Blank'
Ok I've fixed up my code, and it seems to output the correct data for every month but February:
# A function to determine if a year is a leap year.
# Do not change this function.
def is_leap_year (year):
return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)
# You should complete the definition of this function:
def days_in_month(month, year):
if month in ['September', 'April', 'June', 'November']:
print 30
elif month in ['January', 'March', 'May', 'July', 'August','October','December']:
print 31
elif month == 'February' and is_leap_year == True:
print 29
elif month == 'February' and is_leap_year == False:
print 28
Any hints to fix up outputting for February?
EDIT: Just needed to add the argument year when referencing the first function. Here is the 100% working code for future reference:
# A function to determine if a year is a leap year.
# Do not change this function.
def is_leap_year(year):
return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)
# You should complete the definition of this function:
def days_in_month(month, year):
if month in ['September', 'April', 'June', 'November']:
print 30
elif month in ['January', 'March', 'May', 'July', 'August','October','December']:
print 31
elif month == 'February' and is_leap_year(year) == True:
print 29
elif month == 'February' and is_leap_year(year) == False:
print 28
else:
return None
​
​
​
A more pythonic approach would be to define the mapping in a dictionary, then simply retrieve the values from the dictionary.
Try it out:
days_in_month_dict = {"January": 31, "February": 28,
"March": 31, "April": 30,
"May": 31, "June": 30,
"July": 31, "August": 31,
"September": 30, "October": 31,
"November": 30, "December": 31}
def is_leap_year(year):
return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)
def days_in_month(year, month):
if is_leap_year(year) and month == "February":
return 28
try:
#attempt to get value from dictionary
return days_in_month_dict[month]
except KeyError:
#key does not exist, so we caught the error
return None
Some syntax error in your code:
There should be no space before def days_in_month(month,year). Python use indentation to separate code blocks. This is the error you given in comment.
There is no elseif in python, it should be elif
output.is_leap_year = True, it should be is_leap_year(year) == True. The False part should be changed too.
after if statement and else there should be a :, like
if month == 'September' or month == 'April' or month == 'June' or month == 'November':
print 30
elif month == 'January' or month == 'March' or month == 'May' or month== 'July' or month == 'August' or month == 'October' or month== 'December':
print 31
elif month == 'February' and is_leap_year(year) == True:
print 29
elif month == 'February' and is_leap_year(year) == False:
print 28
else:
print 'Blank'
"""
Takes the year and month as input and returns the no. of days
"""
def is_leap_year (year):
return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)
def days_in_month(month, year):
if month == 'September' or month == 'April' or month == 'June' or month == 'November':
result=30
elif month == 'January' or month == 'March' or month == 'May' or month== 'July' or month == 'August' or month == 'October'or month== 'December':
result=31
elif month == 'February' and output.is_leap_year ==True:
result=29
elif month == 'February' and output.is_leap_year == False:
result=28
return result
print(is_leap_year(2016))
print(days_in_month('September',2016))
month = int (input ('month (1-12): '))
if month < 13:
if month == 2:
year = int (input ('year: '))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print ('29')
else:
print ('28')
else:
print ('29')
else:
print ('28')
elif month >= 8:
if month % 2 == 0:
print ('31')
else:
print ('30')
elif month % 2 == 0:
print ('30')
else:
print ('31')
else:
print ('Only 1-12 accepted')
month=input("month")
year=int(input("year"))
if year%4==0:
year=('leap year')
if month in ['September', 'April', 'June', 'November']:
print ("30")
elif month in ['January', 'March', 'May', 'July', 'August','October','December']:
print ("31")
elif month == 'February' and year == "leap year":
print ("29")
elif month == 'February' and year != "leap year":
print ("28")
else:
print("none")
*# Write a function that determines how many days there are in a particular month.
Your function will have two parameters: The month as an integer between 1 and 12,
and the year as a four digit integer.
Ensure that your function reports the correct number of days in February for leap years.*
def year():
a = int(input("insert your year"))
def month():
z = int(input("enter month 1-12 "))
if z==9 or z==4 or z ==6 or z==11:
return print(30)
elif z==1 or z==3 or z==5 or z==7 or z==10 or z==12:
return print(31)
elif z ==2 and a % 4==0:
return print("29 its a leap year")
elif z ==2 and a % 4==1:
return print(28)
month()
year()

Always get printed value of "None"

Alright so here is my code, I get the result I want but I keep getting the "None" value under it. How do I eliminate the "None" value?
n = input("What day of the week are you leaving?")
r = input("How many days will you be resting?")
def days(n):
if n == 0:
print "Sunday"
elif n == 1:
print "Monday"
elif n == 2:
print "Tuesday"
elif n == 3:
print "Wednesday"
elif n == 4:
print "Thrusday"
elif n == 5:
print "Friday"
elif n == 6:
print "Saturday"
elif n >= 7:
print days(n%7)
print days(n+r)
This should do the trick:
days = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"]
print days[(n+r) % 7]
days never returns anything, so it implicitly returns None. Change all of the print statements in days to return statements:
def days(n):
if n == 0:
return "Sunday"
elif n == 1:
return "Monday"
elif n == 2:
return "Tuesday"
elif n == 3:
return "Wednesday"
elif n == 4:
return "Thrusday"
elif n == 5:
return "Friday"
elif n == 6:
return "Saturday"
elif n >= 7:
return days(n % 7)
Change all the print statements in your days(n) function to return instead.
You print in function days and print result from function days.
Because of function days returns nothing it prints None.

Categories