Function arguments (in Python for example)

前端 未结 8 2057
离开以前
离开以前 2020-12-03 16:47

What are [function] arguments? What are they used for?
I started learning Python very recently; I\'m new to programming and I apologize for this basic

8条回答
  •  囚心锁ツ
    2020-12-03 17:15

    In that case for using arguments, it is simply a demo on how to use them, not the most effective perhaps as you demonstrated. Functions are very useful. for example if i wanted to add two numbers:

    def add(num1, num2):
      x = num1 + num2
      return x
    add(1,3)
    

    Functions are useful for performing repetitive tasks, let's say in your example you had to say hello to hundreds of names, instead of having to do a loop of that raw_input() function to read their name and add some text to it you could simply call a function to perform the task and pass arguments (the persons name to it).

    Per your second question, arguments are just variables passed to the function, so whatever variable you pass to it from the outside, for example I pass numbers 1 and 3 to my function add on the inside of that function they are simply referred to as num1 num2.

    In your case with passing too many arguments would yield this:

    >>> add(1,2)
    3
    >>> add(1,2,3)
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: add() takes exactly 2 arguments (3 given)
    >>> 
    

    Best of luck! and feel free to shoot me an email if you need further help (sbrichards (at) mit.edu)

提交回复
热议问题