import string
badChars = string.whitespace + string.punctuation # 标点、字符等defwords(stence):
words =[]for word in stence.split(' '):for char in word:if char in badChars:
word = word.replace(char,'')while word notin words andlen(word)!=0:#word = word.strip(',.!?') 只适用于句首和句中
words.append(word)else:continuereturn words
stence =input('Enter a stence:')
words(stence)
题2:turtle画美国国旗
# 画美国国旗import turtle as t
defdraw_strip(x,y,width,height,col):
t.penup()
t.goto(x,y)
t.pendown()
t.color(col,col)
t.begin_fill()for i inrange(4):if i%2==0:
t.forward(width)else:
t.forward(height)
t.right(90)
t.end_fill()defdraw_star(x, y, length, col):
t.penup()
t.goto(x,y)
t.pendown()
t.color(col, col)
t.begin_fill()for i inrange(5):
t.forward(length)
t.right(144)
t.end_fill()defdraw_USA_stars(origin_x, origin_y, height, color):
length =0.05858* height
H, E = height *0.0633,- height *0.0538# draw outer stars
pos_x, pos_y = origin_x + H - length/2, origin_y + E +0.009517* height
for row inrange(5):for col inrange(6):
draw_star(pos_x + col * H *2, pos_y + row * E *2, length, color)# draw inner stars
pos_x, pos_y = origin_x - length/2+ H *2, origin_y + E *2+0.009517* height
for row inrange(4):for col inrange(5):
draw_star(pos_x + col * H *2, pos_y + row * E *2, length, color)defdraw_USA_national_flag():
t.speed(0)
t.clear()
origin_x, origin_y =-200,200
height =130*2
width =13*19*2# draw stripsfor i inrange(13):if i%2==0:
color ='red'else:
color ='white'
draw_strip(origin_x, origin_y - height /13* i, width, height /13, color)# draw blue rectangle
draw_strip(origin_x, origin_y, width *0.4,7/13.0* height,'blue')# draw stars
draw_USA_stars(origin_x, origin_y, height,'white')
t.penup()
t.goto(-110,100)
draw_USA_national_flag()
题3:巴比伦平方根算法
# 巴比伦平方根算法import math
numStr =input('Find the square root of integer:')whilenot numStr.isdigit():print('Pay attention')
numStr =input('Find the square root of integer:')
number =int(numStr)
guessStr =input('Initial guess:')whilenot guessStr.isdigit():print('Pay attention')
guessStr =input('Initial guess:')
guessInt =int(guessStr)
originalGuess_int = guessInt
tolerance_float =float(input('What tolerance:'))
previous =0
count =0while math.fabs(previous - guessInt)> tolerance_float:
previous = guessInt
quotient = number/guessInt
guessInt =(quotient+guessInt)/2
count = count +1print('Square root of ',number,'is:',guessInt)print('Took',count,'reps to get it to tolerance:',tolerance_float)print('Starting from a guess of:',originalGuess_int)
Python 习题---列表字符串列表和字符串题1:创建一段文章中的单词列表,要求单词中无标点题2:turtle画美国国旗题3:巴比伦平方根算法列表和字符串题1:创建一段文章中的单词列表,要求单词中无标点import stringbadChars = string.whitespace + string.punctuation # 标点、字符等def words(stence): words = [] for word in stence.split(' '):