Defining Funtions And The range() Function
Defining Functions
We can define function by using def keyword, the function definition written by using def keyword with function name followed by parameters
enclosed by simple parenthesis or can be blank. The next statement is at next line with indent. It can have docstring.
Example:Lets write function for checking number is prime or not.
>>> def check_prime(num): ... is_prime = True ... for index in range(2, num): ... if num % index == 0: ... is_prime = False ... break ... index += 1 ... if is_prime: ... print "Given Number is Prime" ... else: ... print "Given Number is Not Prime" ... >>> check_prime(9) Given Number is Prime >>> check_prime(8) Given Number is Not Prime
Function parameters can have Default Argument, Variable Number of Arguments, Keyword Arguments.
Default Arguments
A function can have default arguments as shown below:->>> def modify_me(limit, text = "Their"): ... for i in range(limit): ... print "Hello " + text ...This function can be called with mandatory argument as:-
>>> modify_me(3): Hello Their Hello Their Hello TheirOr with optional arguments as:-
>>> modify_me(3, 'World') Hello World Hello World Hello World
Keyword Arguments
A function can be called with keyword arguments, i.e. keyword=value, as shown below:->>> def greet(limit, greetings = "Hello", whom = "Their"): ... for i in range(limit): ... print greetings + ' ' + whom ...This function can be called with mandatory argument as:-
>>> greet(1): Hello TheirOr with optional keyword arguments as:-
>>> greet(3, 'World') Hello World Hello World Hello WorldOr giving keyword arguments as:-
>>> greet(3, greetings='Good Morning', whom='Dear') Good Morning Dear Good Morning Dear Good Morning Dear
Variable Or Arbitrary Arguments
It can be used when you don't know- How many arguments are there?
- How many of them keywords?
>>> def greet(limit, greetings = "Hello", whom = "Their"): ... for i in range(limit): ... print greetings + ' ' + whom ...This function can be called with mandatory argument as:-
>>> greet(1): Hello TheirOr with optional keyword arguments as:-
>>> greet(3, 'World') Hello World Hello World Hello WorldOr giving keyword arguments as:-
>>> greet(3, greetings='Good Morning', whom='Dear') Good Morning Dear Good Morning Dear Good Morning Dear
range Function
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions:>>> for i in range(10): ... print i, ... 0 1 2 3 4 5 6 7 8 9This will print nothing.
Keep Following, For More.
Comments
Post a Comment