MODULE-
BASICS OF PYTHON PROGRAMMING
Topics Include
● Fundamentals of Python Programming
● Flow Control
● Functions
Objectives
1. Functions:
1. def statements with parameters
2. Return values and return statements
3. The None Value
4. Keyword Arguments and print()
5. Local and Global Scope
6. The global statement
7. Exception Handling
8. A short program: Guess the number
CHAPTER-2
FUN CTIONS
FLOW CONTROL
● You’re already familiar with the print(), input(),
and len() functions from the previous
chapters.
● Python provides several built-in functions like
these, but you can also write your own
functions.
● A function is like a mini-program within a
program.
● To better understand how functions work, let’s
create one. Type this program into the file
editor and save it as helloFunc.py:
Chapter:3
Functions
Chapter:3.1
Function calls
• In the context of programming, a function is a named as sequence of statements
that performs a computation.
• When you define a function, you specify the name and the sequence of
statements.
• Later, you can “call” the function by name.
• We have already seen one example of a function call:
• The name of the function is type.
• The expression in parentheses is called the argument of the function.
• The argument is a value or variable that we are passing into the function as input
to the function.
• The result, for the type function, is the type of the argument.
• It is common to say that a function “takes” an argument and “returns” a result. The
result is called the return value.
Chapter:3.2
Built-in Function
• Python provides a number of important built-in functions
that we can use without needing to provide the function
definition.
• The creators of Python wrote a set of functions to solve
common problems and included them in Python for us to
use.
• The max and min functions give us the largest and
smallest values in a list, respectively:
• The max function tells us the “largest character” in the
string (which turns out to be the letter “w”) and the min
function shows us the smallest character (which turns out
to be a space).
• Another very common built-in function is the len function
which tells us how many items are in its argument.
• If the argument to len is a string, it returns the number of
characters in the string.
• These functions are not limited to looking at
strings.
• They can operate on any set of values, as we
will see in later chapters.
• You should treat the names of built-in functions
as reserved words (i.e., avoid using “max” as a
variable name).
Chapter:3.3
Type conversion functions
• Python also provides built-in functions that
convert values from one type to another.
• The int function takes any value and
converts it to an integer, if it can, or
complains otherwise:
• Python also provides built-in functions that
convert values from one type to another.
• The int function takes any value and
converts it to an integer, if it can, or
complains otherwise:
Chapter:3.4
Random numbers
• Given the same inputs, most computer programs generate the
same outputs every time, so they are said to be deterministic.
• Determinism is usually a good thing, since we expect the same
calculation to yield the same result.
• For some applications, we want the computer to be
unpredictable. Games are an obvious example, but there are
more.
• Making a program truly nondeterministic turns out to be not so
easy, but there are ways to make it at least seem
nondeterministic. One of them is to use algorithms that generate
pseudorandom numbers.
• Pseudorandom numbers are not truly random because they are
generated by a deterministic computation, but just by looking at
the numbers it is all but impossible to distinguish them from
• The random module provides functions that generate
pseudorandom numbers (which we will simply call “random” from
here on).
• The function random returns a random float between 0.0 and 1.0
(including 0.0 but not 1.0).
• Each time you call random, you get the next number in a long
series.
• To see a sample, run this loop:
• The random function is only one of many functions that
handle random numbers.
• The function randint takes the parameters low and high,
and returns an integer between low and high (including
both).
• To choose an element from a sequence at random, you can
use choice:
• The random module also provides functions to generate
random values from continuous distributions including
Gaussian, exponential, gamma, and a few more.
Chapter:3.5
Math functions
• Python has a math module that provides most of the familiar
mathematical functions.
• Before we can use the module, we have to import it:
• This statement creates a module object named math. If you print
the module object, you get some information about it:
• The module object contains the functions and variables defined in
the module.
• To access one of the functions, you have to specify the name
of the module and the name of the function, separated by a
dot (also known as a period). This format is called dot notation.
• The first example computes the logarithm base 10 of the signal-
to-noise ratio. The math module also provides a function called
log that computes logarithms base e.
• The second example finds the sine of radians. The name of the
variable is a hint that sin and the other trigonometric functions
(cos, tan, etc.) take arguments in radians.
• To convert from degrees to radians, divide by 360 and multiply by
2:
• The expression math.pi gets the variable pi from the math
module. The value of this variable is an approximation of ,
accurate to about 15 digits.
• If you know your trigonometry, you can check the previous result
by comparing it to the square root of two divided by two:
Chapter:3.6
Adding new functions
• So far, we have only been using the functions
that come with Python, but it is also possible
to add new functions.
• A function definition specifies the name of a
new function and the sequence of statements
that execute when the function is called.
• Once we define a function, we can reuse the
function over and over throughout our
program.
• Here is an example:
• def is a keyword that indicates that this is a
function definition. The name of the function
is print_lyrics.
• The rules for function names are the same
as for variable names: letters, numbers and
some punctuation marks are legal, but the
first character can’t be a number. You can’t
use a keyword as the name of a function, and
you should avoid having a variable and a
function with the same name.
• The empty parentheses after the name indicate that this function
doesn’t take any arguments.
• Later we will build functions that take arguments as their inputs.
• The first line of the function definition is called the header; the rest is
called the body. The header has to end with a colon and the body
has to be indented.
• By convention, the indentation is always four spaces. The body can
contain any number of statements.
• The strings in the print statements are enclosed in quotes. Single
quotes and double quotes do the same thing; most people use single
quotes except in cases like this where a single quote (which is also
an apostrophe) appears in the string.
• If you type a function definition in interactive mode, the interpreter
prints ellipses (. . . ) to let you know that the definition isn’t complete:
• To end the function, you have to enter an empty line (this is not necessary
in a script).
• Defining a function creates a variable with the same name.
• The value of print_lyrics is a function object, which has type “function”.
• The syntax for calling the new function is the same as for built-in
functions:
• Once you have defined a function, you can use it inside another
function. For example, to repeat the previous refrain, we could write a
function called repeat_lyrics:
But that’s not really how the song goes.
Chapter:3.7
Definitions and uses
• Pulling together the code fragments from the previous section, the
whole program looks like this:
● This program contains two function definitions: print_lyrics and
repeat_lyrics.
● Function definitions get executed just like other statements, but the
effect is to create function objects.
● The statements inside the function do not get executed until the
function is called, and the function definition generates no output.
● As you might expect, you have to create a function before you can
execute it. In other words, the function definition has to be executed
before the first time it is called.
Chapter:4.8
Flow of execution
● In order to ensure that a function is defined before its first use, you
have to know the order in which statements are executed, which is
called the flow of execution.
● Execution always begins at the first statement of the program.
Statements are executed one at a time, in order from top to bottom.
● Function definitions do not alter the flow of execution of the program,
but remember that statements inside the function are not executed until
the function is called.
● A function call is like a detour in the flow of execution. Instead of going
to the next statement, the flow jumps to the body of the function,
executes all the statements there, and then comes back to pick up
where it left off.
● That sounds simple enough, until you remember that one function can call another.
● While in the middle of one function, the program might have to execute the
statements in another function. But while executing that new function, the program
might have to execute yet another function!
● Fortunately, Python is good at keeping track of where it is, so each time a function
completes, the program picks up where it left off in the function that called it.
● When it gets to the end of the program, it terminates. What’s the moral of this
sordid tale? When you read a program, you don’t always want to read from top to
bottom.
● Sometimes it makes more sense if you follow the flow of execution.
Chapter:3.9
Parameters and arguments
● Some of the built-in functions we have seen require arguments. For
example, when you call math.sin you pass a number as an argument.
Some functions take more than one argument: math.pow takes two, the
base and the exponent.
● Inside the function, the arguments are assigned to variables called
parameters.
● Here is an example of a user-defined function that takes an argument:
● This function assigns the argument to a parameter named bruce. When
the function is called, it prints the value of the parameter (whatever it is)
twice.
● This function works with any value that can be printed.
● The same rules of composition that apply to built-in functions also apply
to user-defined functions, so we can use any kind of expression as an
argument for print_twice:
● The argument is evaluated before the function is called, so in the
examples the expressions “Spam ’*4andmath.cos(math.pi)‘ are only
evaluated once.
● You can also use a variable as an argument:
● The name of the variable we pass as an argument (michael) has nothing
to do with the name of the parameter (bruce). It doesn’t matter what the
value was called back home (in the caller); here in print_twice, we call
everybody bruce.
Chapter:3.10
Fruitful functions and void
functions
● Some of the functions we are using, such as the math functions, yield
results; for lack of a better name, we call them fruitful functions.
● Other functions, like print_twice, perform an action but don’t return a
value.
● They are called void functions.
● When you call a fruitful function, you almost always want to do
something with the result; for example, you might assign it to a variable
or use it as part of an expression:
● When you call a function in interactive mode, Python displays the
result:
● But in a script, if you call a fruitful function and do not store the result of
the function in a variable, the return value vanishes into the mist!
● This script computes the square root of 5, but since it doesn’t store the
result in a variable or display the result, it is not very useful.
● Void functions might display something on the screen or have some
other effect, but they don’t have a return value. If you try to assign the
result to a variable, you get a special value called None.
● The value None is not the same as the string “None”. It is a special
value that has its own type:
● To return a result from a function, we use the return statement in our
function.
● For example, we could make a very simple function called addtwo that
adds two numbers together and returns a result.
● When this script executes, the print statement will print out “8” because
the addtwo function was called with 3 and 5 as arguments. Within the
function, the parameters a and b were 3 and 5 respectively.
● The function computed the sum of the two numbers and placed it in the
local function variable named added.
● Then it used the return statement to send the computed value back to
the calling code as the function result, which was assigned to the
variable x and printed out.
Chapter:3.11
Why Functions?
● It may not be clear why it is worth the trouble to divide a program
into functions. There are several reasons:
1. Creating a new function gives you an opportunity to name a group of
statements, which makes your program easier to read, understand, and
debug.
2. Functions can make a program smaller by eliminating repetitive code.
Later, if you make a change, you only have to make it in one place.
3. Dividing a long program into functions allows you to debug the parts one
at a time and then assemble them into a working whole.
4. Well-designed functions are often useful for many programs. Once you
write and debug one, you can reuse it.
Chapter:3.12
Debugging
● If you are using a text editor to write your scripts, you might run into
problems with spaces and tabs.
● The best way to avoid these problems is to use spaces exclusively (no
tabs).
● Most text editors that know about Python do this by default, but some
don’t.
● Tabs and spaces are usually invisible, which makes them hard to
debug, so try to find an editor that manages indentation for you.
● Also, don’t forget to save your program before you run it. Some
development environments do this automatically, but some don’t.
● In that case, the program you are looking at in the text editor is not the
same as the program you are running.
● Debugging can take a long time if you keep running the same incorrect
program
● over and over! Make sure that the code you are looking at is the code
you are running.
● If you’re not sure, put something like print("hello") at the beginning of
the program and run it again.
● If you don’t see hello, you’re not running the right program!
Chapter:3.13
Glossary
Terminology description
Algorithm A general process for solving a category of problems
Argument A value provided to a function when the function is
called. This value is assigned to the corresponding
parameter in the function.
Body The sequence of statements inside a function definition
Composition Using an expression as part of a larger expression, or a
statement as part of a larger statement
Deterministic Pertaining to a program that does the same thing each
time it
runs, given the same inputs.
Dot notation The syntax for calling a function in another module by
specifying the module name followed by a dot (period)
and the function name.
Flow of execution The order in which statements are executed during a
program
run.
Fruitful execution A function that returns a value.
Function A named sequence of statements that performs some
useful operation.
Functions may or may not take arguments and may or
Terminology description
Function cell A statement that creates a new function, specifying its
name,
parameters, and the statements it executes.
Function object A value created by a function definition. The name of
the function is a variable that refers to a function object.
The first line of a function definition.
header
Import statement A statement that reads a module file and creates a
module
object.
Module object A value created by an import statement that provides
access to
the data and code defined in a module
Parameter A name used inside a function to refer to the value
passed as an argument.
Pseudorandom Pertaining to a sequence of numbers that appear to be
random, but are generated by a deterministic program.
Return value The result of a function. If a function call is used as an
expression, the return value is the value of the
expression
Void function A function that does not return a value
Chapter:3.14
Exercises
THANK YOU