Practice Python Exercise 1

  • #### Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.

Extras:

  • Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. (Hint: order of operations exists in Python)
  • Print out that many copies of the previous message on separate lines. (Hint: the string "\n is the same as pressing the ENTER button)

In [1]:
#Version 1
def main():
    name, age = input("Enter name") , int( input("Enter age"))
    for i in range( int(input("Enter a number"))):
         print("You will turn 100 in {}".format(2017-age+100))
main()


Enter nameVipin
Enter age27
Enter a number2
You will turn 100 in 2090
You will turn 100 in 2090

Using datetime module to find current date and extracting year from the current date


In [ ]:
from datetime import date 
today = str(date.today()).split("-")
print(type(today))
print(today[0])

Use the above and modify our program


In [ ]:
#Version 2

from datetime import date 
def main():
    name, age = input("Enter name") , int( input("Enter age"))
    thisYear = find_years()
    for i in range( int(input("Enter a number"))):
         print("You will turn 100 in {}".format(thisYear-age+100))
    
def find_years():
    today = str(date.today()).split('-')
    return int(today[0])
main()

In [ ]:
from datetime import date

def main():
    name, age = get_name() , get_age()
    thisYear = find_years()
    print("Hi {} ! You will turn 100 in {} \n".format(name,thisYear-age+100))
    for i in range( int(input("Please enter how many times the above message should show : \n"))):
         print("Hi {} ! You will turn 100 in {}".format(name,thisYear-age+100))

def get_name():
    return input("Please enter your name : \n")

def get_age():
    return int(input("Please enter your age : \n"))

def find_years():
    today = str(date.today()).split('-')
    return int(today[0])

if __name__ == '__main__':
    main()

In [ ]:
from datetime import date

def main():
    
    name = get_name()
    age = get_age()
    
    thisYear = find_years()
    turns100Year = calculate_year(age,thisYear)
    show_msg(name,turns100Year)
    
    
    for i in range( int(input("Please enter how many times the above message should show : \n"))):
         print("Hi {} ! You will turn 100 in {}".format(name,thisYear-age+100))

def get_name():
    return input("Please enter your name : \n")

def get_age():
    return int(input("Please enter your age : \n"))

def find_years():
    today = str(date.today()).split('-')
    return int(today[0])

def show_msg(name,turns100Year):
    print("Hi {} ! You will turn 100 in {} \n".format(name,turns100Year))
    
def calculate_year(age,thisYear):
    assert age >= 0 , "Age is not allowed to be less than zero"
    return thisYear-age+100

if __name__ == '__main__':
    main()

In [ ]:


In [ ]: