Declaring functions in python


#1

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?


#2

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


#3

Thank you for replying.

Even if I am passing a string as an argument?

If so, how do I call the function?
func(“abc”)?


#4

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

# assigning argument 'abc' to parameter string
string='abc'

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

yep, exactly.


#5

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.


#6

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

def func(string):
   # print parameter
   print string

func("hello world")
func(42)

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) {
    System.out.println(a);
}
methodName(42);
methodName("hello world"); // this would give error
// we must pass integer as argument
// given we specified this at the parameter

#7

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.


#8

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.


#9

Yea, I mean apostrophes *
Sorry about that.