《笨方法学PYTHON》——ninthlesson

本文深入探讨函数的概念,包括如何定义、使用及传递参数。通过具体示例,展示函数如何简化代码,实现模块化编程,提高代码复用性和可读性。

习题18:命名、变量、代码、函数

函数可以做三样事情:

  • 他们给代码片段命名,就跟“变量”给字符串和数字命名一样。
  • 他们可以接受参数,就跟你的脚本接受argv一样。
  • 通过使用#1和#2,他们可以让你创建“微型脚本”或者“小命令”。
# this one is like your scripts with argv
def printTwo(*args):
    arg1, arg2 = args
    print("arg1:%r,arg2:%r" % (arg1, arg2))


# ok,that *args is actually pointless,we can just do this
def printTwoAgain(arg1, arg2):
    print("arg1:%r,arg2:%r" % (arg1, arg2))


# this just takes one argument
def printOne(arg1):
    print("arg1:%r" % arg1)


# this one takes no arguments
def printNome():
    print("I got nothin'.")


printTwo("Zed", "Shaw")
printTwoAgain("Zed", "Shaw")
printOne("First!")
printNome()

1. 函数定义是以 def 开始的吗?

是的,def就是定义函数的意思

2. 函数名称是以字符和下划线 _ 组成的吗?

函数名称和变量名称的命名方式一样,字符加下划线,下划线不能作为起始符

3. 函数名称是不是紧跟着括号 ( ?

是的,括号中键入入参,没有入参则为空

4. 括号里是否包含参数?多个参数是否以逗号隔开?

YES

5. 参数名称是否有重复?(不能使用重复的参数名)

6. 紧跟着参数的是不是括号和冒号 ): ?

7. 紧跟着函数定义的代码是否使用了 4 个空格的缩进 (indent)?

8. 函数结束的位置是否取消了缩进 (“dedent”)?

是的

 

 

 

习题19:函数和变量

def cheeseAndCrackers(cheeseCount, boxesOfCrackers):
    print("You have %d cheeses!" % cheeseCount)
    print("You have %d boxes of crackers!" % boxesOfCrackers)
    print("Man that's enough for a party!")
    print("Get a blanket.\n")


print("We can just give the function numbers directly:")
cheeseAndCrackers(20, 30)
print("OR,we can use varibales from our script:")
amountOfCheese = 10
amountOfCrackers = 50
cheeseAndCrackers(amountOfCheese, amountOfCrackers)
print("We can even do math inside too:")
cheeseAndCrackers(10 + 20, 5 + 6)
print("And we can combine the two,variables and math:")
cheeseAndCrackers(amountOfCheese + 100, amountOfCrackers + 1000)

1. 倒着将脚本读完,在每一行上面添加一行注解,说明这行的作用。

2. 从最后一行开始,倒着阅读每一行,读出所有的重要字符来。

3. 自己编至少一个函数出来,然后用10种方法运行这个函数。

10种方法运行这个函数。。。不会呀,这个。

 

 

print_r('点个赞吧');
var_dump('点个赞吧');
NSLog(@"点个赞吧!")
System.out.println("点个赞吧!");
console.log("点个赞吧!");
print("点个赞吧!");
printf("点个赞吧!\n");
cout << "点个赞吧!" << endl;
Console.WriteLine("点个赞吧!");
fmt.Println("点个赞吧!")
Response.Write("点个赞吧");
alert(’点个赞吧’)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值