Learn the python the hard way (Day 3)

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.py
Let's do some math with just function!
ADDING 30 + 5
SUBTRACTING 78 - 4
MULTIPLYING 90 * 2
DIVIDING 100 / 2
Age: 35, Height: 74, Weight: 180, IQ: 50
Here is puzzle.
DIVIDING 50 / 2
MULTIPLYING 180 * 25
SUBTRACTING 74 - 4500
ADDING 35 + -4426
That 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 "<stdin>", line 1, in <module>
NameError: name 'setence' is not defined
>>> ex25.print_first_and_last(sentence)
All
wait.
>>> ex25.print_first_and_last_sorted(sentence)
All
who
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.py
we 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.py
This 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 : 6
Elements was : 7
Elements was : 8
Elements 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值