Python语言程序设计(美-梁勇)第5章习题解答(英文)

合集下载

python程序设计基础课后习题答案(第五章)

python程序设计基础课后习题答案(第五章)

第五章答案5.2:实现i s o d d()函数,参数为整数,如果参数为奇数,返回t r u e,否则返回f a l s e。

def isodd(s):x=eval(s)if(x%2==0):return Falseelse:return Truex=input("请输入一个整数:")print(isodd(x))请输入一个整数:5True5.3:实现i s n u m()函数,参数为一个字符串,如果这个字符串属于整数、浮点数或复数的表示,则返回t r u e,否则返回f a l s e。

def isnum(s):try:x=eval(s)if((type(x)==int)|(type(x)==float)|(type(x)==complex)):return Trueelse:return Falseexcept NameError:return Falsex=input("请输入一个字符串:")print(isnum(x))请输入一个字符串:5True题5.4:实现m u l t i()函数,参数个数不限,返回所有参数的乘积。

def multi(x):xlist=x.split(",")xlist = [int(xlist[i]) for i in range(len(xlist))] #for循环,把每个字符转成int值num=1for i in xlist:num=num*iprint(num)s=input("请输入数字,并用,号隔开:")multi(s)请输入数字,并用,号隔开:5,420题5.5:实现i s p r i m e()函数,参数为整数,要有异常处理,如果整数是质数返回t u r e,否则返回f a l s e。

try:def isprime(s):i=2m=0for i in range(2,s-1):if(s%i==0):i+=1m+=1else:i+=1if(m>0):return Falseelse:return Trueexcept NameError:print("请输入一个整数!")s=eval(input("请输入任意一个整数:")) print(isprime(s))请输入任意一个整数:9False。

Python语言程序设计美梁勇第5章习题解答

Python语言程序设计美梁勇第5章习题解答

Python语言程序设计美梁勇第5章习题解答第5章习题解答一、选择题1. 在Python中,下列哪个不是有效的变量名?A. 1nameB. Name1C. _nameD. name_1正确答案:A. 1name2. 下列哪个运算符不是Python的算术运算符?A. +B. *C. /D. %正确答案:D. %3. 在Python中,下列哪个是赋值运算符?A. ==B. >C. +=D. and正确答案:C. +=4. 下列关于列表的描述中,哪个是错误的?A. 列表是一种有序的集合B. 列表可以包含不同的数据类型C. 列表的索引是从0开始的D. 列表可以通过下标修改其中的元素正确答案:B. 列表可以包含不同的数据类型5. 下列关于字典的描述中,哪个是正确的?A. 字典是一种有序的集合B. 字典的每个元素都有一个对应的键和值C. 字典的元素可以通过索引来访问D. 字典中的键必须是字符串类型正确答案:B. 字典的每个元素都有一个对应的键和值二、编程题1. 编写一个函数,接受一个字符串作为参数,返回该字符串的长度。

```pythondef calculate_length(string):return len(string)```2. 编写一个程序,要求用户输入两个数字,并计算它们的和、差、积和商,最后将结果输出。

```pythonnum1 = float(input("请输入第一个数字:"))num2 = float(input("请输入第二个数字:"))add = num1 + num2subtract = num1 - num2multiply = num1 * num2divide = num1 / num2print("两个数字的和:", add)print("两个数字的差:", subtract)print("两个数字的积:", multiply)print("两个数字的商:", divide)```3. 定义一个列表,其中包含5个学生的成绩,计算并输出这5个学生的平均成绩。

Python语言程序设计(美-梁勇)第7章习题解答(英文)

Python语言程序设计(美-梁勇)第7章习题解答(英文)

Python语⾔程序设计(美-梁勇)第7章习题解答(英⽂)Chapter 7 Objects and Classes1. See the section "Defining Classes for Objects."2. Define the initializer, create data fields, and define methods.3. Use a constructor4. The name of the initializer is __init__.5. The self refers to the object itself. Through self, themembers of the object can be accessed.6. The syntax for constructing an object isClassName(arguments)The arguments of the constructor match the parametersin the __init__ method without self.The constructor first creates an object in the memoryand then invokes the initializer.7. Initializer is a special method that is called whencreating an object.8.The object member access operator is the dot (.).9.You need to pass an argument in the constructor A() toinvoke the class A’s initializer.10.(a) The constructor should be defined as __init__(self).(b) radius = 3 should be self.radius = 311.count is 100times is 012.count is 0n is 113.__i is a private data field and cannot be accessed fromoutside of the class.14. Correct. The printout is Welcome.15.__on is a private data field and cannot be accessedoutside the class.The way to fix it is to add a getter method for theBoolean property as follows:class A:def __init__(self, on):self.__on = not ondef isOn(self):return self.__ondef main():a = A(False)print(a.isOn())main() # Call the main function16.T wo benefits: (1) for protecting data and (2) for easyto maintain the class.In Python, private data fields are defined with twoleading underscores.17.A dd two underscores as the prefix for the method name.18.S ee the text。

Python语言程序设计(美-梁勇)第3章(英文)习题解答

Python语言程序设计(美-梁勇)第3章(英文)习题解答

Chapter 3 Mathematical Functions, Strings, and Objects1.2.True3.r = math.radians(47)4.r = math.degrees(math.pi / 7)5.code = ord('1')code = ord('A')code = ord('B')code = ord('a')code = ord('b')ch = chr(40)ch = chr(59)ch = chr(79)ch = chr(85)ch = chr(90)6.print("\\")print("\"")7.\u00788.D9.2510.title = "chapter " + str(1)11.52312.An object is an entity such as a number, a string, a student, a desk, and a computer. Eachobject has an id and a type. Objects of the same kind have the same type.You can perform operations on an object. The operations are defined using functions. The functions for the objects are called methods in Python13.To find the id for an object, use the id(object) function. To find the type for an object, usethe type(object) function.14.(b)15.s.lower() is "\tgeorgia\n"s.upper() is "\tGEORGIA\n"16.s.strip() is "Good\tMorning"17.The return returned from invoking the format function is a string.18.The width is automatically increased to accommodate the size of the actual value.19.57.46812345678.957.4057.4020.5.747e+011.2e+075.74e+015.74e+0121.5789.4685789.4685789.405789.405789.4022.45.747%45.747%23.45452d2d24.Programming is funProgramming is funProgramming is fun25.turtle.home()26.turtle.dot(3, "red")27.Draw a square28.turtle.speed(number) # Set a number between 1 to 10, the larger, the faster29.turtle.undo()30.turtle.color("red")31.turtle.begin_fill()turtle.color("red")turtle.circle(40, steps = 3) # Draw a triangle ...turtle.end_fill()32.turtle.hide()。

python核心编程第5章课后练习题

python核心编程第5章课后练习题

python核⼼编程第5章课后练习题5-2. 操作符(a)写⼀个函数,计算并返回两个数的乘积(b)写⼀段代码调⽤这个函数,并显⽰它的结果def twoNumRide(a, b):'计算并返回两个数的乘积'c = a * breturn cif __name__ == '__main__':cj = twoNumRide(2, 3)print(cj)----------------------------------------------------------------------------------------------------------------5-3. 标准类型操作符,写⼀段脚本,输⼊⼀个测验成绩,根据下⾯标准,输出他们的评分成绩(A-F)A:90~100 B:80~89 C:70~79 D:60~69 F<60def queryScore(num):"""5-3. 标准类型操作符,写⼀段脚本,输⼊⼀个测验成绩,根据下⾯标准,输出他们的评分成绩(A-F)A:90~100 B:80~89 C:70~79 D:60~69 F<60:param num::return:"""if 90<= num <= 100:print('A')elif 80<= num <=89:print('B')elif 70<= num <=79:print('C')elif 60<= num <=69:print('D')else:print('F')if __name__ == '__main__':score = input('请输⼊0~100的分数:')queryScore(int(score))--------------------------------------------------------------------------------------5-4 取余。

python核心编程第二版课后题答案第五章

python核心编程第二版课后题答案第五章

def ji(x1, x2):'''5-2 返回两个数的乘积'''return x1*x2def grade(score):'''5-3 输入乘积0~100份之内,返回评分'''if 90<=score<=100:return 'A'elif 80<=score<=89:return 'B'elif 70<=score<=79:return 'C'elif 60<=score<=69:return 'D'elif 60>score:return 'F'def isleapyear(year):'''5-4 输入年份,判断是否是闰年,年份小于172800年有效''' if (year%4==0 and year%100 !=0) or year%400==0: return Truereturn Falsedef minmoney(money):'''5-5 将任意一个美元(小于1美元)分成硬币由1美分,5美分,10美分,25美分且硬币数量是最少的一种组合方式'''m1 = int(money*100)m25 = m1/25m1 -= m25*25m10 = m1/10m1 -= m10*10m5 = m1/5m1 -= m5*5# 1美分,5美分,10美分,25美分return [m1,m5,m10,m25]def computer(cmd):'''5-6 输入类似x * y 这样的式子,自动获得值'''ops = ['+','-','**','/','%','*']for op in ops:if op in cmd:cmds = cmd.split(op)cmds[0]=float(cmds[0])cmds[1]=float(cmds[1])if op == '+':return sum(cmds)if op == '-':return cmds[0]-cmds[1]if op == '**':return pow(cmds[0],cmds[1])if op == '/':return cmds[0]/cmds[1]if op == '%':return cmds[0]%cmds[1]if op == '*':return cmds[0]*cmds[1]def tax(value, tax=0.17):'''5-7 输入价格,获得营业税,这里假设税金是20%''' import decimalvalue = decimal.Decimal(str(value))tax = decimal.Decimal(str(tax))return value*taxdef square(x,y=None):'''5-8(a)-1 求正方形或者长方形面积'''if y == None:y = xreturn x*ydef cube(x,y=None,h=None):'''5-8(a)-2 求立方体的体积'''if y==None:y=xif h==None:h=xreturn x*y*hdef circle(r):'''5-8(b)-1 求圆的面积'''import mathreturn 2*math.pi*rdef sphere(r):'''5-8(b)-2 求球的体积'''import mathreturn 4./3*math.pi*r**3def f2c(f):'''5-10 华氏度转摄氏度FahrenheitDegree to CelsiusDegree''' return (f-32)*(5./9)def even(l):'''5-11(a) 求列表中数字的偶数'''rl = []for i in l:if i%2==0:if i in rl:continuerl.append(i)return sorted(rl)def odd(l):'''5-11(b) 求列表中数字的奇数'''rl = []for i in l:if i%2 != 0:if i in rl:continuerl.append(i)return sorted(rl)def individe(x,y):'''5-11(d) 是否能整除'''if x%y==0:return Truereturn Falsedef numinfo():'''5-12 输出当前系统关于数字的范围'''import sysl = {}maxint = sys.maxintminint = -maxintmaxlong = sys.maxsizeminlong = -maxlongmaxfloat = sys.float_info.maxminfloat = sys.float_info.minl['maxint'],l['minint'],l['maxlong'],l['minlong'],l['maxfloat'],l['minfloat'] = \ maxint,minint,maxlong,minlong,maxfloat,minfloatreturn ldef time2minute(time):'''5-13 将由小时和分钟表示的时间转换成只有分钟的时间'''times = time.split(':')return int(times[0])*60+int(times[1])def banktax(interest):'''5-14 返回年回报率'''import decimalreturn (decimal.Decimal(1)+decimal.Decimal(str(interest)))**365def gcd(num1,num2):'''5-15-1 最大公约数'''mins = num1cd = Noneif num2 < num1:num1,num2 = num2,num1cds = []for i in range(1, num1+1):if num1%i == 0:cds.append(i)cdslen = len(cds)for i in range(0,cdslen):if num2%cds[(cdslen-i-1)]==0:cd = cds[(cdslen-i-1)]breakreturn cddef lcm(num1,num2):'''5-15-2 最小公倍数'''# 需要gcd 函数cd = gcd(num1,num2)a = num1/cdb = num2/cdreturn cd*a*bdef payment(startmoney,monthout):'''5-16 给定初始金额和月开销数'''# 最大序号max = float(startmoney)/monthoutif not max.is_integer():max+=1max = int(max)# 格式化输出sapp = 3 - (len(str(startmoney)) - len(str(int(startmoney)))) # 3其实就是'.00' 的长度,sapp表示startmoney增加mapp = 3 - (len(str(monthout)) - len(str(int(monthout)))) # 后面其实是输入数据的数字长度减去他的整型部分slen = str(len(str(startmoney))+sapp) # startmoney 长度加上小数部分的补差长度mlen = str(len(str(monthout))+mapp) # monthout lengthstring = '%d\t$%'+mlen+'.2f\t$%'+slen+'.2f' # 输出格式L1, L2, L3 = len(str(max)), int(mlen)+1, int(slen)+1 # L1 L2 L3 第一第二第三栏宽度if L1 <5:L1 = 5print 'Amount Remaining'print 'Pymt#'.center(L1)+'\t'+'Paid'.center(L2)+'\t'+'Balance'.center(L3)print '-'*L1+'\t'+'-'*L2+'\t'+'-'*L3print string %(0,0,startmoney)for i in range(1,max+1):if startmoney>=monthout:startmoney-=monthoutelse:monthout = startmoneystartmoney = 0print string %(i,monthout,startmoney)def randomlist():'''5-17 生成N个元素由随机数n组成的列表其中1<N<=100 0<=n<=231 -1并排序'''import randomN = [i for i in xrange(2,101)]n = [i for i in xrange(-1,232)]Nn = random.choice(N)Return = []for i in xrange(0,Nn):num = random.choice(n)n.remove(num) # 从n 列表中删除已经选过的数字Return.append(num)return sorted(Return)。

