|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +''' |
| 5 | +Exercise |
| 6 | +
|
| 7 | +Create a program that asks the user to enter their name and their age. |
| 8 | +Print out a message addressed to them that tells them the year that they will turn 100 years old. |
| 9 | +
|
| 10 | +Extras: |
| 11 | +
|
| 12 | +Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. |
| 13 | +(Hint: order of operations exists in Python) |
| 14 | +
|
| 15 | +Print out that many copies of the previous message on separate lines. |
| 16 | +(Hint: the string '\n' is the same as pressing the ENTER button) |
| 17 | +''' |
| 18 | + |
| 19 | +import datetime |
| 20 | + |
| 21 | +def get_int_number(key, value): |
| 22 | + try: |
| 23 | + value = int(value) |
| 24 | + return value |
| 25 | + except ValueError: |
| 26 | + print '{key} must be an integer'.format(key=key) |
| 27 | + return None |
| 28 | + |
| 29 | +def main(): |
| 30 | + name = raw_input('Please input your name: ') |
| 31 | + age_raw = raw_input('Please input your age: ') |
| 32 | + |
| 33 | + now = datetime.datetime.now() |
| 34 | + year = now.year |
| 35 | + |
| 36 | + age = get_int_number(key='age', value=age_raw) |
| 37 | + while not age: |
| 38 | + age_raw = raw_input('Please input your age: ') |
| 39 | + age = get_int_number(key='age', value=age_raw) |
| 40 | + |
| 41 | + year = year + 100 - age |
| 42 | + |
| 43 | + msg = 'Hi, {name}, by the year {year} you will be 100 years old'.format(name=name, year=year) |
| 44 | + print msg |
| 45 | + |
| 46 | + copies_raw = raw_input('Please input the number of copies you want the message to duplicate: ') |
| 47 | + copies = get_int_number(key='copies', value=copies_raw) |
| 48 | + while not copies: |
| 49 | + copies_raw = raw_input('Please input your age: ') |
| 50 | + copies = get_int_number(key='copies', value=copies_raw) |
| 51 | + |
| 52 | + msg = (msg+'\n') * copies |
| 53 | + |
| 54 | + print msg |
| 55 | + |
| 56 | +if __name__ == '__main__': |
| 57 | + main() |
0 commit comments