Problem
I moved to Python today after doing a little of c++. The following code works as intended, but I want to know if I should add the if __name__ == "__main__"
statement. Any other improvements?
import datetime
def inputInfo() :
userName = input("Who are you?")
userAge = input("How old are you?")
return (userName , userAge)
def findYearWhenAge100(name , age) :
currentTime = str(datetime.datetime.now())
currentYear = int(currentTime[0: 4])
age = 100 - int(age)
currentYear += age
print( name ,"is going to be 100 by", currentYear)
if __name__ == "__main__":
userName , userAge = inputInfo()
print(findYearWhenAge100(userName , userAge))
Solution
Just to add to the answers already here, four things jump out at me. The datetime calculations, the print statements, the import statement and the case used in variables.
Case: Python uses snake_case and not camelCase. Please look into formatting your code in a PEP8 way.
import statement: Your code only imports datetime
and later, when you use it, you write datetime.datetime.now()
. Here’s a coding tip you might not have thought of previously – if you need to use more than a single period in your objects.attributes
or objects.methods()
, then you’re probably importing too much/too high a level.
Of course, my example violates that as I request the attribute after the method call – (¬‿¬) but the point remains true for imports.
Datetime: Your code converts the datetime into a string, slices it, converts it to an integer. This is unnecessary. If you’re going to perform calculations, leave everything as integers/floats.
Strings: Please look into the format function or if you use Python 3.6 or newer, f-strings. I’ll put both in the example below including executing a function inside an f-string (so, 3 print statements).
from datetime import datetime
def get_user_input():
name = input("Please tell me your name: ")
age = int(input("How old are you?"))
return name, age
def what_year_when_100(age):
return 100 - age + datetime.now().year
if __name__ == "__main__":
user_name, user_age = get_user_input()
print(f"{user_name} is going to be 100 by {what_year_when_100(user_age)}") # Python 3.6+
when_100 = what_year_when_100(user_age)
print("{} is going to be 100 by {}".format(user_name, when_100)) #Python 2/3
print(f"{user_name} is going to be 100 by {when_100}") # Python 3.6+
Hope this helps!
Your findYearWhenAge100()
function has a print()
statement, and returns nothing, so your __main__
doesn’t need to print the return value.
A good habit is adding """docstrings"""
to your functions. Eg)
def inputInfo():
"""Asks the user for name and age"""
#... remainder of code
The userInput()
function should do things like turning the userAge
string into an int. That should not be the responsibility of functions which need the age.
Use pylint
. It will help you write more standardized code. Things like a space is expected after a comma, not before.
Things like this can be confusing:
age = 100 - int(age)
currentYear += age
age
starts off being the user’s age, but then it gets changed to mean something different, and the name has become misleading. Similarly for currentYear
. It may be better to introduce new variables, like this:
time_until_100 = 100 - int(age)
future_year = currentYear + time_until_100
Or to inline the calculation:
age = int(age)
print(name, "is going to be 100 by", currentYear - age + 100)
Or a compromise between the two
birth_year = currentYear - int(age)
print(name, "is going to be 100 by", birth_year + 100)
Perhaps this last one is clearest (though birth_year
is only an estimate, given we don’t know whether the user has had a birthday yet this year).