Python程序设计第五章知识点概要和任务单

Python程序设计第五章知识点概要和任务单
3、字典元素的修改:
字典变量名[键值]=赋给新值
4、字典元素的添加:
字典变量名[新增加的键值]=新键值对应的内容
或者 字典变量名.update({新增键值1:新键值1对应内容1,...,新增键值n:新键值n对应内容})
5、字典元素的删除:
del字典变量名[要删除的键值]
6、字典元素的遍历:
具体任务:
例1:正确的字典定义:d={1:100,2:200,3:300}或者d={"a":100,(1,):200,[3]:300}
例2:错误的字典定义:d={"a":100,(1,):200,[3]:300}(因为选择列表[3]作为键值,故出错)
例3:字典中元素的访问
>>> d={0:"sprint",1:"summer",2:"autumn",3:"winter"}
二、分节知识点概述及任务要求:
5.1python中字典数据类型。
知识点概要:
1、字典的定义:
字典变量名={键值1:键值1对应的内容,......键值n:键值n对应的内容}
注意:键值一定是不可变的量,如数字,字符串,或元组等,像列表这样的可变量当不了键值。
2、字典中元素的访问:
字典变量名[键值]或者字典变量名.get(键值)
>>> d(显示新增元素后字典d的内容)
{0: 'sprint', 1: 'summer', 2: 'autumn', 3: 'winter', 4: 'qtw'}
例2:
{0: 'sprint', 1: 'summer', 2: 'autumn', 3: 'winter', 4: 'qtw'}

Python语言程序设计习题与答案

Python语言程序设计习题与答案

一、单选题1、字符串是一个字符序列,例如,字符串s,从右侧向左第3个字符用什么索引?A.s[3]B.s[-3]C.s[0:-3]D.s[:-3]正确答案:B2、获得字符串s长度的方法是什么?A.s.len()B.s.lengthC.len(s)D.length(s)正确答案:C3、字符串函数strip()的作用是什么?A.按照指定字符分割字符串为数组B.连接两个字符串序列C.去掉字符串两侧空格或指定字符D.替换字符串中特定字符正确答案:C4、"abc"的长度是3,"老师好"的长度是多少?A.1B.3C.6D.9正确答案:B5、字符串是一个连续的字符序列,用什么方式打印出可以换行的字符串?A.使用转义符\\B.使用\nC.使用空格D.使用“\换行”正确答案:B6、Python中布尔变量的值为A.0,1B.真,假C.T,FD.True,False正确答案:D7、Python通过什么来判断操做是否在分支结构中A.缩进B.冒号C.花括号D.括号正确答案:A8、对负数取平方根,即使用函数math.sqrt(x),其中x为负数,将产生A.虚数B.程序崩溃C.什么都不产生D.ValueError错误正确答案:D9、以下的布尔代数运算错误的是A.not (a and b) == not (a) and not (b)B.(True or False) == TrueC.(True or x) == TrueD.(False and x) == False正确答案:A10、以下不可能出现在or操作真值表中的是A.F or T = TB.T or T = TC.F or F = TD.T or F = T正确答案:C11、Python语言中,与函数使用相关的保留字是哪个?A.passB.forC.evalD.def正确答案:D12、以下哪个不是函数的作用?A.降低编程复杂度B.复用代码C.增强代码可读性D.提高代码执行速度正确答案:D13、假设函数中不包含global保留字,下面对于改变参数值的说法,哪个是不正确的?A.参数的值是否被改变,与函数中对变量的操作有关,与参数类型无关。

Python程序设计习题答案 (5)

Python程序设计习题答案 (5)

第五章课后习题1. 在操作字符串时,需要把两个或多个字符串连接成一个字符串,可以使用对于这种需求,连接操作符或者字符串对象方法实现。

【参考答案】+ join()2.编写程序,由给定字符串随机生成一个6位密码。

【参考答案】import randoms = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*"pwd = ''.join((random.choice(s) for i in range(6)))print(pwd)3.编写程序,把A bad workman quarrels with his Tools.中的T替换为t。

【参考答案】方法一:s = 'A bad workman quarrels with his Tools.'s = s.replace('T','t')print(s)方法二:import res = 'A bad workman quarrels with his Tools.'result = re.sub(r'\bT', 't', s)print(result)4. 简单说明什么是正则表达式以及其作用。

【参考答案】正则表达式是用来描述或者匹配一系列符合某个句法规则的字符串。

在很多文本编辑器或其他工具里,正则表达式通常被用来检索或替换那些符合某种模式的文本内容。

5.有一国外电话号码“2004-959-559 # 这是一个国外电话号码”,编写程序,去除其中的注释和“-”。

【参考答案】import rephone = "2004-959-559 # 这是一个国外电话号码"# 删除字符串中的Python注释num = re.sub(r'#.*$', "", phone)print("电话号码是: ", num)# 删除非数字(-)的字符串num = re.sub(r'\D', "", phone)print("电话号码是: ", num)。

python第5章IF语句课后习题答案

python第5章IF语句课后习题答案

Solutions - Chapter 55-3: Alien Colors #1Imagine an alien was just shot down in a game. Create a variable called alien_color and assign it a value of 'green', 'yellow',or 'red'.∙Write an if statement to test whether the alien’s color is green.If it is, print a message that the player just earned 5 points.∙Write one version of this program that passes the if test and another tha fails. (The version that fails will have no output.) Passing version:Output:Failing version:(no output)5-4: Alien Colors #2Choose a color for an alien as you did in Exercise 5-3, and writean if-else chain.∙If the alien’s color is green, print a statement that the player just earned 5 points for shooting the alien.∙If the alien’s coor isn’t green, print a statement that the player just earned 10 points.∙Write one version of this program that runs the if block and another that runs the else block.if block runs:Output:else block runs:Output:5-5: Alien Colors #3Turn your if-else chain from Exercise 5-4 intoan if-elif-else cahin.∙If the alien is green, print a message that the player earned 5 points.∙If the alien is yellow, print a message that the player earned 10 points.∙If the alien is red, print a message that the player earned 15 points.∙Write three versions of this program, making sure each message is printed for the appropriate color alien.Output for 'red' alien:5-6: Stages of LifeWrite an if-elif-else cahin that determines a person’s stage of life. Set a value for the variable age, and then:∙If the person is less than 2 years old, print a message that the person is a baby.∙If the person is at least 2 years old but less than 4, print a message that the person is a toddler.∙If the person is at least 4 years old but less than 13, print a message that the person is a toddler.∙If the person is at least 13 years old but less than 20, print a message that the person is a toddler.∙If the person is at least 20 years old but less than 65, print a message that the person is a toddler.∙If the person is age 65 or older, print a message that the person is an elder.Output:5-7: Favorite FruitMake a list of your favorite fruits, and then write a series of independent if statements that check for certain fruits in your list.∙Make a list of your three favorite fruits and callit favorite_fruits.∙Write five if statements. Each should check whether a certainkind of fruit is in your list. If the fruit is in your list, the if blockshould print a statement, such as You really like bananas!Output:5-8: Hello AdminMake a list of five or more usernnames, including the name 'admin'.Imagine you are writing code that will print a greeting to each user after they log in to a website. Loop through the list, and print a greeting to each user:∙If the username is 'admin', print a special greeting, such as Hello admin, would you like to see a status report?∙Otherwise, print a generic greeting, such as Hello Eric, thank you for loggin in again.Output:5-9: No UsersAdd an if test to hello_admin.py to make sure the list of users is not empty.∙If the list is emtpy, print the message We need to find some users!∙Remove all of the usernames from your list, and make sure the correct message is printed.Output:5-10: Checking UsernamesDo the following to create a program that simulates how websites ensure that everyone has a unique username.∙Make a list of five or more usernames called current_users.Make another list of five usernames called new_users. Makesure one or two of the new usernames are also inthe current_users list.∙Loop through the new_users list to see if each new username has already been used. If it has, print a message that theperson will need to enter a new username. If a username has not been used, print a message saying that the username isavailable.∙Make sure your comparison is case insensitive. If 'John' has been used, 'JOHN' should not be accepted.Output:Note: If you’re not comfortable with list comprehensions yet, thelist current_users_lower can be generated using a loop:5-11: Ordinal NumbersOrdinal numbers indicate their position in a list, such as 1st or 2nd. Most ordinal numbers end in th, except 1, 2, and 3.∙Store the numbers 1 through 9 in a list.∙Loop through the list.∙Use an if-elif-else chain inside the loop to print the proper ordinal ending for each number. Your output should read "1st2nd 3rd 4th 5th 6th 7th 8th 9th", and each result should be ona separate line.Output:。

Python语言程序设计(美-梁勇)第6章习题解答(英文)

Python语言程序设计(美-梁勇)第6章习题解答(英文)

Chapter 6 Functions1.At least three benefits: (1) Reuse code; (2) Reduce complexity; (3) Easy to maintain.2. See the Sections 6.2 and 6.3 on how to declare and invoke functions.3. return num1 if (num1 > num2) else num24. True: a call to a function with a void return type is always a statement itself.False: a call to a value-returning function is always a component of an expression.5. A syntax error occurs if a return statement is not used to return a value in a value-returning function. You can have a return statement in a void function, whichsimply exits the function. So, this function is OK, although the return statement isnot needed at all.6. See Section 6.2.puting a sales commission given the sales amount and the commission ratedef getCommission(salesAmount, commissionRate):returns a valuePrinting a calendar for a monthdef printCalendar(month, year):Computing a square rootdef sqrt(value):returns a valueTesting whether a number is even and return true if it isdef isEven(value):returns a valuePrinting a message for a specified number of timesdef printMessage(message, times):Computing the monthly payment, given the loan amount,number of years, and annual interest rate.def monthlyPayment(loanAmount, numberOfYears,annualInterestRate):returns a valueFinding the corresponding uppercase letter given a lowercase letter.def getUpperCase(char letter):returns a value8.Line 2, 5-10: not indented correctly.9.None10.The min function should return a value.11.Using positional arguments requires the arguments be passed in the same order as their respective parameters in the function header. You can also call a function using keyword arguments, passing each argument in the form name=value.12.f(1, p2 = 3, p3 = 4, p4 = 4) # Correctf(1, p2 = 3, 4, p4 = 4) # Not Correctf(p1 = 1, p2 = 3, 4, p4 = 4) # Not Correctf(p1 = 1, p2 = 3, p3 = 4, p4 = 4) # Correctf(p4 = 1, p2 = 3, p3 = 4, p1 = 4) # Correct13. "Pass by value" is to pass a copy of the reference value to the function.14. Yes.15.(A) The output of the program is 0, because the variable max is not changed byinvoking the function max.(B)22 42 4 82 4 8 162 4 8 16 32(C)Before the call, variable times is 3n = 3Welcome to CS!n = 2Welcome to CS!n = 1Welcome to CS!After the call, variable times is 3(D)The code printsi is 11i is 22 1i is 3and then it is an infinite loop.16.17.(A) 23.424(B) 36518.x and y are not defined outside the function.19.Yes. The printout isy is 120.1 25 21 244 521.The parameter with non-default Argument must be defined before the parameter with default arguments.22.The later function definition will replace the previous function definition.23.Yes. The printout is14 4 45 1.824.random.randint(34, 55)25.chr(random.randint(ord('B'), ord('M')))26.5.5 + random.random() * 5027.chr(random.randint(ord('a'), ord('z')))。

Python语言程序设计(美-梁勇)第5章习题解答

