Home > Back-end >  Python date of birth
Python date of birth

Time:09-27

Hi I just started to learn python from scratch and stumbled upon this recently

birth_year = input('Birth Year: ')
age = 2022 - float(birth_year)
print(age)

In the above lines of code used to determine the age of a person if I replace float with bool(just for experimenting) it returns the value 2021 no matter what the inputted birth year is. Can someone please explain why is it doing so?

CodePudding user response:

well what are you even expecting bool only has two values 0 or 1. when you pass some value to 'birth_year' the bool value becomes 1 cause in bool anything except 0 returns 1. I hope you are following me, and in the end it's like this, (2022-1)=2021

CodePudding user response:

I believe a bool can have only two values: 1 (true) or 0 (false) Anything that isn't zero is considered to be true. So when you say 2022 - bool(birth_year), you're really saying 2022 - 1, which will equal 2021.

CodePudding user response:

True evaluates to 1 in python. When you call bool() on an integer that does not equal 0, you will get True. You are basically subtracting 1 from 2022 here.

  • Related