Konuyu Oyla:
  • Derecelendirme: 0/5 - 0 oy
  • 1
  • 2
  • 3
  • 4
  • 5
Yaş Hesaplayıcı Programlama Sorununda Hata Ayıklama Yardımı
#1
Hello everyone,
I'm working on a simple age calculator program but I'm having some trouble getting the correct age output. The program should take the user's birth date and calculate their current age based on today's date. However, the age calculation is sometimes off by a year, especially if the birthday has not occurred yet this year.
Here is a piece of my code:
Python
Copy code
from datetime import datetime

def calculate_age(birthdate):
   today = datetime.today()
   age = today.year - birthdate.year
   
   if today.month < birthdate.month or (today.month == birthdate.month and today.day < birthdate.day):
       age -= 1
   
   return age

birthdate = datetime(1990, 7, 5)
print("Yaş:", calculate_age(birthdate))
Can anyone see where I'm going wrong? Is there a better way to calculate age so it's always correct?
Thanks in advance for your help!
Cevapla
#2
I don't know pyton but thanks to internet has many resources.

If you had given us a few sample dates, we would at least have the opportunity to compare the dates that should have been and the dates that produced incorrect results.

You may want to try the code below...


from datetime import date
from dateutil import parser

def calculate_age(birthdate):
   today = date.today()
   return today.year - birthdate.year - ( (today.month, today.day) < (birthdate.month, birthdate.day) )
   
birthdate = parser.parse("05.07.1990")
print( "Yaş:", calculate_age( birthdate ) )
Code testing site URL:  https://www.programiz.com/python-program...-compiler/
Saygılarımla
Muharrem ARMAN

guplouajuixjzfm15eqb.gif
Cevapla


Konu ile Alakalı Benzer Konular
Konular Yazar Yorumlar Okunma Son Yorum
  Lokasyon Sensör hata turkcann 3 448 10-03-2025, Saat: 09:55
Son Yorum: RAD Coder
  Rest Server Hata m_ekici 2 399 09-03-2025, Saat: 13:32
Son Yorum: m_ekici
  DEĞİŞİK HATA tarkanbey 6 618 16-01-2025, Saat: 20:26
Son Yorum: tarkanbey
  Delphi7 Açık Kaynak Kodlu Projedeki Hata Hk. erdal51 5 585 13-09-2024, Saat: 08:11
Son Yorum: hi_selamlar
  Rest Hata Yakalama m_ekici 13 2.873 15-08-2024, Saat: 17:32
Son Yorum: mrmarman



Konuyu Okuyanlar: 1 Ziyaretçi