Python语言程序设计(美-梁勇)第5章习题解答

Python语言程序设计(美-梁勇)第5章习题解答第5章循环5.1分析下面的代码。

在A、B、C处count<100总为true,总为false,还是有时true有时false?Count = 0While count < 100:#APrint ‘’pramming is fun!Count += 1#B#C答:A处一直为true,B处有时为真有时为假,C处一直为假。

5.2如果把程序清单5-3中的第8行的guess初始化为0,错在哪里?答:产生的随机数有可能为0,此时循环将不会执行。

5.3下边的循环体被重复了多少次?每次循环的输出结果是多少?答:a、循环体被重复无限次,没有输出结果;B、循环体被重复无限次,没有输出结果;c、循环体被执行了9次,输出结果为2\n 4\n 6\n 8(4行)5.4指出下面代码的错误:答:a、b均为死循环,c没有循环体。

5.5假设输入值为“2 3 4 5 0”(每行一个数),下面代码的输出结果是什么?答:5 0(每行一个数)5.6假设输入值为“2 3 4 5 0”(每行一个数),下面代码的输出结果是什么?答:14 4(每行一个数)5.7你能把任何一个for循环转换为while循环吗?列出for循环的优点。

答:可以。

For循环的优点是更加简洁和可实现性。

编译器产生的代码可以比while循环更高效的执行。

5.8将下面的for循环转换为while循环。

Sum = 0 答:sum = 0For i in range(1001): i = 0Sum = sum + i while i < 1001:Sum = sum + ii += 15.9你能将任意的while循环转换成for循环吗?将下面这个while 循环转换成for循环。

i = 1 答:sum = 0Sum = 0 for i in range(1, 1000):While sum < 1000: sum = sum + i Sum = sum + ii +=15.10统计下面循环的迭代次数:答:a、n次b、n次c、n - 5 d、ceil((n - 5) / 3)5.12如果你知道一个数n1的公约数不可能大于n1/2,你就可以试图使用下面的循环来改善你的程序:K = 2While k <= n1 / 2 and k <= n2 / 2:If n1 % k == 0 and n2 % k ==0:gcd = kK += 1这个程序是错误的,你能找出原因吗?答:当n1=3,n2=3时,程序找出的最大公约数是1,与正确答案不符。

《Python程序设计》课后习题参考答案

《Python程序设计》课后习题参考答案

第1章一、选择题1.B2.D3.C4.C二、简答题1.(1)简单易学(2)解释性(3)可移植性(4)可扩展性(5)面向对象(6)丰富的库2.(1)Web应用开发(2)自动化运维(3).网络安全(4).网络爬虫(5).游戏开发(6).数据分析(7).人工智能三、编程题1.print('Hello, World!.')2.print('***********************************')print('\t\tHello Python World!')print('***********************************')第2章2.6习题一、选择题1.C2.D3.C4.A5.B6.D二、填空题2.26 2.type()3.274. -5.75; -6 5. False三、简答题1.(1)变量名必须由字母、数字、或者下划线(_)组成。

(2)不能使用空格、连字符、标点符号、引号等其他特殊字符。

(3)以字母或下划线开头,但不能以数字开头(4)严格区分大小写。

