Python Programming Unit 6
Python Programming Unit 6
PROGRAMMING
Unit 5 Functions
Contents
• Standard Mathematical, time, random number
• system specific functions,
• user defined functions,
• parameter passing,
• global variables,
• Default parameters,
• recursion, and
• functions as data.
Introduction
• A function in Python is
a named suite of code,
which can also take an
optional list of
arguments if required.
• You define a Python
function using the def
statement, providing a
name for your function
and specifying either an
empty or populated
argument list within
parentheses.
Introduction
• Functions are the most basic program structure Python provides for maximizing
code reuse and minimizing code redundancy.
• Functions are also a design tool that lets us split complex systems into manageable
parts
Why use Functions
• maximizing code reuse and minimizing redundancy
• As in most programming languages, Python functions are the simplest way to package logic you
may wish to use in more than one place and more than one time. Up until now, all the code we’ve
been writing has run immediately. Functions allow us to group and generalize code to be used
arbitrarily many times later. Because they allow us to code an operation in a single place and use
it in many places, Python functions are the most basic factoring tool in the language: they allow
us to reduce code redundancy in our programs, and thereby reduce maintenance effort.
• procedural decomposition
• Functions also provide a tool for splitting systems into pieces that have well-defined roles. For
instance, to make a pizza from scratch, you would start by mixing the dough, rolling it out,
adding toppings, baking it, and so on. If you were programming a pizza-making robot, functions
would help you divide the overall “make pizza” task into chunks—one function for each subtask
in the process. It’s easier to implement the smaller tasks in isolation than it is to implement the
entire process at once. In general, functions are about procedure—how to do something, rather
than what you’re doing it to.
Standard Functions(Built-in Functions) in Python
• Built in functions, are part of the Python language. These functions have its code written
within the python interpreter, which is not visible to us.
• We can use the built-in functions, by calling them with their names.
Standard Functions(Built-in Functions) in Python
Input() Function
• The Input function, is a built-in function in Python, which allows coders to receive
information through the keyboard, which can then be processed in a program.
• Accepting user input, lets you retrieve values from the user, while your program is
running.
• This means that you do not need to depend on pre-existing values, or the contents of
a file, in order to run your program.
• When we call an input function, our program will pause. The program resumes,
only after the user enters the text, through the Python shell or command line.
Multiple inputs in One Line
• In Python, it is possible to get multiple values, or user inputs, from the user in one
line.
math-Mathematical Functions
• This module provides access to the mathematical functions defined by the C
standard.
• These functions cannot be used with complex numbers; use the functions of the
same name from the cmath module if you require support for complex numbers.
The distinction between functions which support complex numbers and those which
don’t is made since most users do not want to learn quite as much mathematics as
required to understand complex numbers. Receiving an exception instead of a
complex result allows earlier detection of the unexpected complex number used as a
parameter, so that the programmer can determine how and why it was generated in
the first place.
•
math-Mathematical Functions
The following functions are provided by this module. Except when explicitly noted
otherwise, all return values are floats.
Number-theoretic and representation function Power and logarithmic functions Trigonometric functions
math.ceil(x) math.isfinite(x) math.cbrt(x) math.acos(x)
math.comb(n,k) math.isinf(x) math.exp(x) math.asin(x)
math.copysign(x, y) math.isnan(x) math.exp2(x) math.atan(x)
math.fabs(x) math.isqrt(n) math.expm1(x) math.atan2(y, x)
math.factorial(n) math.lcm(*integers) math.log(x[, base]) math.cos(x)
math.floor(x) math.ldexp(x, i) math.log1p(x) math.dist(p, q)
math.fmod(x, y) math.modf(x) math.log2(x) math.hypot(*coordinates)
math.frexp(x) math.nextafter(x, y, steps=1) math.log10(x) math.sin(x)
math.fsum(iterable) math.perm(n, k=None) math.pow(x, y) math.tan(x)
math.gcd(*integers) math.prod(iterable, *, start=1) math.sqrt(x)
math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) math.remainder(x, y)
math.sumprod(p, q) math.ulp(x)
math.trunc(x)
math-Mathematical Functions
Angular Hyperbolic Special functions Constants
Conversion functions
math.degrees(x) math.acosh(x) math.erf(x) math.pi
math.radians(x) math.asinh(x) math.erfc(x) math.e
math.atanh(x) math.gamma(x) math.tau
math.cosh(x) math.lgamma(x) math.inf
math.sinh(x) math.nan
math.tanh(x)
Time
• The Python time module provides many ways of representing time in code, such as
objects, numbers, and strings. It also provides functionality other than representing
time, like waiting during code execution and measuring the efficiency of your code.
• Since it is a part of Python's standard utility module, there is no need to install the
time module separately. We can use this module by simply importing it using the
following statement
import time
• Epoch: The epoch, which varies depending on the platform, is the moment when
time begins. The epoch is January 1, 1970, 00:00:00 (UTC) on Windows and most
Unix systems, and leap seconds are not included in the calculation of the number of
seconds that have passed since the epoch. We can use time to find out what the
epoch is on a particular platform.gmtime(0).
Important Functions in the time module
• time.time(): The time.time() function in the
time module in python can be defined as the
number of seconds that have passed since the
epoch or the current time passed since the
epoch in seconds. Usually, it is represented in
floating-point numbers.
• time.ctime() : The time.ctime() function in the
time module in python is calculated as the
number of seconds that passed since the epoch
as a variable argument. Then, it returns a time
string that represents the local current time in
24 characters or mentioned milliseconds. If
we don't pass any number of seconds in the
variable argument, then it computed times till
the present.
Important Functions in the time module
• The time.sleep() function in the time
module in python is implemented,
when we want to call for suspension
or delay in the execution of the current
thread for the mentioned number of
seconds. It is widely used to halt the
program or delay the execution for the
specified time that has been set in the
argument.
Random numbers
• We’ve seen some modules or libraries in Python:
• math
• graphics
• A library is a collection of pre-written code indented to be re-used.
• Python comes with a couple hundred modules
• And there are thousands more third-party modules
• Let’s look at another built-in module: random
Randomness
The random module provides functions for generating random numbers
• Computers are deterministic:
• The same instructions given the same data (input) yields the same results every time
• Usually this is what we want!
• When would we want a program to do different things every time it’s run?
• Games
• Simulations of the real world: traffic, weather, galaxies colliding, …
• Cryptography
• For these kinds of problems we want random numbers
• But how can we get real randomness in a deterministic machine?
• There are ways (hooking up a radiation source and look for decays, etc. … ) but it’s not needed
most of the time
• Pseudorandom numbers are usually good enough for our purposes
Randomness
What does “random” mean?
• An even distribution of results
• If we’re rolling a die, we expect 1 about 1/6 th of the time
• And 2 about 1/6 th of the time, 3 about 1/6th …
• Uniform distribution: each possibility is equally likely
• This does NOT mean exactly uniform results!
• If you roll a die six times, you will get some number twice
• What it means is that over a large number of tests, the distribution gets closer to 1/6th each
• An even distribution isn’t enough to be “random”
• What if the die always rolled 1,2,3,4,5,6, 1,2,3,4,5,6,… in that order?
• Random numbers should be unpredictable
• Specifically seeing several numbers in the series should not let us guess the next one
Pseudorandom numbers
Pseudorandom numbers use a deterministic algorithm (a random number
generator, RNG) to generate numbers that appear to be random:
• Approximately uniform
• Hard to predict (but theoretically not impossible)
• ALL RNGs will repeat eventually, a good one does not for a very long time
• A lot of research has gone (and goes) into RNGs
• Linear congruential, alternating shift generator, Mersenne twister, …
• The Art of Computer Programming spends half a book on RNGs.
• Why so much research? They are very important for security!
• Cryptograph uses random numbers for session keys (like automatically generated one-time passwords)
• If someone could predict the output of the RNG, they could predict the key and break in!
Randomness involves information
• Randomness involves information or the lack of it
• Imagine you are standing at the top of a 50-story building.
• If someone asked you to predict what the traffic at ground-level would be, “when will the
next car come around the corner?” you would be in a good position to make a prediction
because you can see the streets for a long way
• If you were standing at ground level next to the same building, you have much less
information and you could not make a very good prediction about the traffic
• With more information, things are less random; with less information, things seem more
random
• That’s why the RNG numbers are called pseudo. With enough information, i.e. the RNG
algorithm used and the seed, you could calculate the numbers just like the computer does.
The numbers ARE predictable in that sense. Since we don’t usually have that info (or want
to do that), the numbers seem random to us!
A good RNG
• What makes a “good” random number generator?
• The same features we mentioned earlier – uniform distribution, being unpredictable
• It must be quick to calculate – a typical game would use millions of them
• Most of them use integer arithmetic because it’s faster than floating point
• It must have a long cycle before it repeats
• EVERY RNG will eventually repeat if run long enough, but if the cycle is a few million numbers,
it will seem “unpredictable” for most humans
• Why will it repeat? Imagine you had a “perfect” RNG which would generate every possible number the
computer could represent (in no predictable order). That’s a finite number of numbers. What if you
asked for another random number after it had done that? It HAS to give you a number it has already
given before! It has no others to give.
Using Python’s random number library
Python’s random number generator is in the random library
• import random or from random import *
• There are several functions in the library.
• https://docs.python.org/3/library/random.html
• Note the big red warning! This RNG should not be used for critical applications like banking!
• Output
Function Arguments
• In Python, functions use following types of arguments:
• Required Arguments
• Keyword Arguments
• Default Arguments
• Variable-length Arguments
Function Arguments- Required Arguments
• Required arguments are the arguments passed to a function in correct positional
order
Function Arguments- Keyword Arguments
• In Python, it also allows to mix and
match the arguments passed.
• This is done by passing the arguments
as argument=value manner. This is
called Keyword Arguments.
• The order of placing the argument
doesn’t cause an error in this case.
• All the keyword arguments passed
must match one of the parameters in
the function definition. No parameters
should receive more than one value.
Function Arguments- Default Arguments
• A defaultargument is an argument that assumes a default value if a value is
not provided in the function call for that argument.
Function Arguments – Variable Length
Arguments
• Sometimes, when we write a program it is not always known how many number of
arguments it will have.
• We can’t create the definition with this uncertainty because if we define a function expecting
4 arguments and it only receives 3, then Python will throw an error.
• To tackle such a scenario, Python has a provision for variable-length arguments. We can use
an asterisk(*) before the variable that will hold the number of arguments together.
• *args in function definition allows you to pass a non keyworded variable-length tuple
argument list to the calling function
• **kwargs in function definition allows you to pass keyworded variable-length dictionary
argument list to the calling function.
• The *args must come after all the positional parameters and **kwargs must be towards the
end.
Function Arguments – Variable Length
Arguments
• Non-keyworded variable-length arguments are received as tuple and keyworded
variable-length arguments are received as dictionary.
• The names args and kwargs are given for representational purposes only. It is not
mandatory to use these names while coding.