练习一:求从1到100的数字中所有能既能被3整除,又能被5整合的数字有哪些。
for item in range(1,101):
if item % 3 ==0 and item % 5 == 0:
print(item)
练习二:输入一个字符串返回满足以下条件的字符串
■如果字符串长度大等于3,添加 'ing' 到字符串的末尾
■如果字符串是以 'ing' 结尾的,就在末尾添加 'ly'
■如果字符串长度小于3,返回原字符串
x = raw_input("请输入:")
if len(x) >= 3:
if 'ing' in x:
x = x + 'ly'
print x
else:
x = x + 'ing'
print x
elif len(x) < 3:
print x
练习三:判断回文
■输入一个数字,如果是回文数字,返回True,否则 返回False
■提示:回文:62426是回文数字
x = input("请输入一个数字:")
if (int(len(x))%2==0) and (x[0:int(len(x)/2)]==x[-1:int(-len(x)/2-1):-1]):
print('True')
elif (x[0:int((len(x)-1)/2)] == x[-1:int((-len(x)-1)/2):-1]):
print('True')
else:
print('False')
练习四:输入一个字符串,返回满足以下条件字符串
■找到字符串中的子串 'not' 和 'bad’
■如果 'bad' 出现在 'not' 后面,就把 'not' ... 'bad' 之间包含的所有字符串替换成 'good'
x = raw_input("请输入一个字符串:")
if ('not' in x) and ('bad' in x):
if (x.find('not') < x.find('bad')):
new_word = x.replace(x[(x.find('not')+3):(x.find('bad'))],'good')
print(new_word)
else:
print('not isn\'t before bad')
else:
print('not and bad is not exist at same time')
练习五:输入一个字符串,把字符串拆分成两个等分
■如果字符串长度是偶数,前一半和后一半的长度是相同的
■如果字符串长度是奇数,则多出的一个字符加到前一半,如:'abcde',前一半是'abc',后一半是'de'
x = raw_input("请输入一个字符串:")
if ((len(x)%2) == 0):
a = x[:int(len(x)/2)]
b = x[int(len(x)/2)+1:]
print a,b
else:
a = x[:int(len(x)/2)+1]
b = x[int(len(x)/2)+1:]
print a, b
练习六:输入一个字符串返回满足以下条件的字符串
■找出与字符串的第一个字母相同的字母,把它们替换成 '*',除了第一个字母本身以外
■例如: 输入'babble', 返回 'ba**le’
x = raw_input("请输入一个字符串:")
one = x[0]
for i in range(len(x)):
if x[i] == one:
y = x[1:int(len(x))].replace(x[i],'*')
s = x[0] + y
print s
输出结果如下:
练习七:输入一个字符串,返回满足以下条件的字符串
■由字符串的最前面两个字母和最后两个字母组成的字符串。
■例如: 'spring' 返回 'spng', 'is' 返回 'is’
■当输入的字符串长度小于2时,返回空字符串
x = raw_input("请输入一个字符串:")
if len(x) < 2:
print('')
elif len(x) == 2 or len(x) == 3:
print(x)
else:
f_two = x[:2] + x[-2:]
print f_two
输出结果如下:
练习八:落球计算
▪一球从100米高度自由落下,假设每次落地后反跳回原高度的一半;再落下,再弹起。请问第6次落地后会弹起多少米?
▪请分别使用for循环与while循环。并使用break与contiune流程控制关键字
h = 100
times = 0
while h > 0:
times = times + 1
h = h/2
if times == 6:
print('第%s次触地,高度为:%s'%(times,h))
break
输出结果如下:
x = input('请输入第一个数:')
y = input('请输入第二个数:')
s = []
sushu = []
if x < y:
pass
elif x == y:
print('两个数相等')
else:
x,y = y,x
for i in range(int(x)+1, int(y)):
for j in range(2,i):
if i % j == 0:
s.append(i)
for i in range(int(x),int(y)):
if i not in s:
sushu.append(i)
print(sushu)
输出结果如下: