笨方法学python 习题19

代码如下:

#cheese_and_crackers是函数,代码展示了给函数cheese_and_crackers传递值的各种方式,函数会将传入的值打印出来。
#可以给函数传递数字,变量,数学表达式
#可以给函数传递数学表达式+变量
#这与函数的参数和生成变量时用的=与赋值符类似
#用=对其命令,也可以将其作为参数传递给一个函数
def cheese_and_crackers(cheese_count,boxes_of_crackers):
    print(f"you have {cheese_count} cheese!")
    print(f"you have {boxes_of_crackers} boxes of crackers!")
    print("man that's enough for a party!")
    print("Get a blank.\n")
print("We can just give the function numbers directly:")
cheese_and_crackers(20,30)

#为函数cheese_and_crackers传递了变量amount_of_cheese 和amount_of_crackers ,并为变量赋值
print("OR,We can use variables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50

cheese_and_crackers(amount_of_cheese,amount_of_crackers)

#为函数cheese_and_crackers传递了数学公式
print("We can even do match inside too:")
cheese_and_crackers(10+20,5+6)

#为函数cheese_and_crackers传递了数学公式和变量
print("And we can combine the two,variables and math:")
cheese_and_crackers(amount_of_cheese + 100,amount_of_crackers +1000)

结果输出:

We can just give the function numbers directly:
you have 20 cheese!
you have 30 boxes of crackers!
man that's enough for a party!
Get a blank.

OR,We can use variables from our script:
you have 10 cheese!
you have 50 boxes of crackers!
man that's enough for a party!
Get a blank.

We can even do match inside too:
you have 30 cheese!
you have 11 boxes of crackers!
man that's enough for a party!
Get a blank.

And we can combine the two,variables and math:
you have 110 cheese!
you have 1050 boxes of crackers!
man that's enough for a party!
Get a blank.

进程已结束,退出代码0

Tips

1. 怎么处理用户输入的数字?
用int()把input()的值转换为整数
2. 创建amount_of_cheese变量会不会改变函数重变量cheese_count?
不会。这些变量是在函数之外的,当它们被传递到函数重以后,函数会为这些变量创建一些临时版本,当函数运行结束后,这些临时变量就会被丢弃,一切又回到了之前。
3. 全局变量(amount_of_cheese)的名称和函数变量的名称不可以取成一样的

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值