(5)要避免与Python关键字和函数名冲突2. 见表2.4.第3章3.4综合实验#1s1 = " keep on going never give up "s2 = s1.capitalize()print(s2)#2s3 = s2.strip()print(s3)#3print (s3.endswith('up'))#4print (s3.startswith('on'))#5print (s3.replace('e','aa'))#6print (s3.split('n'))#7print (s3.upper())#8n1 = 'Lily'print ('%s says: %s.'%(n1,s3))#9print (s3.center(40,'#'))#10print (s3.count('e'))#11print (s3.split())#12print ('/'.join(s4))#13print (' '.join(s4[::-1]))3.5 习题一、选择题1.B2.D3.C4.C二、填空题1. 'moon'2. 'shipfriend'3. 54. 'bEIjING'5. spam三、编程题1.str1 = 'I want to go to Beijing, Berli and Beijing this year. How about you?' str2 = str1.split()str2 = ' '.join(str2)print (str2)2.思路:(1).变量名的第一个字符是否为字母或下划线(2).如果是,继续判断--> 4(3).如果不是,报错(4).依次判断除了第一个字符之外的其他字符(5).判断是否为字母数字或者下划线while True:s = input('请输入字符(q退出):')if s == 'q':exit()#判断字符串第一个变量是否满足条件if s[0].isalpha() or s[0] == '_':for i in s[1:]:#判断判断除了第一个元素之外的其他元素是否满足条件if i.isalnum() or i == '_':continueelse:print('不合法')breakelse:print('合法')else:print('不合法')3.#!/usr/bin/env python#coding:utf-8s = input("输入:")s1 = s.split(" ")s2 = s1[0].upper()s3 = s1[-1].upper()print (s2.count(s3))4.s = input('input a string:\n')letters, space, digit, others = 0,0,0,0for c in s:if c.isalpha():letters += 1elif c.isspace():space += 1elif c.isdigit():digit += 1else:others += 1print ('char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others))第4章4.4 综合实验#01fav_city = []#02fav_city.append('Qinghai')fav_city.append('Chengdu')fav_city.append('Dalian')fav_city.append('Xizang')fav_city.append('Haerbin')print (fav_city)#03fav_city[0] = 'Qingdao'#04fav_city.insert(2,'Kunming')#05del fav_city[0]#06fav_city.remove('Xizang')#07fav_city.sort()#08fav_city.reverse()#09for city1 in fav_city:print (city1)#10tuple_city = tuple(fav_city)#11len(tuple_city)4.5 习题一、选择题1.D2.A3.B4.D5.C二、填空题1.[123,22, 123,22]2.x = [1,3,5,7,9]3. [11,22,33,11]4. Flase5. b= [::2]6. (6,)三、编程题#1import randomx = [random.randint(0,100) for i in range(10)]x.sort()print (x)#2.list1 = ['Hollywood', 'Mexico', 'New Delhi', 'Tokyo'] item = list1.pop(0)list1.append(item)print (list1)#3a = int(input('a:'))for b in x:if a < b:x.insert(x.index(b),a)breakelse:x.append(a)print (x)#3x.pop()x[:5] = sorted(x[:5] ,reverse = True)x[5:] = sorted(x[5:])print (x)4.#列表推导法list1 = [22,11,33,22,44,33]temp_list=[]for x in list1:if x not in temp_list:temp_list.append(x)print (temp_list) #输出结果未排序#排序方法list1 = [22,11,33,22,44,33]list2 = sorted(list1)temp_list = []i = 0while i < len(list2):if list2[i] not in temp_list:temp_list.append(list2[i])else:i += 1print (temp_list) #输出结果已排序第5章字典综合实验1.Qing_Hai = ['qinghai','xining','青',8,'810000']Si_Chuan = ['sichuan','chengdu','川',21,'610000']Gan_Su = ['gansu','lanzhou','陇',14,'730000']Ning_Xia = ['ningxia','yinchuan','宁',5,'750000']Nei_MengGu = ['neimenggu','huhehaote','内蒙古',12,'010000'] Shaan_Xi = ['shaanxi','xian','陕',10,'710000']Shan_Xi = ['shanxi','taiyuan','晋',11,'030000']He_Nan = ['henan','zhengzhou','豫',18,'450000']Shan_Dong = ['shandong','jinan','鲁',16,'250000']provinces = [Qing_Hai,Si_Chuan,Gan_Su,Ning_Xia,Nei_MengGu,Shaan_Xi,Shan_Xi,He_Nan,Shan_Dong] Yellow_River_basin = {}for province in provinces:Yellow_River_basin[province[0]] = province[1:]print(Yellow_River_basin)2.# 遍历嵌套字典的键for key in Yellow_River_basin.keys():print(key)# 遍历嵌套字典的值for value in Yellow_River_basin.values():print(value)# 遍历嵌套字典的键值对for key, value in Yellow_River_basin.items():print(key+"'s Capital is : %s "%value[0]+" For_short is : %s "%value[1]+"Area_manage is : %d个"%value[2]+"Postal_code is : %s"%value[3])3.for provinc in Yellow_River_basin.keys():if provinc == 'sichuan':Yellow_River_basin[provinc] = ['chengdu', '蜀', 21, '610000']elif provinc == 'gansu':Yellow_River_basin[provinc] = ['lanzhou', '甘', 14, '730000']elif provinc == 'shaanxi':Yellow_River_basin[provinc][1] = '秦'print(Yellow_River_basin)4qinghai = {'name':'QingHai','capital':'XiNing','for_short':'青','area_manage':8}sichuang = {'name':'SiChuan','capital':'ChengDu','for_short':'川','area_manage':21}gansu = {'name':'GanSu','capital':'LanZhou','for_short':'陇','area_manage':14}ningxia = {'name':'NingXia','capital':'YinChuan','for_short':'宁','area_manage':5}neimenggu = {'name':'Neimenggu','capital':'HuheHaote','for_short':'内蒙古','area_manage':12} shaanxi= {'name':'ShaanXi','capital':'XiAn','for_short':'陕','area_manage':10}shanxi = {'name':'ShanXi','capital':'TaiYuan','for_short':'晋','area_manage':11}henan = {'name':'HeNan','capital':'ZhengZhou','for_short':'豫','area_manage':18}shandong = {'name':'ShanDong','capital':'JiNan','for_short':'鲁','area_manage':16}basin_list = [qinghai,sichuang,gansu,ningxia,neimenggu,shaanxi,shanxi,henan,shandong] Postal_Code = ['810000','610000','730000','750000','010000','710000','030000','450000','250000']print(basin_list)5for province_num in range(len(basin_list)):basin_list[province_num]['postal_code'] = Postal_Code[province_num]print(basin_list)第5章综合实验一、选择题1.B2.C3.B4.D5.D二、简答题1.(1)字典的键(key)具有唯一性。

Java语言程序设计(基础篇)原书第十一版 梁勇 第5、6章 课后题答案

