code does not want to print when i run it - python

def leap():
year = int(input("enter a number: "))
if year == range(300,2000):
print(year/400)
elif year == range(2001,2024):
print(year/4)
leap()
so I am trying to create a function that calculates if the year is a leap year, but it seems it does not want to show the answer of the leap year. there is no error message when I run the code,
also, I am doing this in visual studio code.

The object returned by range(300, 2000) has a type that is different than year, in your case an int. We can see this in the REPL:
>>> r = r(300, 2000)
>>> r
range(300, 2000)
>>> type(r)
<class 'range'>
Typically, comparing values of two types will not lead to equality. For this reason == is not what you're looking for.
Ranges are a builtin type in Python, which implements all the common sequence operators. This is why what you're looking for is:
if year in range(300, 2000):
...
This clause will operate as you expect. Note that it does not scan the list, and is in fact take O(1) time, not O(n).
However, it is probably easier to simply see if your values are within the expected parameters using a direct integer comparison:
if year >= 300 and <= 2000:
...

You can do it this way simply:
def leap():
year = int(input("enter a number: "))
if 300 <= year < 2000:
print(year/400)
elif 2001 <= year < 2024:
print(year/4)
leap()
Or use in instead of ==

i believe this will determine a leap year
def leap():
year = int(input("enter a number: "))
if year % 400 == 0:
print('leap year')
elif year % 4 ==0 and year % 100 != 0:
print('leap year')
else:
print('not a leap year')
leap()
leap()

Related

How do I print from a list from loop that is then passed into a formula in a loop?

The goal is:
Starting at the year 1900 count every year to input year.
Then run it through leap year formula.
Print only years that are leap years.
I can get the counter to work and print, I can get leap year formula to work, 1 year at a time. I would like to combine both. What am I doing incorrectly?
counter = 1900
my_list = []
my_list = [str(item) for item in input("Enter ending year: ")]
while counter < my_list:
counter += 1
my_list.append(counter) # adds each value to list
if str(my_list) % 4 == 0 and str(my_list) % 100 != 0 or str(my_list) % 400 == 0:
print(str(my_list)[1:-1] + " is a leap year")
else:
pass
As you seem to be quite new to python and your code is not working I will just guess what you want to do and propose an answer
begin = 1900
end_as_str = input("Enter ending year: ") # input returns a string
end_as_int = int(end_as_str) # therefore you have to cast it to an int
for year in range(begin, end_as_int): # to give it here to range
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
print(str(year) + " is a leap year!")
Be aware that this will not include the end year
as range(1,4) for example would give you the numbers 1, 2 and 3 in an iterator, so the end is not included
I hope that you are a not submitting this right away to a teacher like this, and without going through it and understanding it, as I do not want to be the guy doing assignments for you. If it helps you to better understand python I am happy ;)
Edit: If you do not understand something from my solutin (for example range) try googling for it or search on youtube, you will likely find an explanation

leap year python script

