Declaring functions in python


Hello guys,

I have started learning python since a couple of days.
My question is that if I am creating a function who’s parameter is string. (the value passed to it is going to be a string)
So, I declare my function as: def func(‘string’) or def func(string)?

which one is right between the above two and why?


the last one, def func(string), the argument at function call will be passed to the function parameter, you can’t assign to strings so the parameter has to be a variable


Thank you for replying.

Even if I am passing a string as an argument?

If so, how do I call the function?


yes, given the string has to be assigned to parameter, if it helps:

# assigning argument 'abc' to parameter string

if the parameter was 'string', you would have gotten an error (you can’t assign to string)

yep, exactly.


Yea, I got an error. So I was just wondering the reason why, I get it now.
Arguments need to changed among variables and string and not parameters.

Thank you so much for your explanation.


python is weakly typed in that regard, even though we name the parameter string:

def func(string):
   # print parameter
   print string

func("hello world")

we can still pass integers, floats and Boolean’s. Python doesn’t enforce data type on parameter. This is different from for example java:

void methodName(int a) {
methodName("hello world"); // this would give error
// we must pass integer as argument
// given we specified this at the parameter


Yea, I was trying to compare it with Java earlier.
My preconceived notion was that anything without parenthesis is going to be a variable (which supports integers, floats) and anything in double quotes would be classified as characters and strings.

My bad. Understood now.


parenthesis? () are parenthesis

you mean quotation marks/double quotes or apostrophes?

careful, python doesn’t have a char data type (a single character in python is simply a string), and in Java String is not one of the 8 primitive data types.


Yea, I mean apostrophes *
Sorry about that.