Leap Year Function (Python) [duplicate] - python

This question already has an answer here:
Why does the print function return None?
(1 answer)
Closed 4 months ago.
I know I'm missing something very simple, but I cannot for the life of me figure it out.
Here's what I have right now.
def days_in_feb(user_year):
if user_year % 100 == 0:
if user_year % 400 == 0:
user_year = print(f'{user_year} has 29 days in February.')
else:
user_year = print(f'{user_year} has 28 days in February.')
else:
if user_year % 4 == 0:
user_year = print(f'{user_year} has 29 days in February.')
else:
user_year = print(f'{user_year} has 28 days in February.')
return user_year
if __name__ == '__main__':
user_year = int(input())
print(f'{days_in_feb(user_year)}')
It will run fine once but then when it goes to take the next input, I get "days_in_feb() did not return a value. Your function may be missing a return statement." I think it has something to do with reassigning user_year to those print statements
in the function but without them I don't know what to return.

Instead of having the function print out your statments about the selected year, have it return a value and then print this value.
It is also okay to use longer function names and explain what the function does.
You might also consider the single responsibility principle (SRP) and instead of returning a string, return an int. This way you'll have a higher reusability for the function.
And I think it is a good idea to tell the user what you are asking for, so i updated the input.
For example:
def get_days_in_feb_for_year(user_year):
if user_year % 100 == 0:
if user_year % 400 == 0:
return 29
else:
return 28
else:
if user_year % 4 == 0:
return 29
else:
return 28
if __name__ == '__main__':
user_year = int(input('Please enter a year: '))
days_in_feb = get_days_in_feb_for_year(user_year)
print(f'{user_year} has {days_in_feb} days in February.')

Maybe of topic, but return what you really want from the function instead of creating side effect of printing from the function.
def days_in_feb(user_year):
if user_year % 100 == 0:
if user_year % 400 == 0:
return 29
else:
return 28
else:
if user_year % 4 == 0:
return 29
else:
return 28
if __name__ == '__main__':
user_year = int(input())
print(f'{user_year} has {days_in_feb(user_year)} days in Feburary.')

Related

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.

CS50 python Credit not working for AMEX, working fine with other cards

from cs50 import get_int, get_string
#Asking User For Credit Card Number
def main():
while True:
Credit_Card = str(get_int("Enter Credit Card Number: "))
if Credit_Card != "":
break
cardCheck(cardSum, Credit_Card)
def cardSum(Credit_Card):
even = 0
odd = 0
CC = len(Credit_Card)
if (CC == 0):
return 0
else:
if (CC % 2 == 0):
last = int(Credit_Card[-1])
even += last
return even + cardSum(Credit_Card[:-1])
else:
last = int(Credit_Card[-1])
last = last * 2
oddDigits = last // 10 + last % 10
odd += oddDigits
return odd + cardSum(Credit_Card[:-1])
#Checking is card valid or not
def cardCheck(cardSum,Credit_Card):
Total = cardSum(Credit_Card)
if (Total % 10 == 0):
if (len(Credit_Card) == 15) and (int(Credit_Card[0:2]) in [37, 34]):
print("AMEX")
elif (len(Credit_Card) == 16) and (int(Credit_Card[:2]) in range(50, 56)):
print("MASTER CARD")
elif (len(Credit_Card) in [13, 16]) and (int(Credit_Card[:1]) == 4):
print("VISA")
else:
print("INVALID")
else:
print("INVALID")
if __name__ == "__main__":
main()
I cannot figure it out Why my Program is not giving correct output with these AMEX Card Number:378282246310005 , 371449635398431 In My C implemented credits these two card are showing AMEX
but in python it showing INVALID as output
It's working Fine For Master,Visa
I believe the problem is your code is using an absolute sense of parity instead of a relative one. That is, we start doubling with the second to last digit on the right and then every other digit going left. But the parity of the indicies of the digits to double depends on whether the original number had an odd or even number of digits. Your code doesn't account for this.
We need to calculate the parity of the card at the start, and pass this parity throught the recursive cardSum() calls, so it doubles the correct digits:
def cardSum(digits, parity):
if not digits:
return 0
digit, digits = int(digits[-1]), digits[:-1]
if len(digits) % 2 == parity:
digit *= 2
digit = digit // 10 + digit % 10
return digit + cardSum(digits, parity)
def cardCheck(cardSum, credit_card):
checksum = cardSum(credit_card, len(credit_card) % 2)
if checksum % 10 == 0:
if len(credit_card) == 15 and int(credit_card[0:2]) in [34, 37]:
print("AMEX")
elif len(credit_card) == 16 and int(credit_card[:2]) in range(50, 56):
print("MASTER CARD")
elif len(credit_card) in [13, 16] and int(credit_card[:1]) == 4:
print("VISA")
else:
print("INVALID")
else:
print("INVALID")
if __name__ == "__main__":
credit_card = input("Enter Credit Card Number: ")
if credit_card != "":
cardCheck(cardSum, credit_card)
My guess is this comes up with AMEX because it is an odd length number -- did you test odd length numbers from any other card issuer?