I am trying to write a code that will accept any of the months of the year and output the month entered plus a list of the days in the month. But if February is entered it should ask for the birth year and check if that is a leap year and output February plus the days in February.
Where did I go wrong?
month = input("Enter any month of the year: ")
for n in month:
if (n == "January" or
n == "March" or
n == "April" or
n == "May" or
n == "June" or
n == "July" or
n == "August" or
n == "September" or
n == "October" or
n == "November" or
n == "December"):
print (n + range(1, 32))
elif n == "February" :
year = input("Enter a year")
for i in year:
if i % 4 == 0:
print (year + range(1,29))
I will advise you to simply use the built-in calendar module
# Program to display calendar of the given month and year
# importing calendar module
import calendar
yy = 2014 # year
mm = 11 # month
# To take month and year input from the user
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy, mm))
# output
# November 2014
#Mo Tu We Th Fr Sa Su
# 1 2
# 3 4 5 6 7 8 9
#10 11 12 13 14 15 16
#17 18 19 20 21 22 23
#24 25 26 27 28 29 30
Assuming your intent is to learn how to program (such as for a educational assignment), the following should help. If it's just to do the job, you should probably use some of the built-in Python modules (like datetime or calendar) since they'll do a lot of the hard work for you.
First, input returns a string and, when you iterate over a string (for n in month), you'll get one character at a time. So iterating over "May" will give you "M", "a", and "y", none of which are equal to "May". Don't iterate, just compare the entire string:
if month == "January" ...
Second, not all those months have 31 days, you'll need to distinguish those that have 30:
if month == "February":
doFebStuff()
elif month in ['September', 'April', 'June', 'November']:
do30DayStuff()
else:
do31DayStuff()
Third, you can't concatenate a string and a range, you'll need to do something like:
print(month, end='')
for i in range(1, 32):
print(f" {i}", end='')
print()
Fourth, again for the year, input gives you a string and you don't want to iterate over it. You also want to make it an integer if you're going to do mathematical calculations on it, something like:
year = int(input("Enter a year: "))
Fifth, the rules for leap years are slightly more complex than every four years, specifically:
if it's a multiple of 400, it's a leap year; else
if it's a multiple of 100, it's not; else
if it's a multiple of 4, it is; else
it's not.
Taking all that into account, here's one way to do it, with added checks for validity (month name and year):
Days30 = ["September", "April", "June", "November"]
Days31 = ["January", "March", "May", "July", "August", "October", "December"]
lastDay = None
month = input("Enter any month of the year: ")
if month == "February":
lastDay = 28
year = -1
while year < 0:
try:
year = int(input("Enter the year: "))
except:
year = -1
if year % 400 == 0 or (year % 100 != 0 and year % 4 == 0):
lastDay = 29
elif month in Days30:
lastDay = 30
elif month in Days31:
lastDay = 31
if lastDay is None:
print(f"I don't know the month {month}")
else:
print(f"{month}:", end="")
for day in range(1, lastDay + 1):
print(f" {day}", end="")
print()
I wouldn't try to pass that off as your own work (you'll almost certainly be pinged for plagiarism) but it's a good bit of code for getting some ideas.
If you are asking where did you go wrong, there are some places:
Your if and elif are not indented properly, they do not align.
When you write for n in month:, n takes value of every letter in the month inputed. e.g. if you entered "July", n would be iterating as "J", "u", "l", and "y". So comparing n to full names of months will always evaluate to False. Just compare the month instead of iterating over it.
When taking input, python stores the value entered by user as string (year = input("Enter a year")). So when you are iterating over the variable year (for i in year) you are iterating over a string of numbers and not the number. Furthermore, modulus operator won't work for strings (i % 4) as i in this case is a string. Just do year = int(input("Enter a year")) to convert year to ineger and do not iterate over it, check for remainder with 4 directly.
You can refer to the code by paxdiablo to get a working code.

Append based on another reference

Im allowed to use Numpy for the task.
I need to show the total sales in a month with two lists: dates and sales.
My approach is to make a list of all sales during a month by stripping the month off the date, creating a 2D matrix and adding the values that check for each month.
import numpy as np
dates = ["02/01/19", "03/02/19"]
sales = ["10.50", "12.20"]
month = [x.strip("0").split("/")[0] for x in dates]
monthsales = np.vstack((month, sales)).astype(np.float)
def monthlysales():
jan = []
for i in monthsales[0, 0:]:
if i == 1:
jan.append()
s = input("Pick month: ")
if s == "1":
print("Sales total for Jan is:", np.sum(jan), "USD")
else:
print("Not a valid month")
return
print(monthsales)
print(monthlysales())
The problem is that I dont know what to append so that it takes the second row of my matrix, which would complete the code
A solution keeping your logic:
Here I loop over the months (as you did, but here using enumerate), and look for when the month is equal to 1. Using enumerate allows us to know the column number of when the month equals 1 (id). Then it's just a matter of appending the sales (row 1) at the month we're interested in (id)
import numpy as np
dates = ["02/01/19", "03/02/19"]
sales = ["10.50", "12.20"]
month = [x.strip("0").split("/")[0] for x in dates]
monthsales = np.vstack((month, sales)).astype(np.float)
def monthlysales():
jan = []
# Loop over months with enumerate
for id, month in enumerate(monthsales[0]):
if month == 1:
# Append sales (row 1) at column id
jan.append(monthsales[1, id])
s = input("Pick month: ")
if s == "1":
print("Sales total for Jan is:", np.sum(jan), "USD")
else:
print("Not a valid month")
print(monthsales)
print(monthlysales())
Of course, since you're allowed to use numpy you could have avoided any looping altogether. Consider the following line:
monthsales[1, monthsales[0] == 1].sum()
This sums up the sales for all the January months in one line. No loops. For any reasonable amount of data this will be considerably quicker than the solution with enumerate.
Looking more like your initial solution you could have had:
def monthlysales():
s = int(input("Pick month: "))
if s >= 1 and s <= 12:
monies = monthsales[1, monthsales[0] == s].sum()
print("Sales total for month {} is {} USD".format(s, monies))
else:
print("Not a valid month")

