Zeller's congruence gives the wrong outcome (Python) - python

So I want to calculate the day of the week by a given user input:
input1 = int(input("Please enter the year in which you were born\n"))
input2 = int(input("Please enter the month in which you were born\n"))
input3 = int(input("Please enter the day on which you were born\n"))
if 1 <= input2 <= 2:
input1 -= 1
elif input2 < 3:
input2 = input2 + 10
else:
input2 = input2 - 2
print(f'On which day of the week were you born?\n'
f'Please input your answer of the day of the week as follows:\n'
f'"mo", "tu", "we", "th", "fr", "sa", "su"')
inputweekday = str(input(f'Enter the day of the week on which you were born here\n'))
week_days=["su", "mo", "tu", "we", "th", "fr", "sa"]
D = abs(input1) % 100
C = int(str(input1)[:2])
A = 13*(input2 +1)
F = (input3 + (A//5) + D + (D//4) + (C//4) - 2*C) % 7
for i, x in enumerate(week_days):
if F == i:
F = x
if F == inputweekday:
print('You were correct.')
else:
print(f'Your answer was not correct.')
sys.exit(0)
I dont know why I cant seem to get the right days. Ive been struggling for hours and i couldnt find the answer online since almost all of them are implementented on C++.
Any tips?

Try this:
year = int(input("Please enter the year in which you were born\n"))
month = int(input("Please enter the month in which you were born\n"))
day = int(input("Please enter the day on which you were born\n"))
if month < 3:
month += 12
year -= 1
# inputweekday = str(input(f'Enter the day of the week on which you were born here\n'))
week_days=["sat", "su", "mo", "tu", "we", "th", "fr"]
century = int(year / 100)
century_year = year % 100
weekday = (day + 13*(month + 1)//5 + century_year + century_year//4 + century//4 - 2*century) % 7
print(weekday)
print(week_days[weekday])

Related

Finding Minutes Between Years

can you please check my code? I think something is wrong somewhere.
import datetime
this_year = datetime.datetime.today().year
def age_in_minutes(b_year: int):
d1 = datetime.datetime.strptime(f'{this_year}', '%Y')
d2 = datetime.datetime.strptime(f'{b_year}', '%Y')
age = (d1-d2).days * 24 * 60
return f"{age:,}"
while True:
birth_year = input("Enter you birth year: ")
try:
if int(birth_year) == this_year:
print("Please enter year less than this year...")
elif int(birth_year) > this_year:
print("Please enter year less than this year...")
elif len(birth_year) < 4 or len(birth_year) > 5:
print("PLease enter a valid year...")
elif int(birth_year) <= 1900:
print("Please enter a year after 1900...")
else:
minutes_old = age_in_minutes(int(birth_year))
print(f"You are {minutes_old} minutes old.")
break
except ValueError:
print("Please enter in a year format: ")
I'm tackling a challenge. It said if I enter 1930, I should get "48,355,200". But I'm getting "48,388,320". I'm new to Python.
You could try this code
I found it somewhere in 2021 but I don't know the source
current_year = 2022
year = int(input("Please enter a year: "))
if year == current_year:
print("There are 0 minutes from", year, "to present.")
elif year < current_year:
print("There are", (current_year - year) * 525600, "minutes from", year, "to present.")
else:
print("There are", (year - current_year) * 525600, "minutes from present to", year)
try this:
import datetime
this_year = datetime.datetime.today().year
print(this_year)
def age_in_minutes(b_year: int):
d1 = datetime.datetime.strptime(f'{this_year}', '%Y')
d2 = datetime.datetime.strptime(f'{b_year}', '%Y')
age = (d1-d2).days * 24 * 60
return f"{age:,}"
while True:
birth_year = int(input("Enter you birth year: "))
try:
if birth_year == this_year:
print("Please enter year less than this year...")
elif birth_year > this_year:
print("Please enter year less than this year...")
elif len(str(birth_year)) < 4 or len(str(birth_year)) > 5:
print("PLease enter a valid year...")
elif birth_year <= 1900:
print("Please enter a year after 1900...")
else:
minutes_old = age_in_minutes(birth_year)
print(f"You are {minutes_old} minutes old.")
break
except ValueError:
print("Please enter in a year format: ")
Output:
Enter you birth year: 1930
You are 48,388,320 minutes old.
I don't do any exceptional but change your type casting, and it can give me a desire result.
You haven't calculated leap year. You can follow this:
import datetime
this_year = datetime.datetime.today().year
def age_in_minutes(b_year: int):
leap_year = 0
non_leap_year = 0
for year in range(b_year, this_year+1):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
leap_year += 1
else:
non_leap_year += 1
leap_year_in_days = leap_year * 366
non_leap_year_in_days = non_leap_year * 365
age = (leap_year_in_days + non_leap_year_in_days) * 24 * 60
return f"{age:,}"
while True:
birth_year = input("Enter you birth year: ")
try:
if int(birth_year) == this_year:
print("Please enter year less than this year...")
elif int(birth_year) > this_year:
print("Please enter year less than this year...")
elif len(birth_year) < 4 or len(birth_year) > 5:
print("PLease enter a valid year...")
elif int(birth_year) <= 1900:
print("Please enter a year after 1900...")
else:
minutes_old = age_in_minutes(int(birth_year))
print(f"You are {minutes_old} minutes old.")
break
except ValueError:
print("Please enter in a year format: ")

Skip lines in Python 3

Just started learning. Trying to figure out how to skip a line in the Times = (Times * int(Random_Number)),
to be something like :
print(Times)
print(Times)
Etc..
Year = input("Now's year : ")
name= input("Enter your name: ")
Initial_age= float(input(("Enter your age: ")))
Final_age= float(Year) + (100 - Initial_age)
Times =(name+ " You're turning"+ " 100 at year " + str(Final_age))
Random_Number = (input("Enter a random number: "))
Times = (Times * int(Random_Number))
print(Times)
If you want to print each NAME You're turning 100 at year XXXX on a new line, like this
John You're turning 100 at year 2109.0
John You're turning 100 at year 2109.0
John You're turning 100 at year 2109.0
John You're turning 100 at year 2109.0
Add a \n at the end here
Times = name + " You're turning 100 at year " + str(Final_age) + "\n"
But the nicest is to use a loop, and a print inside of it
year = int(input("Now's year : "))
name = input("Enter your name: ")
initial_age = int(input("Enter your age: "))
random_number = int(input("Enter a random number: "))
final_age = year + 100 - initial_age
for i in range(random_number):
print(name, "You're turning 100 at year", final_age)

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

Python - Multi Input Validation

I'm writing a pay calculator program using a series of nested loops. Everything works except I have to make sure that the input for number of hours worked on the specified day is between 0 and 24 inclusive. This is the code I have for that section, I've tried multiple different options but they all either crash the program or aren't recognised at all. Any help would be appreciated!
This is the related code:
for x in range(0, weeks):
for y in days:
while True:
print ("Enter the number of hours for Week", x+1, y, ":")
try:
hours = int(input())
except ValueError:
print ("Invalid: Enter a positive integer")
continue
else:
break;
if y == 'Saturday':
newRate = satRate
elif y == 'Sunday':
newRate = sunRate
else:
newRate = baseRate
rate += (hours * newRate)
This is the whole code if you need a more wide look:
baseRate = -1
while baseRate < 1:
baseRate = float(input("Enter the base pay rate: "))
if baseRate < 1:
print("Invalid: Enter a non-negative amount")
satRate = baseRate * 1.5
sunRate = baseRate * 2
pay = 0
rate = 0
hours = -2
weeks = -1
while weeks < 1:
while True:
try:
weeks = int(input("Enter the number of weeks: "))
except ValueError:
print("Invalid: Enter a positive integer")
continue
else:
break
if weeks < 1:
print("Invalid: Enter a positive integer")
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
for x in range(0, weeks):
for y in days:
while True:
print ("Enter the number of hours for Week", x+1, y, ":")
try:
hours = int(input())
except ValueError:
print ("Invalid: Enter a positive integer")
continue
else:
break;
if y == 'Saturday':
newRate = satRate
elif y == 'Sunday':
newRate = sunRate
else:
newRate = baseRate
rate += (hours * newRate)
pay = (round(rate, 2))
av = pay/weeks
average = round(av,2)
print("Total pay is: ", pay)
print("Average pay per week is: ", average)
Your code doesn't check for valid hours input (unless you removed it due to it crashing, etc). Here one way to do it:
try:
hours = int(input())
while not 0 <= hours <= 24:
print ("Invalid input, hours must be between 0 and 24 inclusive.")
print ("Try again")
hours = int(input())
except ValueError:
print ("Invalid: Enter a positive integer")
continue
It is usually better to work more modular, using functions for your actions. This code may work and it's much more readable:
def get_baserate():
rate = input('Base rate:')
try:
rate = float(rate)
if not rate > 0:
print 'Rate must be positive'
return get_baserate()
return rate
except TypeError:
print 'Rate must be a positive number'
return get_baserate()
def get_weeks():
weeks = input('Number of weeks:')
try:
weeks = int(weeks)
if not weeks > 0:
print 'A positive number must be entered'
return get_weeks()
return weeks + 1
except TypeError:
print 'An integer must be entered'
return get_weeks()
def get_hours(week, day):
hours = input('Enter number of hours worked on %s of week %s:' % (day, week))
try:
hours = int(hours)
if not 0 <= hours <= 24:
print 'A number between 0-24 must be entered'
return get_hours(day)
return hours
except TypeError:
print 'An integer must be entered'
return get_hours(day)
def get_payday(rate, hours, day):
rate = 2*rate if day == 'Sunday' else 1.5*rate if day == 'Saturday' else rate
return hours*rate
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
rate = get_baserate()
weeks = get_weeks()
total_payday = 0
for week in range(1, weeks):
for day in days:
hours = get_hours(week, day)
total_payday += get_payday(rate, hours, day)
print 'Your total pay is: %s' % total_payday

How would I turn these raw_input answers and input them into my functions?

I'm pretty new to coding so bear with me but how do I make this code work? I'm trying to take the information that is entered by the user and input it into my functions so I can print the total.
def hotel_cost(nights):
return nights * 140
def plane_cost(city):
if city == "Atlanta":
return 220
elif city == "Boston":
return 550
elif city == "Chicago":
return 900
def rental_car_cost(days):
if days >= 7:
return days * 100 - 50
elif days >= 1 and days <= 5:
return days * 100 - 20
a = raw_input("Please choose number of nights: ")
b = raw_input("Please choose which city you are flying to (Atlanta, Boston, Chicago) ")
c = raw_input("Please choose days of rental car use: ")
d = raw_input("Please choose how much spending money you plan on spending: ")
a = nights
b = city
c = days
total = a + b + c + d
print "Your total cost of trip is %d" % total
You need to first convert your numeric input values to numbers and then pass your input values to your functions.
Delete the lines
a = nights
b = city
c = days
Calculate your total with
total = hotel_cost(int(a)) + plane_cost(b) + rental_car_cost(int(c)) + float(d)
I assumed that for the number of nights and rental car days only integers make sense.
I am not sure if this applies in Python version 2. However, you could try this:
a = int(raw_input("Please choose number of nights: ") * 140 )
# Multiplies by 140, but this would defeat the purpose of your functions.
And apply the int function to convert all of your inputs into integers.
You can use input() in Python 2 as it evaluates the input to the correct type. For the functions, you just need to pass your values into them, like this:
def hotel_cost(nights):
return nights * 140
def plane_cost(city):
if city == "Atlanta":
return 220
elif city == "Boston":
return 550
elif city == "Chicago":
return 900
def rental_car_cost(days):
if days >= 7:
return days * 100 - 50
elif days >= 1 and days <= 5:
return days * 100 - 20
nights = input("Please choose number of nights: ")
city = raw_input("Please choose which city you are flying to (Atlanta, Boston, Chicago) ")
rental_duration = input("Please choose days of rental car use: ")
spending_money = input("Please choose how much spending money you plan on spending: ")
total = hotel_cost(nights) + plane_cost(city) + rental_car_cost(rental_duration) + spending_money
print "Your total cost of trip is %d" % total

Categories

Resources