您的位置:首页 > 编程语言 > Python开发

python-如何根据用户选择实现不同函数功能

2017-04-12 16:34 781 查看
由于本人python小白一个,目前在看《python 核心编程第二版》,以下代码大部分来自 https://wenku.baidu.com/view/4250ebaaa417866fb94a8e58.html.
题目如下:写一个带文本菜单的程序,菜单项如下:(1)取五个数的和;(2)取5个数的平均值 (x)退出。由用户做一个选择,然后执行相应的功能。

def sum():

total=0

for i in range(5):

print"please input number%d"%(i+1)

a=input()

total=total+a

print"total=",total

def average():

total=0

for i in range(5):

b=float(input('please enter a number%d:'%(i+1)))

total=total+b

print'the average is',total/5

print'''

please input 1 to get the total of 5 numbers

please input 2 to get the average of 5 numbers

please input x to exit

'''

choice=raw_input()

if choice=='1':

sum()

elif choice=='2':

average()

elif choice=='x':

pass

本程序十分基础,在此记录在运行过程的一些想法

首先,由于input输入数值则保存值也为数值类型,而raw_input()是字符型,导出时还需要转换,故在取数时用input较好。

其次print"please input number%d"%(i+1)  a=input()和a=(input('please enter a number%d:'%(i+1))) 效果一样

最后,运行时,代码会先运行

print'''

please input 1 to get the total of 5 numbers

please input 2 to get the average of 5 numbers

please input x to exit

'''

再根据相应的选择运行对应的函数
(只是记录自己的学习过程)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