Python – passing arguments to a function

Question:

I’m new to python actually started watching a tutorial, I know decent JavaScript, now here are my if statements

if str(fileType) == "V":
    if (not windowTitle) and (not windowSize):
        playVideo()
    elif (windowTitle) and (windowSize):
        playVideo(windowSize=int(windowSize), windowTitle=windowTitle)
    elif (windowSize):
        playVideo(int(windowSize=windowSize))
    elif (windowTitle):
        playVideo(windowTitle=windowTitle)

I want to know that if you want to skip the first argument and give second argument in python how would you do that, and I am giving arguments by writing their name = and the variable is that okay?

and after I check fileType I want to check if windowTitle and windowSize are empty am I doing it right?

and also I don’t know what’s in a variable if user skips (hits enter without writing anything), like in JavaScript it would be undefined

Asked By: Curious

||

Answers:

You are correctly using the syntax to pass arguments to a method in python. There are two two ways to pass arguments to a method:

  1. By passing the argument’s value directly – you need to pass the arguments in order.
  2. By passing the argument’s name-value pair (as you’ve used before) – the arguments do not need to be in order as long you’ve specified the name value pair. This is also known as keyword arguments.

If you want to skip first argument and only pass the second argument, you can use keyword arguments (mentioned in 2 above). Something like – playVideo(windowTitle='My Video')

Also if the user skips to pass an argument, in case of the method having the default value – it’ll take the default value.

Answered By: Subhash Prajapati

Yes, you can specify default values to function arguments. This makes the arguments optional (i.e, they do not have to be provided when the function is called).

def sum(a=0, b=0):
    return a + b


print(sum(a=1))  #prints 1
print(sum(b=2))  #prints 2
print(sum(1,2))  #prints 3
print(sum())  #prints 0
Answered By: Venkatesh A
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.