Python Tutorial
def function_name(parameter1[, parameter2, ..]): "comments or doc string" # function code # return statement (optional default is None)
def get_avg_mark(name, mark1, mark2): mark = (mark1 + mark2) / 2; return (name, mark);
var_tuple = get_avg_mark('student1', 78, 87); print var_tuple;Output:
$ python test_tuple.py ('student1', 82)
#!/usr/bin/python def show_message(msg): print(msg); return; show_message("Welcome to python!");Output:
$ python test_msg.py Welcome to python!
#!/usr/bin/python def update_list(param): param.extend(['A', 'B', 'c']); print "param inside function: ", param; return list_var = [1, 2, 3]; print "list_var before function call: ", list_var; update_list(list_var); print "list_var after function call: ", list_var;Output:
$ python test_ref.py list_var before function call: [1, 2, 3] param inside function: [1, 2, 3, 'A', 'B', 'c'] list_var after function call: [1, 2, 3, 'A', 'B', 'c']
#!/usr/bin/python def update_param(param): param = 10; print "param inside function: ", param; return int_var = 20; print "int_var before function call: ", int_var; update_param(int_var); print "int_var after function call: ", int_var;Output:
$ python test_ref.py int_var before function call: 20 param inside function: 10 int_var after function call: 20
#!/usr/bin/python def show_message(msg): print(msg); return; show_message();Output:
$ python test_msg.py Traceback (most recent call last): File "test_msg.py", line 7, inhere msg parameter is a required parameter but it is not passed when invoking, so resulting python interpreter error.show_message(); TypeError: show_message() takes exactly 1 argument (0 given)
show_message("Welcome to python!");Output:
$ python test_msg.py Welcome to python!
#!/usr/bin/python def get_avg_mark(name, mark1, mark2): mark = (mark1 + mark2) / 2; return mark; avg= get_avg_mark(mark1=98, name = 'student1', mark2 = 77); print avg;Output:
$python get_avg.py 87here calling function using parameter name as keyword and parameter order is not important.
#!/usr/bin/python def get_avg_mark(name, mark1, mark2=77): mark = (mark1 + mark2) / 2; return (name, mark); avg= get_avg_mark(mark1=98, name = 'student1'); print avg; avg= get_avg_mark('student2', 78, 86); print avg;Output:
$ python test_avg.py ('student1', 87) ('student2', 82)
#!/usr/bin/python # marks parameter is the variable-length parameter which holds non specified param values are as tuples. def get_avg_mark(name, *marks): mark = 0; for m in marks: mark +=m; mark = mark/len(marks); return (name, mark); avg= get_avg_mark('student1', 76, 70, 72); print avg; avg= get_avg_mark('student2', 78, 86, 65, 85); print avg;Output:
$ python test_avg.py ('student1', 72) ('student2', 78)« Previous Next »
Python Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page