初学Python-第二章练习题

2-8 循环和操作符。创建一个包含五个固定数值的列表和元组,输出他们的和。然后修改代码为接受用户的输入数值。
while循环:

!/usr/bin/python

a = []
b = 0
c = 0
while b < 5:
a.append(int(raw_input(‘Input something: ‘)))
c = c + a[b]
b = b + 1
print c

for循环:

!/usr/bin/python

a = []
b = 0
c = 0
for x in range(5):
a.append(int(raw_input(‘Input something: ‘)))
c = c + a[b]
b = b + 1
print c

2-9 循环和操作符。创建一个包含五个固定数值的列表和元组,输出他们的平均值。

PS:重点在除法传统的除法 / 对整型除法会舍去小数点部分,而地板除法 // 不管什么类型的作数都会舍去小数点部分,所以需要使用浮点型进行计算,除非引用真正的除法(from future import division)

!/usr/bin/python

a = []
b = 0
c = 0
while b < 5:
a.append(float(raw_input(‘Input something: ‘)))
c = c + a[b]
b = b + 1
print c

2-10 带循环和条件判断。

!/usr/bin/python

while True:
num = int(raw_input(‘Please input a number between 1 and 100: ‘))
if 1 <= num <= 100:
print ‘Yes,you are right’
break
else:
print “Input number is not between 1 and 100”
continue

2-11 带文本的菜单,菜单项如下:(1)取五个数的和,(2)取五个数的平均值,(x)退出。

!/usr/bin/python

!-- coding:utf-8 --

while True:

print '(1) 取五个数到和'
print '(2) 取五个数到平均值'
print '(x) 退出'

select = raw_input('What want you to do: ')

if select == '1':
    a = []
    b = 0
    c = 0
    while b < 5:
        a.append(int(raw_input('Input number: ')))
        c = c + a[b]
        b = b + 1
    print c
elif select == '2':
    a = []
    b = 0
    c = 0
    while b < 5:
        a.append(float(raw_input('Input something: ')))
        c = c + a[b]
        b = b + 1
    print c / len(a)
elif select == 'x':
    break
else:
    continue
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值