Trying to build a python program that renders day of birth when user inputs birthday. Current attempt acts like a loop

We all know that in the Gregorian calendar that we are currently using, a random day of the week can be one of 7 options.
The intention of my code is based on a segment in Arthur Benjamin's Think Like A Math Genius (2006), whereby you can perform a simple party trick using mathematics. Using codes (basically implementing shortcuts based on the patterns of the Gregorian and finding the remainders after dividing by seven), one can quickly and accurately predict past and future days of the week.
My current attempt results in PyCharm overcomputing and eating up majority of CPU activity. I reckon that this could be because I have not limited the extent of user input 'Year' the same way I limited 'typedMonth'.
This is the original code:
print("Enter the full date: in dd/Month/yyyy")
Date = int(input("dd:"))
typedMonth = str(input("Month:"))
Year = int(input("yyyy: "))
while not int(Year) in range(0,3000):
Year = int(input("Please enter year (yyyy) limited to [0 - 3000] : "))
if typedMonth in ['January']:
Month = 3
while int(Year) % 4 == 0:
Month = 2
elif typedMonth in ['February']:
Month = 6
while int(Year) % 4 == 0:
Month = 5
elif typedMonth in ['March', 'November']:
Month = 6
elif typedMonth in ['April', 'July']:
Month = 2
elif typedMonth in ['May']:
Month = 4
elif typedMonth in ['August']:
Month = 5
elif typedMonth in ['September', 'December']:
Month = 1
elif typedMonth in ['October']:
Month = 3
elif typedMonth in ['June']:
Month = 0
else:
Month = 0
remYear = Year%400
if 300 <= remYear <= 400:
Year = Year + 1
elif 200 <= remYear <= 300:
Year = Year + 3
elif 100 <= remYear <= 200:
Year = Year + 5
else:
Year = Year + 0
print(remYear)
Day = (Date + int(Month) + remYear) % 7
print(Day)
Isolated testing shows that the first four lines of code work as intended (if I just print typedMonth), for instance.
In silo, the segment near the end from remYear= Year%400 also works as intended.
Hence, to my untrained eye, the 'overcomputation' is likely due to the stretch of code that I use to fix the Month variable from user input string typedMonth. To emphasise, the initial input for Month starts with the string typedMonth. I then use while statements to convert user input of string to an integer value. This integer value is attributed to variable 'Month' so that the final computation of integers 'Date', 'Month' and 'Year' can be made. Remainder will correspond to day of the week (e.g. 0 = Sunday, 1 = Monday, 2 = Tuesday, etc).
This is the updated code (third iteration). Thanks to the comments below, I am now able to enter most years as input and the program will run. Logic errors still persist, especially with the codes assigned to the months. I will fix them in future iterations.
print("Enter the full date: in dd/Month/yyyy")
Date = int(input("dd:"))
typedMonth = str(input("Month:"))
Year = int(input("yyyy: "))
while not int(Year) in range(1,3000):
Year = int(input("Please enter year (yyyy) limited to [0 - 3000] : "))
if typedMonth in ['January']:
Month = 3
while int(Year) % 4 == 0:
Month = 2
elif typedMonth in ['February']:
Month = 6
while int(Year) % 4 == 0:
Month = 5
elif typedMonth in ['March', 'November']:
Month = 6
elif typedMonth in ['April', 'July']:
Month = 2
elif typedMonth in ['May']:
Month = 4
elif typedMonth in ['June']:
Month = 0
elif typedMonth in ['August']:
Month = 5
elif typedMonth in ['September', 'December']:
Month = 1
elif typedMonth in ['October']:
Month = 3
remYear = Year%400
if 300 <= remYear <= 400:
Year = Year + 1
elif 200 <= remYear <= 300:
Year = Year + 3
elif 100 <= remYear <= 200:
Year = Year + 5
else:
Year = Year + 0
calcYear = int(Year % 100)
Day=(Date + Month + calcYear) % 7
print("The date is %d"%Date)
print("The month is %d"%Month)
print("The calculated year is %d"%calcYear)
print("The code for day is %d"%Day)
if Day in [0]:
print("You were born on a Sunday")
elif Day in [1]:
print("You were born on a Monday")
elif Day in [2]:
print("You were born on a Tuesday")
elif Day in [3]:
print("You were born on a Wednesday")
elif Day in [4]:
print("You were born on a Thursday")
elif Day in [5]:
print("You were born on a Friday")
elif Day in [6]:
print("You were born on a Saturday")
print("~~End Of Program~~")
Recommendations for restricting the range of computation of Year (limiting user input for Year does not fix the above problems) or restructuring the value for variable month from initial string input 'typedMonth' would be greatly appreciated.
P.S.1 Perhaps I should use another software for this project? I just started out with python so i don't know what applications would be more suited for such programs. Do recommend if you think that this could be a viable solution!
P.S.2 Made progress! The program kind of works for millennial babies (aka enter year after 2001), i still need to fix the logic!
P.S.3 Thanks to the comments below, I am now able to run the program. There are still glaring logic errors within the code. I endeavor to commence work on this project when time allows. I will update this post accordingly. Thanks for joining me in my learning journey!
You asked if Python was a suitable tool for this sort of project. It is, but it is much more suitable if you use it properly. In other words, don't make the problem unnecessarily difficult.
I understand your impulse to implement a particular algorithm to get comfortable with programming, but I have to say that this isn't a good choice. Date arithmetic is usually a pain. If you want to use computational shortcuts (and you should), then take a look at the shortcuts that the Python programming environment offers.
For example:
>>> import datetime
>>> from dateutil import parser
>>> date = "25/December/1999"
>>> datetime.datetime.strftime(parser.parse(date), "%A")
'Saturday'
The dateutil module isn't part of the standard library but it is well worth the trouble of installing.

