#父与子的编程之旅#第八章
新年第一篇,新年快乐!不废话,直接入正题!
《父与子的编程之旅与小卡特一起学python》这本书真的比较通俗易懂好上手,是编程小白的最佳选择!(编者看到记得给我广告费)
第八章主要讲循环。循环一般分为可以计数的循环和不可计数的循环两种。
可以计数的循环一般用for循环,e.g. for i in range (1,10)
不可计数的循环一般用while循环,e.g. while i<10
讲到while循环不得不提的是跳出循环的两个条件,break和continue,它们的区别是continue跳出当前循环直接跳到下一次的迭代中,而break是直接跳出本循环,循环终止。
还有一个要提的就是循环结果的输出,如果用print函数输出循环结果,那么就要把变量和字符串用逗号间隔的输出
如果用easygui.msgbox函数(easygui库)输出,那么变量和字符串同时输出的时候用“+”号间隔。
直接贴第八章课后题吧!
'''第一题''' """编写一个程序,显示一个乘法表。开始时要询问用户显示哪个数的乘法表。输出应该如下所示: Which multiplication table would you like? 5 Here's your table: 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40 5 * 9 = 45 5 * 10 = 50 """ inputnum = int(raw_input("Which multiplication table would you like?")) print "Here's your table:" for i in range(1,11): print inputnum," * ",i," = ",i*inputnum '''注意print将变量和字符串组合到一起是用逗号间隔的,而easygui.msgbox是用加号''' '''第二题''' '''使用while循环实现同样的效果''' inputnum = int(raw_input("Which multiplication table would you like?")) i = 1 print "Here's your table:" while i < 11: print inputnum," * ",i," = ",i*inputnum i = 1+i '''第三题''' '''向乘法表程序中再加点东西。询问用户想要的乘法表之后,再问用户希望最大乘到几。 输出应当如下所示: Which multiplication table would you like? 7 How high do you want to go? 12 Here's your table: 7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49 7 * 8 = 56 7 * 9 = 63 7 * 10 = 70 7 * 11 = 77 7 * 12 = 84 ''' inputnum = int(raw_input("Which multiplication table would you like?")) wantnum = int(raw_input("How high do you wangt to go?")) print "Here's your table:" for i in range (1,wantnum+1): print inputnum," * ",i," = ",inputnum*i