Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Python Programming Unit 6

This document provides an overview of functions in Python, including built-in functions, user-defined functions, and their importance in code reuse and procedural decomposition. It covers various standard functions such as mathematical, time, and random number functions, as well as how to create and use user-defined functions. The document emphasizes the significance of functions in organizing code and enhancing maintainability.

Uploaded by

bittugarg308
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Python Programming Unit 6

This document provides an overview of functions in Python, including built-in functions, user-defined functions, and their importance in code reuse and procedural decomposition. It covers various standard functions such as mathematical, time, and random number functions, as well as how to create and use user-defined functions. The document emphasizes the significance of functions in organizing code and enhancing maintainability.

Uploaded by

bittugarg308
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

PYTHON

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!

• The simplest function is random


chance = random()
• Gives a random floating point number in the range [0.0, 1.0)
• Notation: including 0.0, not including 1.0
• Useful for probabilities, 1 means “will happen”, 0 means “will not happen”
if random() < 0.7: # 70% chance to be True

• What if we want a random float in another range?


• You could multiply and add
score = 90.0 * random() + 10.0
the range of this variable is [10.0, 100.0)
Using random()
• We want the program to print out a greeting
• 30% of the time it should be “hi!”
• 20% of the time it should be “hello”
• And 50% of the time it should be “How are you?”
• rnd = random() # gives a float number between 0 and 1
• if rnd <= 0.3:
print(“hi!”)
elif rnd <= 0.5: #between 0.3 and 0.5, a space of 0.2
print(“hello”)
else:
print(“How are you?”)
Random integers
We could multiply, add and type-cast to get a random integer from the random
function. But there are functions in the library to do it for us.
• The randrange function
• Takes one to three arguments and returns an integer:
• randrange(stop):
between zero (inclusive) and stop (exclusive! Not including stop)
• randrange(start, stop): [start, stop)
between start (inclusive) and stop (exclusive)
• randrange(start, stop, step):
Likewise, but only gives start plus a multiple of step
Random integers
• “Give me a random multiple of 10 between 0 and 100 inclusive.”
• score = randrange(0, 101, 10)
• What if we had written 100 instead? 100 is not included in the possible results

• Also: randint (a, b):


• Inclusive on both ends! The same as randrange (a, b+1)
• Always has two arguments, no more, no less
• Returns numbers in a range starting at a, up to and including b
Random choice
Python can also choose randomly from a list of alternatives:
sacrifice = choice([“time”, “money”, “quality”])
• Must give a list of choices, in square brackets.
• Don’t forget the brackets!
choice (“time”, “money”, “quality”)
TypeError: choice(2) takes 2 positional arguments but four were
given

• Can give a string as an argument instead: answer=choice(“ABCD”)


Returns a random letter from the string
Could get the same result with answer = “ABCD”[randrange(4)]
User Defined Functions
• We can create and define, our own functions in python as well. So, the functions that we create,
are called user defined functions.
• In order to create a user defined function, we need to define it first.
• To define a function, we need to use the, def, keyword. The def keyword, is a reserved word in
python.
• Syntax of user defined function.
• def function_name(parameters):
• # What the function does goes here
• return result
• 1st, you need to use the def keyword, give your function a name, followed by a pair of
parentheses, and end the line, with a colon.
• If your function takes parameters, the names of the parameters are mentioned inside the opening,
and closing of the parentheses.
User Defined Functions
• There's a return statement, that returns the result of the operation on the arguments.
The return statement returns control to the point, where the function was originally
called.
• Note that, the arguments and the return statement, are optional. This means that, you
create a function, that takes in no arguments, and returns nothing.
User Defined Functions
User Defined Functions
• Please note that, in function definition, the parameters that your function uses, are
referred to as arguments, in python programming.
• When you call the function, with specific values for these parameters, they're called
arguments, or actual parameters.
• This is because, the arguments in the function call, are the values used for the
function's parameters.
• Next, you have to begin coding the function, with an indentation block. This
indentation block, is the body of that function, that describes what your function
does.
User Defined Functions Example
User Defined Function Example- Calling
• Calling

• 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.

You might also like