Date Validity and Leap Year Checker

I've been trying to find ways to shorten or modify this code to increase the efficiency and reduce the complexity. Any Help?
I'm new to this website so I hope for a good response :D!
a=int(input('Enter the date:'))
b=int(input('Enter the month:'))
c=int(input('Enter the year:'))
if b<=12 and a<=31 and b>0 and a>0:
if b==2:
if a>29:
k=0
elif a<=29:
k=1
elif b==1 or b==3 or b==5 or b==7 or b==8 or b==10 or b==12:
if b>31:
k=0
else:
k=1
else:
if b>30:
k=0
else:
k=1
else:
k=0
if k==0:
print 'Invalid Date'
elif k==1:
if (c%4)==0:
if (c%100)==0:
if (c%400)==0:
t=1
else:
t=0
else:
t=1
if t==1:
print 'It is a leap year and has a valid date'
elif t==0 :
if a==29 and b==2:
print 'It isn\'t a valid date neither a leap year'
else:
print 'It is a valid date and a leap year'
Use inbuilt modules -
import datetime
import calendar
def validate_date(year, month, date):
"""Returns True if valid date else False"""
try:
datetime.datetime(year, month, date)
return True
except ValueError:
return False
Use calender.isleap(year) to check if the year is a leap year or not.
If you want to avoid the built-in modules and roll your own code, and if you change k and t to logical variables you could use
k = (1 <= b <= 12) and (1 <= a <= [31,29,31,30,31,30,31,31,30,31,30,31][b])
t = (c%4 == 0) and (c%100 != 0 or c%400 == 0)
As recommended by others, you should also change your variable names to be more clear. Note that this does not test that the variables are integers.
Here is another easier and more efficient way to check whether the entered year is a leap year or not.
year = int(input("Type a year: "))
if year % 4 == 0 and year %100 != 0 or year % 400 == 0:
print ("\nIs a leap-year")
else:
print ("\nIs not a leap-year")

Categories