Java语言程序设计(基础篇)原书第十一版 梁勇 第5、6章 课后题答案
int month=in.nextInt();
System.out.println("Month\t\tCD Value");
for (int i=1;i<month+1;i++){
money=money+money*rate/1200;
System.out.println(i+"\t\t"+money);
}
mean=sum/10;
double a=num-Math.pow(sum,2)/i;
standard=Math.pow(a/(i-1),0.5);
System.out.println("平均值是:"+mean);
System.out.print("方差是:"+standard);
}
}
5.47商业:检测ISBN-13
System.out.print("请输入10个数:");
Scanner in=new Scanner(System.in);
for (i=0;i<10;i++) {
list[i] = in.nextDouble();
sum += list[i];
num += Math.pow(list[i],2);
char d7=str.charAt(6);char d8=str.charAt(7);char d9=str.charAt(8);
char d10=str.charAt(9);char d11=str.charAt(10);char d12=str.charAt(11);

Python语言程序设计(工作手册式) 作业习题及答案 第五章

Python语言程序设计(工作手册式) 作业习题及答案 第五章

第五章一、单选题(共2题,10分)1、关于IiSt和String下列说法错误的是:A、IiSt可以存放任意类型。

B、1ist是一个有序集合,没有固定大小。

C、用于统计string中字符串长度的函数是string.IenO。

D、string具有不可变性,其创建后值不能改变。

正确答案:D2、关于字符串下列说法错误的是()A、%f用于格式化输出浮点类型数据B、字符串的子串查找函数find。

只能返回第一个符合子串的位置,否则返回为0。

C、既可以用单引号,也可以用双引号创建字符串D、在三引号字符串中可以包含换行回车等特殊字符正确答案:B二、简答题(共38题,190分)1、【字符串基础训练】在当前目录下创建一个"test.Iog w文件。

在test文件中写入w.查找当前文件操作标记的a He11oWord wβ在test文件“He11oWord“后面输入"Python位置(提示:Seek())。

把文件操作符的位置移动最前面。

以二进制方式输出test文件。

关闭test文件。

删除test文件。

编写代码输出当前Pythor1脚本工作的目录路径。

正确答案:2、【文件内容合并】有两个磁盘文件A和B,各存放一行字母,要求编写代码实现将这两个文件中的信息合并,并按字母先后顺序排列,最后输出到一个新文件C中。

正确答案:3、【文件存储】从键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件'test'中保存,并实现循环输入,直到输入一个#为止。

正确答案:4、写出下面程序的功能。

假设文件a origina1”内容为Upgrcynpmepyk.Writeaprogram.那么文件αsavetoo”内存储的内容应该是什么?正确答案:5、使用之前所学的循环语句以及列表完成这样的一个输出结果(字典方法可能能更加方便的完成)正确答案:6、编写函数判断两个字符串是否包含相同的字母正确答案:7、现有字符串str=,thisisstringexamp1e....wow 编写代码把字符串的atex1分别改为12345并去除其中的s和h正确答案:8、添加指定长度字符串如a=“12345"b="abcde”从键盘读取n,若n=1则输出字符串“12345a”若n=2则输出字符串“12345ab”正确答案:9、已知a="aAsmr3idd4bgs7D1sf9eAF”请将a字符串的数字取出,并输出成一个新的字符串。

Python语言程序设计(美-梁勇)第4章习题解答(英文)

Python语言程序设计(美-梁勇)第4章习题解答(英文)

Chapter 4 Selections1. <, <=, ==, !=, >, >=2. Yes. i becomes 1, j becomes 0, b1 becomes True, and b2 becomes Flase.3. random.randrange(0, 20) or random.randint(0, 19)4. random.randrange(10, 20) or random.randint(10, 19)5. random.randrange(10, 50 + 1) or random.randint(10, 50)6. random.randrange(0, 2) or random.randint(0, 1)7.if y > 0:x = 18.if score > 90:pay *= 1.039.if score > 90:pay *= 1.03else:pay *= 1.0110.If number is 30,(a) displays30 is even30 is odd(b) displays30 is evenIf number is 35,(a) displays35 is odd(b) displays35 is odd11. Note: else matches the second if clause. The output is “x is 3” if x = 3 and y = 2. The o utput is “z is 7” if if x = 3 and y = 4. No output if if x = 2 and y = 2.12. Note: else matches the first if clause. The output is “x is 2” if x = 2 and y = 4. No output if if x = 3 and y = 2.The output is “z is 6” if if x = 3 and y = 3.13.Consider score is 90, what will be the grade? The conditions are tested in the wrong orders.14.(A) and (C) are equivalent. (B) and (D) are incorrectly indented.15.newLine = (count % 10 == 0)16.Both are correct. (B) is better. Both conditions in (A) are tested. In (B) the condition is tested only once.17.For number is 14, (a) displays:14 is even(b) displays14 is evenFor number is 15, (a) displays:15 is multiple of 5(b) displays15 is multiple of 5For number is 30, (a) displays:30 is even30 is multiple of 5(b) displays30 is even18.Yes19.This program will have a runtime error, because tax will not be created.20. (true) and (3 > 4)Falsenot(x > 0) and (x > 0)False(x > 0) or (x < 0)True(x != 0) or (x == 0)True(x >= 0) or (x < 0)True(x != 1) == not (x == 1)True21. (x > 1) and (x < 100)22. ((x > 1) and (x < 100)) or (x < 0)23.x >= y >= 0 Falsex <= y >= 0 Truex != y == 5 True(x != 0) or (x == 0) True24.Yes25.If ch is 'A', the expression is true;If ch is 'p', the expression is false;If ch is 'E', the expression is true;If ch is '5', the expression is false;26.(x < y and y < z) is True(x < y or y < z) is Truenot (x < y) is False(x < y < z) is Truenot (x < y < z) is False27. age > 13 and age < 1828.weight > 50 or height > 160.29.weight > 50 and height > 160.30.(weight > 50 or height > 160) and not (weight > 50 and height > 160)31. Sorted32.ticketPrice = 20 if (ages >= 16) else 10print(count, end = "\n" if count % 10 == 0 else " ")33.A:if x > 10:score = 3 * scaleelse:score = 4 * scaleB:if income > 10000:tax = income * 0.2else:tax = income * 0.17 + 1000C:if number % 3 == 0:print(i)else:print(j)34.The precedence order of the Boolean operators are not, and, or in this order.TrueTrue35.True36.2 * 2 -3 > 2 and 4–2 > 5 False2 * 2 -3 > 2 or 4–2 > 5 False 37.Yes. Yes. Yes.。

Python语言程序设计(美-梁勇)第6章习题解答(英文)

Python语言程序设计(美-梁勇)第6章习题解答(英文)

Python语言程序设计(美-梁勇)第6章习题解答(英文)Python语言程序设计(第6章函数6.1使用函数的好处是什么?答:至少有三个好处:(1)重用代码(2)减少复杂性(3)易于维护6.2如何定义一个函数?如何调用一个函数?答:1)函数定义包括函数名称、形参以及函数体。

定义函数语法如下: Def functionname(list of parmeters)#Function body2)调用函数有两种方式。

当函数有返回值时将其当做一个值处理,如:larger = max( 3 , 4);当函数每天有返回值时,对函数的调用必须是一条语句,如:print(‘ Programming is fun’)6.3你能用传统的表达式简化程序清单6-1的max函数吗?答:return num1 if num1 > num2 else num26.4对none函数的调用总是它自己语句本身,但是对带有返回值函数的调用总是表达式的一部分。

这种说法正确吗?答:如果一个函数没有返回值,默认情况下,它返回一个特殊值none。

因此,无返回值函数不会返回值,它被称为none函数,none函数可以赋值给一个变量来表明这个变量不知想任何对象。

正确:调用一个函数void返回类型总是声明本身。

错误:调用一个有返回值的函数都是一个表达的一个组成部分。

6.5 none函数能不能有return语句?下面的return函数是否会造成语法错误?Def xFunction(x, y):Print (x + y)Return答:可以有return语句,会造成错误,因为这个函数是有返回值的函数。

6.6给出术语函数头、形参、实参的定义。

答:函数头:以一个def关键字开始,后面紧接着函数名以及形参并以冒号结束。

形参:函数头中的参数,它就像一个占位符。

实参:当调用函数时,就将一个值传递给形参,这个值就是实参。

6.8答:定义函数时未定义正确。

6.9答:None 函数无返回值6.10答:min函数应返回一个值。

Python程序设计第5章 习题解答

Python程序设计第5章  习题解答

945.4 习题5.1 设计控制台应用程序,程序包含如下内容:1)定义狗类Dog 。

字段:名字(name )、年龄(age )、性别(sex )、皮毛颜色(furColor )。

方法:叫的方法(Bark()),显示“汪汪汪”。

跑的方法(Run()),显示“撒欢地跑”。

2)定义猫类Cat 。

字段:名字(name )、年龄(age )、性别(sex )、皮毛颜色(furColor )、猫眼睛的颜色(eyeColor )。

