Learn Python The Hard Way(18)

Functions do three things:

    1. They name pieces of code the way variables name strings and numbers.

    2. They take arguments the way your scripts take argv.

    3. Using #1 and #2 they let you make your own "mini scripts" or "tiny commands".

You can create a function by using the word def in Python. I'm going to have you make four different functions that work like your scripts, and then show you how each one is related.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# this one is like your scripts with argv
def print_two(*args):
	arg1, arg2 = args
	print "arg1: %r, arg2: %r" % (arg1, arg2)
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
	print "arg1: %r, arg2: %r" % (arg1, arg2)
# this just takes one argument
def print_one(arg1):
	print "arg1: %r" % arg1

def print_none():
	print "I got nothin'."
print_two ("Zed" ,"Shaw")
print_two_again ("Zed","Shaw")
print_one ("First!" )
print_none()

result:

                                    155106_H3xQ_189901.jpg

Let's break down the first function, print_two which is the most similar to what you already know from making scripts:

    1. First we tell Python we want to make a function using def for "define".

    2. On the same line as def we then give the function a name, in this case we just called it "print_two" but it             could be "peanuts" too. It doesn't matter, except that your function should have a short name that says             what it does.

    3. Then we tell it we want *args (asterisk args) which is a lot like your argv parameter but for functions. This             has to go inside () parenthesis to work.

    4. Then we end this line with a : colon, and start indenting.

    5. After the colon all the lines that are indented 4 spaces will become attached to this name, print_two. Our             first indented line is one that unpacks the arguments the same as with your scripts.

    6. To demonstrate how it works we print these arguments out, just like we would in a script.

Now, the problem with print_two is that it's not the easiest way to make a function. In Python we can skip the whole unpacking args and just use the names we want right inside (). That's what print_two_again does.

After that you have an example of how you make a function that takes one argument in print_one.

Finally you have a function that has no arguments in print_none.








转载于:https://my.oschina.net/xtfjt1988/blog/401914

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值