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: ")
Related
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])
it as been a long time without programming. I'm doing a function that converts the age of a dog to human years, but I'm getting some mistakes and I am not getting through them. This is my code
def calculator():
# Get dog age
age = input("Input dog years: ")
try:
# Cast to float
d_age = float(age)
# If user enters negative number, print message
if(d_age < 0):
print("Age can not be a negative number", age)
# Otherwise, calculate dog's age in human years
elif(d_age == 1):
d_age = 15
elif(d_age == 2):
d_age = 2 * 12
elif(d_age == 3):
d_age = 3 * 9.3
elif(d_age == 4):
d_age = 4 * 8
elif(d_age == 5):
d_age = 5 * 7.2
else:
d_age = 5 * 7.2 + (float(age) - 5) * 7
print("\n \t \'The given dog age", age, "is", d_age, "human years.'")
except ValueError:
print(age, "is an invalid age")
calculator()
and I'm not understanding why d_age < 0 is not working and I'm not getting why it appears as an error "calculator() is not defined". Thanks in advance!
NOTE: I saw that there already is question about this, but I'm doing in a different way.
EDIT: I just didn't do it with dictionaires, because it wasn't yet introduced in the course. I'm just trying to do with what I learned. Thanks anyway.
Looks like your code is not structure correctly. If you move the elif blocks and make some minor changes it will work. See below:
def calculator():
# Get dog age
age = input("Input dog years: ")
try:
# Cast to float
d_age = float(age)
# If user enters negative number, print message
if(d_age < 0):
print("Age can not be a negative number", age)
# Otherwise, calculate dog's age in human years
elif(d_age == 1):
d_age = 15
elif(d_age == 2):
d_age == 2 * 12
elif(d_age == 3):
d_age == 3 * 9.3
elif(d_age == 4):
d_age = 4 * 8
elif(d_age == 5):
d_age = 3 * 7.2
else:
d_age = 5 * 7.2 + (age - 5) * 7
print("\n \t \'The given dog age", age, "is", d_age, "human years.")
except ValueError:
print(age, "is an invalid age")
calculator()
How about this?
While statement to keep question looping until you get a valid response.
Dictionary to have a more organised age calculation sheet instead of lots of if statements.
def calculator_dog_age():
age = 0
while age == 0:
age = input("Input dog years: ")
try:
age = int(age)
if 20 > age > 0:
print('A good age was entered:', age)
age_dict = {1: 15, 2: 24, 3: 27.9, 4: 32}
if age in age_dict:
return age_dict[age]
else:
return age * 7.2 + (age - 5) * 7
else:
print('Please enter a realistic age!')
age = 0
except:
print('Please enter an integer!')
age = 0
print(calculator_dog_age())
This is my suggestion, even though the answer was accepted.
def calculator():
age = input("Input dog years: ")
try:
d_age = float(age)
ageDict = {1: 15, 2: 12, 3: 9.3, 4: 8, 5: 7.2}
if d_age in ageDict:
print(round(d_age*ageDict[d_age],2))
else:
print(round(5*7.2+(d_age - 5)*7,2))
except ValueError:
print(age,"is an invalid age")
calculator()
#get user's input on dog_age
dog_age = input("Enter your dog's age in years")
try:
#cast to a float
d_age = float(dog_age)
#convert dog age to human age
#ensure input is not negative
if (d_age > 0):
if (d_age <=1):
h_age = d_age *15
elif (d_age <=2):
h_age = d_age *12
elif (d_age <=3):
h_age = d_age*9.3
elif (d_age <=4):
h_age = d_age*8
elif (d_age <=5):
h_age = d_age*7.2
else:
h_age = 36 + (d_age - 5) *7
human_age = round(h_age,2)
#print instruction for valid input
print('The given dog age', dog_age,'is', str(human_age),'in human years')
else:
print('Age cannot be a negative number.')
except ValueError:
print(dog_age,'is invalid.')
The question I was solving has similar conditions but with different calculations required. I hope it helps (P.S initially I also could not figure out why my dog age <0 condition was not working, turns out, it’s all about blocking the conditions together and indentation use (: )
If anyone struggling with indention error or "SyntaxError: unexpected character after line continuation character" from print("\n \t 'The given dog age", age, "is", d_age, "human years."
The following solution helped me
def calculator():
# Get dog age
age = input("Input dog years: ")
try:
# Cast to float
d_age = float(age)
if (d_age> 5):
human_age = (d_age-5)*7+5*7.2
print("The given dog age",str(d_age),"is", str(human_age), "in human years")
elif (d_age>4):
human_age = d_age*7.2
print("The given dog age",str(d_age),"is",str(human_age),"in human years")
elif (d_age>3):
human_age = d_age*8
print("The given dog age",str(d_age),"is",str(human_age),"in human years")
elif (d_age>2):
human_age = d_age*9.3
print("The given dog age",str(d_age),"is",round(human_age,2),"in human years")
elif (d_age>1):
human_age = d_age*12
print("The given dog age",str(d_age),"is",str(human_age),"in human years")
elif (d_age>0):
human_age = d_age*15
print("The given dog age",str(d_age),"is",str(human_age),"in human years")
elif (d_age<0 or d_age==0):
print(d_age, "is a negative number or zero. Age can not be that.")
except:
print(age, "is an invalid age.")
print(traceback.format_exc())
calculator()
fee = []
age = int(input("Enter age: "))
while age != '':
age = int(input("Enter age: "))
if age <= 5:
fee.append(0)
elif age >= 6 and age <= 64:
fee.append(50.00)
else:
fee.append(25.00)
total = sum(fee)
print("Total payment: ", total)
I want to make a program that would sum up the given entrance fees. I don't even know if I'm doing it correctly
You can't compare a string to an integer, that's your main problem. If you retrieve it from the user as a string and check it is indeed an integer or not will work. That code should do the trick:
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
fee = []
r='start'
while r != '':
r = input("Enter age: ")
if RepresentsInt(r):
age = int(r)
if age <= 5:
fee.append(0)
elif age >= 6 and age <= 64:
fee.append(50.00)
else:
fee.append(25.00)
total = sum(fee)
print("Total payment: ", total)
fee = 0
age = int(input("Enter age: "))
while age != '':
try:
age = int(input("Enter age: ")) // to avoid exception of string
except:
break
if age <= 5:
fee += 0 // no need to append if outcome is a number
elif age >= 6 and age <= 64:
fee += 50
else:
fee += 25
total = fee
print("Total payment: ", total)
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()
import os
from datetime import date
def program():
Year = input("year of birth:" )
Month = input("month of birth:" )
Day = input("day of birth:" )
Date_of_Birth = (Day + "/" + Month + "/" + Year)
print('Your Date of Birth is ' + Date_of_Birth)
d = date.today()
y = d.year
os.system("cls")
age = y - int(Year)
print('Your age is ' + str(age))
def zodiac_sign():
if (int(Month)==12<2):
print("\n Capricorn")
elif (int(Month)==1<3):
print("\n aquarium")
elif (int(Month)==2<4):
print("\n Pices")
elif(int(Month)==3<5):
print ("\n Aries")
elif(int(Month)==4<6):
print("\n Taurus")
elif(int(Month)==5<7):
print("\n Gemini")
elif(int(Month)==6<8):
print("\n cancer")
elif(int(Month)==7<9):
print ("\n leo")
elif(int(Month)==8<9):
print ("\n virgo")
elif(int(Month)==9<10):
print ("\n libra")
elif(int(Month)==10<12):
print ("\n Scorpio")
elif(int(Month)==11<13):
print("\n Sagittarius")
zodiac_sign()
input()
program()
I'm trying to get the zodiac sign but I can't find a way to insert the number. I already tried to put it like this:
if (int(Month)==12<2 , int(day)==22<1):
print("\n Capricorn")
etc etc
but it keeps saying "capricorn" no matter which date I put in. Can you give me any solution?
I'm using python V3.4.0
import os
from datetime import date
def program():
Year = input("year of birth:" )
Month = input("month of birth:" )
Day = input("day of birth:" )
Date_of_Birth = (Day + "/" + Month + "/" + Year)
print('Your Date of Birth is ' + Date_of_Birth)
d = date.today()
y = d.year
os.system("cls")
age = y - int(Year)
print('Your age is ' + str(age))
if ((int(Month)==12 and int(Day) >= 22)or(int(Month)==1 and int(Day)<= 19)):
Signo_Zodiacal = ("\n Capricorn")
elif ((int(Month)==1 and int(Day) >= 20)or(int(Month)==2 and int(Day)<= 17)):
zodiac_sign = ("\n aquarium")
elif ((int(Month)==2 and int(Day) >= 18)or(int(Month)==3 and int(Day)<= 19)):
zodiac_sign = ("\n Pices")
elif ((int(Month)==3 and int(Day) >= 20)or(int(Month)==4 and int(Day)<= 19)):
zodiac_sign = ("\n Aries")
elif ((int(Month)==4 and int(Day) >= 20)or(int(Month)==5 and int(Day)<= 20)):
zodiac_sign = ("\n Taurus")
elif ((int(Month)==5 and int(Day) >= 21)or(int(Month)==6 and int(Day)<= 20)):
zodiac_sign = ("\n Gemini")
elif ((int(Month)==6 and int(Day) >= 21)or(int(Month)==7 and int(Day)<= 22)):
zodiac_sign = ("\n Cancer")
elif ((int(Month)==7 and int(Day) >= 23)or(int(Month)==8 and int(Day)<= 22)):
zodiac_sign = ("\n Leo")
elif ((int(Month)==8 and int(Day) >= 23)or(int(Month)==9 and int(Day)<= 22)):
Signo_Zodiacal = ("\n Virgo")
elif ((int(Month)==9 and int(Day) >= 23)or(int(Month)==10 and int(Day)<= 22)):
zodiac_sign = ("\n Libra")
elif ((int(Month)==10 and int(Day) >= 23)or(int(Month)==11 and int(Day)<= 21)):
zodiac_sign = ("\n Scorpio")
elif ((int(Month)==11 and int(Day) >= 22)or(int(Month)==12 and int(Day)<= 21)):
zodiac_sign = ("\n Sagittarius")
print(zodiac_sign)
program()
fixed by me
def again():
print("")
print("Please check you month")
print("Month must be the following")
print("01 - January")
print("02 - Febuary")
print("03 - March")
print("04 - April")
print("05 - May")
print("06 - Jun")
print("07 - Jully")
print("08 - August")
print("09 - September")
print("10 - October")
print("11 - Novemver")
print("12 - December")
print("")
def zodiac():
month = input("Month of birth(eg. 01,04,,12):")
day = int(input("Day of birth:"))
bday = ( month + "/" + str(day))
if (int(month) > 12):
again()
zodiac()
elif month == "01":
if (day > 31):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 20):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Capricorn!")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Aquarius")
elif month == "02":
if (day >28):
print("")
print("Invalid Date")
print("Please try again")
print("")
zodiac()
elif (day <= 18):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Aquarius")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Pisces")
elif month == "03":
if (day > 31):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 20):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Pisces")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Aries")
elif month == "04":
if (day > 30):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 20):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Aries")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Taurus")
elif month == "05":
if (day > 31):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 20):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Taurus")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Gemini")
elif month == "06":
if (day > 30):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 21):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Gemini")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Cancer")
elif month == "07":
if (day > 31):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 22):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Cancer")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Leo")
elif month == "08":
if (day > 31):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <=23):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Leo")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Virgo")
elif month == "09":
if (day > 30):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 23):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Virgo")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Libra")
elif month == "10":
if (day > 31):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 23):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Libra")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Scorpio")
elif month == "11":
if (day > 30):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 23):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Scorpio")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Sagittarius")
elif month == "12":
if (day > 31):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 21):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Sagittarius")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Capricorn")
else:
print("")
again()
zodiac()
zodiac()
print("")
again = input("Type 'zodiac' if you want to try again: ")
if (again == "zodiac"):
zodiac()