概述
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
最后
以上就是野性超短裙为你收集整理的初学Python-第二章练习题!/usr/bin/python!/usr/bin/python!/usr/bin/python!/usr/bin/python!/usr/bin/python!-- coding:utf-8 --的全部内容,希望文章能够帮你解决初学Python-第二章练习题!/usr/bin/python!/usr/bin/python!/usr/bin/python!/usr/bin/python!/usr/bin/python!-- coding:utf-8 --所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复