Python: Recursion returning None value [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 5 years ago.
I am trying to write a program that finds happy numbers:
more info here.
This is not a school assignment, but I'm just trying to practice my Python 2.7.
Basically, recursion is a vital part of this because I have to keep squaring every digit.
In my code, I use recursion to keep running it, I have a base case, and it works, but for some reason, even though I call the function, no recursion occurs.
It just returns the digits squares for the first number, which is a bug test, and it returns None, then it stops running.
What's the problem?
num = raw_input('Pick a positive integer that you want to check for a happy number')
def happyn(number,second,third,fourth):
if len(number) == 2:
go = int(number[0])**2 + int(number[1])**2
elif len(number) == 3:
go = int(number[0])**2 + int(number[1])**2 + int(number[2])**2
elif len(number) == 4:
go = int(number[0])**2 + int(number[1])**2 + int(number[2])**2 + int(number[2]**2)
if len(number) == 1 and int(number) == 1 or int(number) == 7:
return True
elif len(number) == 1:
return False
else:
print go
go = str(go)
go1 = go[0]
print go1
if len(go) == 1:
go1 = go[0]
happyn(go1,0,0,0)
elif len(go) == 2:
go1 = go[0]
go2 = go[1]
happyn(go1,go2,0,0)
elif len(go) == 3:
go1 = go[0]
go2 = go[1]
go3 = go[2]
happyn(go1,go2,go3,0)
elif len(go) == 4:
go1 = go[0]
go2 = go[1]
go3 = go[2]
go4 = go[4]
happyn(go1,go2,go3,go4)
print happyn(num,0,0,0)
All the possible execution branches must return something, otherwise the recursion won't work. For example, this is wrong:
happyn(go1,0,0,0)
If nothing is explicitly returned, the function will return None. Therefore, the correct way is:
return happyn(go1,0,0,0)
The same goes for all the other exit points in your function.
You are not returning the result of your recursive calls, ie return happyn(go1, 0, 0, 0). In Python, any function that ends without a return statement implicitly returns None.
This is not really a good place to use recursion; a simple while loop would suit better.
def sum_sq(i):
total = 0
while i:
total += (i % 10) ** 2
i //= 10
return total
def is_happy(i):
while i >= 10:
i = sum_sq(i)
return i in (1, 7)
def main():
i = int(raw_input("Please enter a positive integer: "))
if is_happy(i):
print("{} is a happy number.".format(i))
else:
print("{} is an unhappy number.".format(i))
if __name__=="__main__":
main()

Python: Determining the Leap Year

I have to write a program where I enter a number and the program replies whether the number is a leap year or not. I'm new to python so I am unsure of where to start. So far, I know that a leap year is any number divisible by 4, but not by 100 (unless it is also divisible by 400).
Use the built-in calendar.isleap:
import calendar
calendar.isleap(2020)
#=> True
I am also a python beginner. I tried my best, see if this works.
def isLeap(year):
tyear = year
if tyear % 4 == 0:
tyear = year
if tyear % 100 == 0:
tyear = year
if tyear % 400 == 0:
print('Leap Year')
else:
print('Not a Leap Year')
else:
print('Leap Year')
else:
print('Not a Leap Year')
isLeap(2004) # Returns Leap Year
isLeap(2005) # Returns Not a Leap Year
Maybe this could help.
year = int(input("Input year: "))
if year % 4 == 0:
print("Year is leap.")
if year % 100 == 0 and year % 400 != 0:
print("Year is common.")
else:
print("Year is common.")
Most previous answers are correct here is another way to skin a cat:
The math logic is based on this full credit
year = 2024
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
elif year % 400 != 0:
return False
else:
return True
Here is test case
def checkit(year):
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
elif year % 400 != 0:
return False
else:
return True
x = range(2013,2027)
for n in x:
print(n,checkit(n))
This is how to do leap years :)
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print(year, "is leap!")
else:
print(year, "is not leap!")

Categories