Gevin Says
今天GevinView准备再开一个新坑,时不时的找一些适用于Python初学者的练习题,供各位对Python感兴趣的同学们使用。
这些题目和答案,我都会放到我在GitHub的项目python_practices中,题目的来源也会放到项目中。今天是第一题,题目来源于网站PRACTICE PYTHON,该网站也提供了自己的答案,大家也可以一块参考一下。
1. 题目
练习一
编写一个程序,要求用户输入姓名和年龄,然后返回给用户一个消息,其消息内容是,告诉用户哪一年他会到100岁。
附件项:
上面的程序上再多加一项,让用户再输入一个数字,然后用户输入的数字是几,就把上面程序中的消息打印几遍。
......
......
......
下面进入答案部分...
2. 答案
作为Python入门的第一题,用最基础的Python知识即可搞定。因此首先提供一个基础答案。
2.1 基础答案
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
name = raw_input('Please input your name: ')
age = raw_input('Please input your age: ')
now = datetime.datetime.now()
year = now.year
age = int(age)
year = year + 100 - age
msg = 'Hi, {name}, by the year {year} you will be 100 years old'.format(name=name, year=year)
print msg
copies = raw_input('Please input the number of copies you want the message to duplicate: ')
copies = int(copies)
msg = (msg+'\n') * copies
print msg
2.2 进阶答案
接下来的Python练习题中,如果题目恰当,Gevin会在基础答案之外,再提供一个更好的答案,其逻辑也会稍微复杂一点。正如本题,如果重构代码,可以提供如下解决方案:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
def get_int_number(key, value):
try:
value = int(value)
return value
except ValueError:
print '{key} must be an integer'.format(key=key)
return None
def main():
name = raw_input('Please input your name: ')
age_raw = raw_input('Please input your age: ')
now = datetime.datetime.now()
year = now.year
age = get_int_number(key='age', value=age_raw)
while not age:
age_raw = raw_input('Please input your age: ')
age = get_int_number(key='age', value=age_raw)
year = year + 100 - age
msg = 'Hi, {name}, by the year {year} you will be 100 years old'.format(name=name, year=year)
print msg
copies_raw = raw_input('Please input the number of copies you want the message to duplicate: ')
copies = get_int_number(key='copies', value=copies_raw)
while not copies:
copies_raw = raw_input('Please input your age: ')
copies = get_int_number(key='copies', value=copies_raw)
msg = (msg+'\n') * copies
print msg
if __name__ == '__main__':
main()
由于是Python练习题,Gevin不在文章中对相关Python知识点做介绍,有问题欢迎大家留言交流。