博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Learn the python the hard way (Day 3)
阅读量:6591 次
发布时间:2019-06-24

本文共 8155 字,大约阅读时间需要 27 分钟。

  hot3.png

Day 3 , I will introduce fucntion, if-statement, for, while and module. Yes after the day, we can coding for something. Luckly, there are not difficult, Let's go
function:
    named for piece of code, is like viriable named string or intger
    function can accept parameter, is like your script accept argv
    function can create smaller script
note:
    def beginning
    function name is consist of underscore and character
    function should follw a ()
    whether () have parameter, if multi parameters should split by comma
    should have repeate parameter
    function should have end :
    content of function should have 4 tab indent
    dedent means the function is over
call function:
    take function name
    function should follw a ()
    whether '( 'have parameter, if multi parameters should split by comma
    the end should be ')'
[root@alicia python_zed]# vi ex21.py  1 # function can return a value for the other useage  2   3 def add(a,b):  4   5     print "ADDING %d + %d" %(a,b)  6   7     return a+b  8   9 def subtract (a, b): 10  11     print "SUBTRACTING %d - %d" %(a,b) 12  13     return a-b 14  15 def multiply (a, b ): 16  17     print "MULTIPLYING %d * %d" % (a,b) 18  19     return a*b 20  21 def divide(a,b): 22  23     print "DIVIDING %d / %d" %(a,b) 24  25     return a/b 26  27 print "Let's do some math with just function!" 28  29 age = add(30,5) 30  31 height = subtract(78,4) 32  33 weight = multiply(90,2) 34  35 iq = divide(100,2) 36  37 print "Age: %d, Height: %d, Weight: %d, IQ: %d" %(age, height,weight,iq) 38  39 # A puzzle for the extra credit, type it in anyway 40  41 print "Here is puzzle." 42  43 what = add(age,subtract(height,multiply(weight,divide(iq,2)))) 44 #what = add(35,subtract(74,multiply(180,devide(50,2)))) 45 #what = 35+(74-180*50/2) 46  47 print "That becomes: ",what, "can you do it by hand?"----------------------------------------------------------------------[root@alicia python_zed]# python ex21.pyLet's do some math with just function!ADDING 30 + 5SUBTRACTING 78 - 4MULTIPLYING 90 * 2DIVIDING 100 / 2Age: 35, Height: 74, Weight: 180, IQ: 50Here is puzzle.DIVIDING 50 / 2MULTIPLYING 180 * 25SUBTRACTING 74 - 4500ADDING 35 + -4426That becomes:  -4391 can you do it by hand?-------------------------------------------------------------

def func(): and retrun a value for the other useage

module:
[root@alicia python_zed]# vi ex25.py 33 def sort_sentence(sentence): 34  35     """Takes in a full sentence and returns the sorted words.""" 36  37     words = break_words(sentence) 38  39     return sort_words(words) 40  41 def print_first_and_last(sentence): 42  43     """prints the first and last words of the sentence.""" 44  45     words = break_words(sentence) 46  47     print_first_word(words) 48  49     print_last_word(words) 50  51 def print_first_and_last_sorted(sentence): 52  53     """sorts the words the print the first and last words""" 54  55     words = sort_sentence(sentence) 56  57     print_first_word(words) 58  59     print_last_word(words) 60 "ex25.py" 60L, 969C                                           60,1-4   -------------------------------------------------------------------     >>> import ex25>>> sentence = "All good things come to those who wait.">>> words = ex25.break_words(sentence)>>> words['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']>>> sorted_words = ex25.sort_words(words)>>> ex25.print_first_word(sorted_words)All>>> ex25.print_last_word(sorted_words) who>>> sorted_words['come', 'good', 'things', 'those', 'to', 'wait.']>>> sorted_words= ex25.sort_sentence(sentence)>>> sorted_words['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']>>> ex25.print_first_and_last(setence)Traceback (most recent call last):  File "
", line 1, in
NameError: name 'setence' is not defined>>> ex25.print_first_and_last(sentence)Allwait.>>> ex25.print_first_and_last_sorted(sentence)Allwho
if-statement:
every if-statement must have an else
if this else should never run because it doesn't make sense. then you must use a die function in the else that prints out an error message and dies
never nest if-statement more than two deep and always try to do them one deep
if ,elif ,else like a paragraphs, where each if-elif-else grouping is like a set of sentence, put blank lines before and after
your boolean tests should have be simple, if they are very complex,you should put them into a variable
[root@alicia python_zed]# vi ex30.py  1 # else and if   2   3 people = 30  4   5 cars = 40  6   7 buses = 15  8   9 if cars > people: 10  11     print "we should take the cars." 12  13 elif cars < people: 14  15     print "we shouldn't take the cars." 16  17 else: 18  19     print "we can't decide." 20  21 if people > buses: 22  23     print "Alright, let's just take the buses." 24  25 else: 26  27     print "Fine, let's stay home then." 28  29 if cars > people and buses < cars: 30  31     print "we should take cars rather than buses.""ex30.py" 32L, 398C written    ------------------------------------------------------------------                               [root@alicia python_zed]# python ex30.pywe should take the cars.Alright, let's just take the buses.we should take cars rather than buses.

