简体   繁体   中英

An error in a program to calculate age in python

Hello everybody i wrote a simple program to calculate age in python i faced a problem that the result was uncorrect and i fixed it,but i want to know its reason,i'll put the code and it's a weak code,because i'm a newbie.

So why should i put variables(Day,Month,and Year) down if statements,while when they were up them the result was uncorrect? and thanks.

CrrentYear=input("Enter the current year in numbers : ")
CurrentMonth=input("Enter the current month in numbers : ")
CurrentDay=input("Enter the current day in numbers : ")
BirthYear=input("Enter your birth year in numbers : ")
BirthMonth=input("Enter your birth month in numbers : ")
BirthDay=input("Enter your birth day in numbers : ")


if CurrentDay < BirthDay:
    CurrentDay+=30
    CurrentMonth-=1

if CurrentMonth < BirthMonth:
   CurrentMonth+=12
   CrrentYear-=1

Day=CurrentDay-BirthDay
Month=CurrentMonth-BirthMonth
Year=CrrentYear-BirthYear



print("Your age is : "+str(Year)+" "+"Years"+" "+"and"+" "+str(Month)+"     "+"Months"+" "+"and"+" "+str(Day)+" "+"Days")

Your question is a little vague... but I will try to help.

By "up if statements" I think you mean above the if statements, and by "down if statements" I think you mean below the if statements.

If you calculate Day , Month and Year above the if statements, sometimes the code will still work, depending on the inputs. This is because your first if statements only happen IF currentDay is less than birthDay .

In my case, my birthday is on the 1st, so that if statement returns False , so the result is ok: you don't need to round the day and month (yet).

However, if the current day was 20 and the birthday was 10 , you can't have -10 days, so you have to add one month , and recalculate how many days it was.

The same kind of logic applies to the months & years.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM