python基础训练题答案_Python练习题(1)

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知识点做介绍,有问题欢迎大家留言交流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值