习题19:函数和变量

发布时间:2017-11-12 17:12:20编辑:Run阅读(4861)

    函数里面的变量和脚本里面的变量之间是没有连接的,更多的函数练习

    代码如下

    # coding: utf-8
    __author__ = 'www.py3study.com'
    def cheese_and_crackers(cheese_count, boxes_of_crackers):
       print("You have {} cheeses !".format(cheese_count))
       print("You have {} boxes of crackers !".format(boxes_of_crackers))
       print("Man that's enough for a party !")
       print("Get a blanket.\n")
    print("We can just give the function numbers directly:")
    cheese_and_crackers(20, 30)
    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_cheese)
    print("We can even do math inside too:")
    cheese_and_crackers(10 + 20, 5 + 6)
    print("And we can combine the two, variables and math:")
    cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)

    通过这个练习,可以看到给函数cheese_and_crackers 很多的参数,然后在函数里把它们打印出来,可以在函数里用变量名,可以在函数里做运算,甚至可以变量和运算结合起来

    函数的参数和生成变量时用的 = 赋值符类似,事实上,如果一个物件你可以用 = 将其命名,通过也可以将其作为参数传递给一个函数

    应该看到的结果

    图片.png

    常见问题

    怎么处理用户输入的数字,如果想让数量相加?

    记住使用int() 把input()的值转为整数

    可以在函数中调用函数吗?

    可以,后面会用到

关键字