python核心编程第二章练习答案

2.8

循环和操作符(自己定义一个列表的较简单,下面的答案是用户自己输入列表)

方法一
sb=[]
sum=0
st=list(input("please input the number:"))
print (st)
for i in range(len(st)):
    sb.append(int(st[i]))
    sum+=sb[i]
print (sum)

这里写图片描述
后来发现这种方法只能处理0-9的数字
方法二:
但是这种只能每次输入一个数字

sum=0
while 1:
    sum+=int(input("please input a number:"))
    print (sum)

这里写图片描述

2.10

num=int(input("please input a number from 1 to 100:"))
while 1:
    if 1<=num and num<=100:
        print ("succeed")
        break
    else:
        print ("invalid input,try again!")
        num = int(input("please input a number from 1 to 100:"))

2.11

while 1:
    print ("1-->取五个数的和\n2-->取五个数的平均值\nx-->退出")
    option=input("please input your options:")
    if option=="1":
        print ("(1)输入五个数并求和")
        i=0
        sum=0
        for i in range(0,5):
            print('please input %d number' % (i + 1))
            sum+=int(input("the number:"))
            i+=1
            print ("the sum is:",sum)
    elif option=="2":
        sum=0
        i=0
        print("(2)取五个数的平均值")
        for i in range(0,5):
            print('please input %d number' % (i + 1))
            sum+=int(input("input the number: "))
            i+=1
        print (float(sum)/5)
    elif option=="x" or option=="X":
        print ("quit!")
        break
    else:
        print ("wrong option,please input agin")
        option = input("please input your options:")

2.12

后面的好像都挺简单的?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值