练习1:
#!/usr/bin/python3
# 根据输入的行数,绘制一个矩形
while True:
nums = int(input("请输入矩形的所占行数(大于2小于20):"))
if nums < 2 or nums > 20:
print("输入有误,请重新输入")
continue
else:
break
star = '* ' * nums
print(star)
for i in range(nums):
blank = ' ' * (nums - 2)
print('* ' + blank + '*')
print(star)
练习2:
#!/usr/bin/python3
# 判断是否为回文
print("判断是否是回文:")
while True:
string = input("请输入一个字符串:")
length = len(string)
if length < 2:
print("The length of input string should be longer than 2: length:%d" % (length,))
continue
else:
break
flag = True
for i in range(length // 2):
if string[i] != string[length - 1 - i]:
flag = False
break
if flag:
print("input: "%s " is huiwen" % (string,))
else:
print("input: "%s " is not huiwen" % (string,))
练习3:
#!/usr/bin/python3
# 输入一个整数,小球从此高度落下,每次反弹的距离是原始高度的一半,回弹高度小于0.01米时,
# 结束,求小球回弹的次数,和一共经过的距离
while True:
height = int(input("请输入小球落下的高度(大于1米):"))
if height < 1:
print("输入有误,请重新输入")
continue
else:
break
orgin = float(height)
count = 0
distance = 0
while orgin / 2> 0.01:
count += 1
# 每次下落时距离应该是落下的高度和回弹的高度值之和
distance += orgin + orgin / 2;
orgin /= 2
# 应该加上最后依次落下的高度
distance += orgin
print("从%d落下后,一共反弹%d次,一共经过的距离%f" % (height, count, distance))
练习4:
#!/usr/bin/python3
# 随机产生一注双色球号码:7个红球(范围1~33,不能重复)和1个篮球(1-16)
import random
reds = []
for i in range(7):
ball = str(random.randint(1, 33))
while ball in reds:
ball = str(random.randint(1, 33))
else:
reds.append(ball)
red = " ".join(reds)
blue = str(random.randint(1, 16))
rcolor = "31"
bcolor = "34"
print("The random number is ( 33[%s;40m%s 33[0m 33[%s;40m%s 33[0m)"
% (rcolor, red, bcolor, blue))
执行结果:
练习5:
#!/usr/bin/bash
# 产生100以内10个不同的随机数放入list1
# list1的每个值进行平方放入list2
# list1中50以内的数值放入list3
# list1中每个偶数进行平方加1,放入list4
import random
list1 = []
for i in range(10):
val = random.randint(1, 100)
while val in list1:
val = random.randint(1, 100)
else:
list1.append(val)
print("list1:" + str(list1))
list2 = [item ** 2 for item in list1]
list3 = [item for item in list1 if item < 50]
list4 = [item ** 2 + 1 for item in list1 if item % 2 == 0]
print("list1:" + str(list1))
print("list2:" + str(list2))
print("list3:" + str(list3))
print("list4:" + str(list4))