方法:叫的方法(Bark()):显示“喵喵喵”。

3)主类:实现一个Dog 对象(miaomiao 毛毛,3,母,金色),实现叫的方法和跑的方法。

实现一个Cat 对象(mimi 咪咪,2,公,白色,蓝色),实现叫的方法。

5.2 设计控制台应用程序,定义球Ball 类,已知球的半径,计算球的体积、表面积。

字段:球的半径(radius )。

方法:计算球体积的方法BallV olume(),计算公式34V πR 3=。

计算球表面积的方法BallSurfaceArea(),计算公式2S 4πR =。

ci = Circle(1,2,3)ci.draw()li = Line(1,2,3,4)li.draw()class Person:def __init__(self, first, middle, last, age):self.first = first;self.middle = middle;st = last;self.age = age;def __str__(self):return self.first + ' ' + self.middle + ' ' + st + \' ' + str(self.age)def initials(self):return self.first[0] + self.middle[0] + st[0]def changeAge(self, val):self.age += valmyPerson = Person('Raja', 'I', 'Kumar', 21)print(myPerson)myPerson.changeAge(5)print(myPerson)print(myPerson.initials())95。

Python语言程序设计-课后练习-第5周

Python语言程序设计-课后练习-第5周

中国大学MOOC课程 《Python语言程序设计》 课后练习(第5周)北京理工大学Python语言教学团队【说明】本文是中国大学MOOC课程《Python语言程序设计》第5周的课后练习,预估学习完成时间约50分钟。

本周课后练习内容包括1道编程题,主要辅助同学通过使用Python的turtle库理解函数的使用。

对于尚未安装Python运行环境的同学,请根据第1周课程内容介绍的步骤安装Python 3.5.1或者Python 3.5.2版本解释器,如果操作系统兼容性有问题,可以安装Python 3.4版本解释器。

【课后练习】1. Python函数库(学习资料)turtle是Python的内置图形化模块。

Python 3系列版本安装目录的Lib文件夹下可以找到turtle.py文件。

因为turtle绘制图形的命令简单且直观。

更多信息请查阅turtle库官方文档。

https:///3/library/turtle.html引入turtle库可以采用如下两种方式。

>>>import turtle #或者>>>from turtle import * #下文中提到的“第二种方式”可以将turtle库理解为有一系列函数组成,这些函数如表1-3所示,调用函数则调用相关功能。

这里采用第二种方式引入turtle库。

可以turtle库使用画笔pen绘制图形,表1给出了控制画笔绘制状态的函数。

表1:turtle库的画笔绘制状态函数(共3个)函数描述pendown()放下画笔penup()提起画笔,与pendown()配对使用pensize(width)设置画笔线条的粗细为指定大小turtle以小海龟爬行角度来绘制曲线,小海龟即画笔,表2给出了控制turtle画笔运动的函数。

表2:turtle库的画笔运动的函数(共13个) 函数描述forward()沿着当前方向前进指定距离backward()沿着当前相反方向后退指定距离right(angle)向右旋转angle角度left(angle) 向左旋转angle角度goto(x,y) 移动到绝对坐标(x,y)处setx( ) 将当前x轴移动到指定位置sety( ) 将当前y轴移动到指定位置setheading(angle) 设置当前朝向为angle角度home() 设置当前画笔位置为原点,朝向东。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Chapter 5 Loops
1. count < 100 is always True at Point A. count < 100 is
always False at Point C. count < 100 is sometimes True or
sometimes False at Point B.
2.
It would be wrong if it is initialized to a value between 0 and 100, because it could be the number you attempt to guess.
When the initial guess value and random number are equal, the loop will never be executed.
3. (a) Infinite number of times.
(b) Infinite number of times.
(c) The loop body is executed nine times. The printout is 2, 4, 6, 8 on
separate lines.
4. (a) and (b) are infinite loops, (c) has an indentation error.
5.
max is 5
number 0
6.
sum is 14
count is 4
7.
Yes. The advantages of for loops are simplicity and readability. Compilers can
produce more efficient code for the for loop than for the corresponding while
loop.
8. while loop:
sum = 0
i= 0
while i <= 1000:
sum += i
i += 1
9. Can you always convert a while loop into a for loop?
Not in Python. For example, you cannot convert the while loop in Listing 5.3,
GuessNumber.py, to a for loop.
sum = 0
for i in range(1, 10000):
if sum < 10000:
sum = sum + i
10.
(A)
n times
(B)
n times
(C)
n-5 times
(D)
The ceiling of (n-5)/3 times
11.
Tip for tracing programs:
Draw a table to see how variables change in the program. Consider (a) for example.
i j output
1 0 0
1 1
2 0 0
2 1 1
2 2
3 0 0
3 1 1
3 2 2
3 3
4 0 0
4 1 1
4 2 2
4 3 3
4 4
(A).
0 0 1 0 1 2 0 1 2 3
(B).
****
****
2 ****
3 2 ****
4 3 2 ****
(C).
1xxx2xxx4xxx8xxx16xxx
1xxx2xxx4xxx8xxx
1xxx2xxx4xxx
1xxx2xxx
1xxx
(D).
1G
1G3G
1G3G5G
1G3G5G7G
1G3G5G7G9G
12.No. Try n1 = 3 and n2 =3.
13. The keyword break is used to exit the current loop. The program in (A) will
terminate. The output is Balance is 1.
The keyword continue causes the rest of the loop body to be skipped for the current iteration. The while loop will not terminate in (B).
14. If a continue statement is executed inside a for loop, the rest of the iteration is skipped, then the action-after-each-iteration is performed and the loop-continuation-condition is checked. If a continue statement is executed inside a while loop, the rest of the iteration is skipped, then the loop-continuation-condition is checked.
Here is the fix:
i = 0
while i < 4:
if i % 3 == 0:
i += 1
continue
sum += i
i += 1
15.
TestBreak.py
sum = 0
number = 0
while number < 20 and sum < 100:
number += 1
sum += number
print("The number is " + str(number))
print("The sum is " + str(sum))
TestContinue.py
sum = 0
number = 0
while (number < 20):
number += 1
if (number != 10 and number != 11): sum += number
print("The sum is " + str(sum))
16.
(A)
print(j)
1
2
1
2
2
3
(B)
for j in range (1,4):
1
2
1
2
2
3。

相关文档
最新文档