program asking for the name and date (year, month and day) of a person’s birth in Python

Asked

Viewed 6,588 times

0

Hello, I am having difficulties in the following code in Python:.

The idea is to create a program that asks for the name and date (year, month and day) of birth of a person.

The program must also request the current date (year, month and day).

On the basis of these dates, it shall determine the age of the person.

Example of a result:

What’s your name? joaquin

What year were you born? 2001

What month were you born in? 2

What day were you born? 23

What year is it? 2018

What month is it? 4

What day is it? 9

Joaquim is 16 years old

The problem is that if a person turns his or her birthday on April 5, 1974 and the current date is January 2, 2018, that person should be 43 years old!

And this is where you’re always giving me 44 years! I don’t know if I made myself clear!??!

Here is my code

1 answer

0


Right, you can create two date objects (dataNasc and dataAtual) and subtract to get the timedelta(difference between both) and after that consider the average of days of a year, getting more or less like this.

import datetime

#Entrada de valores
print('='*18)
print('Exercício 2: idade')
print('='*18)
nome = input ("Como se chama? ")
ano = eval (input ("Nasceu em que ano? "))
mes = eval (input ("Nasceu em que mês? "))
dia = eval (input ("Nasceu em que dia? "))
ano_atual = eval (input ("Ano atual? "))
mes_atual = eval (input ("Mês atual? "))
dia_atual = eval (input ("Dia atual? "))
dataNasc = datetime.date(ano, mes, dia)
dataAtual = datetime.date(ano_atual, mes_atual, dia_atual)

#diferença retorna em timedelta
diferenca = (dataAtual - dataNasc)
#Cálculos e Resultados
rslt = (diferenca.days / 365.25)
#ano_atual-ano

if (dia == dia_atual and mes == mes_atual):
    print ("O %s tem %d anos!" %(nome, rslt))
else:
    ((dia > dia_atual and mes == mes_atual) or mes < mes_atual)
    print ("O %s tem %d anos!" %(nome, rslt))

For further doubts regarding comparisons with dates and manipulations access here

  • The problem is whether a person has his birthday on April 5, 1974 and the current date is January 2, 2018, that person should be 43 years old! And this is where you’re always giving me 44 years! I don’t know if I made myself clear!??!

  • I edited the answer, check if that way it was clear.

  • I have an error in the compilation of the code: ================== Exercise 2: age ==================== What’s it called? Joao Was born in what year? 1974 Was born in what month? 4 Was born on what day? 1 Current year? 2018 Current month? 2 Current day? 1 Traceback (Most recent call last): File "python", line 12, in <module> Nameerror: name 'datetime' is not defined

  • Did you put import datetime at the beginning? the code posted here is normally running here for me

  • 1

    Already gives!! Thanks for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.