for-loop:

while
use while loop only to loop forever, and that means probably.
use a for-loop for all other kinds of looping, especially if there is a fixed or limited number of things to loopover
debug
do not use a debug, it almost have no useage
the best way to debug a program is to use print, to print out the values of variable at points in the program to see where they go wrong
make sure parts of your programs work as you work on them, Do not write massive files of code before you try to run them, code a little ,run a little,and fix a little
[]root@alicia python_zed]#vi ex32.py  1 # for-loop and list  2   3 the_count = [1,2,3,4,5]  4   5 fruits = ['apples', 'oranges', 'pears', 'apricots']  6   7 change = [1, 'pennies', 2, 'dimes', 3, 'quarter']  8   9 #the first kind of for-loop goes through a list 10  11 for number in the_count: 12  13     print "This is count %d " % number 14  15 # same as above 16  17 for fruit in fruits: 18  19     print "A fruit of type: %s " % fruit 20  21 # also we can go through mixed lists too 22  23 # notice we have to use %r since we don't know what's in it 24  25 for i in change: 26  27     print "I got %r " % i 28  29  30 # we can also build lists, first start with an empty one  31  32 elements = [] 33  34 # then use the range function to do 0 to 5 counts 35  36 for i in range(0,6): 37  38     print "Adding %d to the list."  %i 39  40     elements.append(i) 41  42 # now we can print them out too 43  44 for i in elements: 45  46     print "Element was: %d " % i 47  48  49 # one sentence for value to elements 50  51 elements = range(6,10) 52  53 for i in elements: 54  55     print "Elements was : %d" %i-----------------------------------------------------------------[root@huan python_zed]# python ex32.pyThis is count 1 This is count 2 This is count 3 This is count 4 This is count 5 A fruit of type: apples A fruit of type: oranges A fruit of type: pears A fruit of type: apricots I got 1 I got 'pennies' I got 2 I got 'dimes' I got 3 I got 'quarter' Adding 0 to the list.Adding 1 to the list.Adding 2 to the list.Adding 3 to the list.Adding 4 to the list.Adding 5 to the list.Element was: 0 Element was: 1 Element was: 2 Element was: 3 Element was: 4 Element was: 5 Elements was : 6Elements was : 7Elements was : 8Elements was : 9>>> help(range)Help on built-in function range in module __builtin__:range(...)    range(stop) -> list of integers    range(start, stop[, step]) -> list of integers        Return a list containing an arithmetic progression of integers.    range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.    When step is given, it specifies the increment (or decrement).    For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!    These are exactly the valid indices for a list of 4 elements.

ok, today's content is very much,  and we go to the lesson 35.

next, list, string, dictionary will come on.

转载于:https://my.oschina.net/hding/blog/377452

你可能感兴趣的文章
旧瓶新酒之业务入云不简单
查看>>
ASP.NET Core 2加入了Razor页面特性
查看>>
一个“小白”眼中的容器
查看>>
公有云还能信任吗?Azure遭雷击中断超过一天
查看>>
PHP 8引入JIT支持,以提高CPU性能
查看>>
Juval Löwy:为什么每个类都应该是一个服务
查看>>
用JEP 343打包工具,构建自包含、可安装的Java应用程序
查看>>
TOP 13大最热开源微服务Java框架
查看>>
微服务落地,我们在考虑什么?\n
查看>>
Adaptive Execution让Spark SQL更高效更好用
查看>>
艰困之道中学到的经验教训
查看>>
区块链和数据科学:如果同时应用这两种技术,将会实现什么?
查看>>
BAT集体升级云事业部,这背后都藏着哪些“小心思”?
查看>>
.NET Core 2.1的重大缺陷延长了.NET Core 2.0的寿命
查看>>
谈谈UCloud的秒级在线快照服务
查看>>
俄罗斯世界杯直播背后的技术趋势
查看>>
Visual Studio 2017 15.9预览版3支持ARM64 for UWP
查看>>
配置PHPStorm+Vagrant+Laravel的Xdebug调试环境
查看>>
DevOps日常:别人家的运维这样过
查看>>
微软推出VS Code新特性,为TypeScript和JavaScript用户提供AI辅助开发功能
查看>>