Functions Arguments
So argument is parameters where you can provide the values to functions and also useful in case you don't have to make variable global.So let's modify our existing code for input argument.
functions.py :
students = []
def get_students_titlecase():
student_titlecase = []
for student in students:
students_titlecase = student.title()
return students_titlecase
def print_students_titlecase():
students_titlecase = get_students_titlecase()
print(students_titlecase)
def add_student(name) :
students.append(name)
student_list = get_students_titlecase()
add_student("Abhinaw")
So now modify our add_student method:
def add_student(name,student_id=332)
students.append(name)
So here you will notice student_id=332 is basically a default or optional student_id if any user does not provide student_id then it will add the value automatically but if any user provides then in that case it will be overridden by the userinput value.
Now let's add student Dictionaries to our add_student method:
def add_student(name , student_id=222)
student = {"name:" name, "student_id", student_id}
students.append(student)
So call this function like this
add_student(name="Abhinaw" , student_id=14)
In Python there can be multiple variable arguments such as inbuild print function.
print("hello", "World", 34, None , "Wow')
you must have question here like how come it possible let me create our own function just to cater above.
def var_args(name, *args)
print(name)
print(args)
just to call the function
var_args("Abhine","Android Developer",None, True)
you can add any number of argument.
There is also a concept called kwargs.
let's have a look.
def var_args(name,**kwargs):
print(name)
print(kwargs["description"],kwrgs["feedback"])
var_args("Abhinaw" ,description="Loves Android", feedback=None,androidcodingworld_subscriber=True)
it is called kwargs argument and defined with **kwrgs.So it is not a list it is Dictionaries thats where it differs from above example.
basically it was an example of variable arguments you can add as much as you can in the form of list or can also make it Dictionaries.
No comments:
Post a Comment