第3章 选择结构与循环结构
3.1 分析逻辑运算符“or”的短路求值特性。
答:
假设有表达式“表达式1 or 表达式2”,如果表达式1的值等价于True,那么无论表达式2的值是什么,整个表达式的值总是等价于True。因此,不需要再计算表达式2的值。
3.2 编写程序,运行后用户输入4位整数作为年份,判断其是否为闰年。如果年份能被400整除,则为闰年;如果年份能被4整除但不能被100整除也为闰年。
答:
1)Python 3.4.2代码
x = input('Please input an integer of 4 digits meaning the year:')
x = eval(x)
if x%400==0 or (x%4==0 and not x%100==0):
print('Yes')
else:
print('No')
2)Python 2.7.8代码
x = input('Please input an integer of 4 digits meaning the year:')
if x%400==0 or (x%4==0 and not x%100==0):
print 'Yes'
else:
print 'No'
3.3 编写程序,生成一个包含50个随机整数的列表,然后删除其中所有奇数。(提示:从后向前删。)
答:
1)Python 3.4.2代码
import random
x = [random.randint(0,100) for i in range(50)]
print(x)
i = len(x)-1
while i>=0:
if x[i]%2==1: