Week 5 Python
Week 5 Python
Lecture 5.1
Introduction to functions :-
If we run the block [1] code, we will not get any output. Functions are not executed
unless they are called.
Code :-
Output :-
Lecture 5.2
Lecture 5.3
Obvious sort :-
find the minimum element in the list l
append that element in the list x
remove that element in the list l
Another way -
Lecture 5.4
Sum of n numbers -
sum(n)=sum(n-1)+n
Factorial -
#fact(n)=fact(n-1).n
Lecture 5.6
Recursion :-
Lecture 5.7
Positional arguments :-
All functions that we have seen so far have used positional arguments. Here, the
position of an argument in the function call determines the parameter to which it is
passed.
Keyword arguments :-
Keyword arguments introduce more flexibility while passing arguments.
Default arguments :-
Parameters that are assigned a value in the function definition are called default
parameters.
An argument corresponding to a default parameter can be passed as a positional
argument or as a keyword argument.
Default parameters always come at the end of the parameter list in a function definition.
Lecture 5.8
Scope of a variable :-
The region in the code where a name can be referenced is called its scope. If we try to
reference a variable outside its scope, the interpreter will throw a NameError.
Local vs Global -
In the above example, the scope of the name x is local to the function; x has a
meaningful existence only inside the function and any attempt to access it from outside
the function is going to result in an error
The name y is accessible from within the function as well. We say that the scope of y is
global. That is, it can be referenced from anywhere within the program — even inside a
function — after it has been defined for the first time.
Lecture 5.9
Types of functions :-
Built-in functions -
So far we have been freely using built-in functions like -
print(), int(), len() and so on.
Library functions -
These functions are the built-in functions i.e., they are predefined in the library of the
python, such as -
sqrt(), log() , random() and so on.