0% found this document useful (0 votes)
254 views

'Python Notes Unit 2

Functions allow programmers to organize Python code into reusable chunks. There are two types of functions - built-in functions that are included with Python and user-defined functions created by programmers. Functions are defined using the def keyword followed by the function name and parameters. To call a function, the function name is written along with any arguments. Functions make code more modular and reusable, avoiding repetition.

Uploaded by

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

'Python Notes Unit 2

Functions allow programmers to organize Python code into reusable chunks. There are two types of functions - built-in functions that are included with Python and user-defined functions created by programmers. Functions are defined using the def keyword followed by the function name and parameters. To call a function, the function name is written along with any arguments. Functions make code more modular and reusable, avoiding repetition.

Uploaded by

Veeranan Senniah
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

PYTHON PROGRAMMING

UNIT 2
FUNCTIONS:

In Python, a function is a group of related statements that performs a specific task.

Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.

Furthermore, it avoids repetition and makes the code reusable.

Syntax of Function

deffunction_name(parameters):

"""docstring"""

statement(s)

Above shown is a function definition that consists of the following components.

1. Keyword def that marks the start of the function header.


2. A function name to uniquely identify the function. Function naming follows the
same rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are
optional.

4. A colon (:) to mark the end of the function header.

5. Optional documentation string (docstring) to describe what the function does.


6. One or more valid python statements that make up the function body. Statements
must have the same indentation level (usually 4 spaces).

7. An optional return statement to return a value from the function.

FUNCTION CALLS:

How to call a function in python?

Once we have defined a function, we can call it from another function, program, or
even the Python prompt. To call a function we simply type the function name with
appropriate parameters.

>>>greet('Paul')
Hello, Paul. Good morning!

Types of Functions

Basically, we can divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.


2. User-defined functions - Functions defined by the users themselves.

Type Conversion

The process of converting the value of one data type (integer, string, float, etc.) to
another data type is called type conversion. Python has two types of type
conversion.

1. Implicit Type Conversion

2. Explicit Type Conversion


Implicit Type Conversion

In Implicit type conversion, Python automatically converts one data type to another
data type. This process doesn't need any user involvement.

Let's see an example where Python promotes the conversion of the lower data type
(integer) to the higher data type (float) to avoid data loss.

Example 1: Converting integer to float


num_int = 123
num_flo = 1.23

num_new = num_int + num_flo

print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))

print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
Run Code

When we run the above program, the output will be:

datatype of num_int: <class 'int'>


datatype of num_flo: <class 'float'>

Value of num_new: 124.23


datatype of num_new: <class 'float'>
Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to required
data type. We use the predefined functions like int(), float(), str(), etc to perform
explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes)
the data type of the objects.

Syntax :

<required_datatype>(expression)

Typecasting can be done by assigning the required data type function to the
expression.

Python math Module

Python has a built-in module that you can use for mathematical tasks.

The math module has a set of methods and constants.

Math Methods

Method Description

math.acos() Returns the arc cosine of a number

math.acosh() Returns the inverse hyperbolic cosine of a number

math.asin() Returns the arc sine of a number

math.asinh() Returns the inverse hyperbolic sine of a number


math.atan() Returns the arc tangent of a number in radians

math.atan2() Returns the arc tangent of y/x in radians

math.atanh() Returns the inverse hyperbolic tangent of a number

math.ceil() Rounds a number up to the nearest integer

RANDOM NUMBERS:
Python Random Module

Python has a built-in module that you can use to make random numbers.

The random module has a set of methods:

Method Description

seed() Initialize the random number generator

getstate() Returns the current internal state of the random number generator

setstate() Restores the internal state of the random number generator

getrandbits() Returns a number representing the random bits


 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:

defprint_lyrics():

print("I'm a lumberjack, and I'm okay.")


print('I sleep all night and I work all day.')

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.

DEFINITION AND USES:


Python def keyword is used to define a function, it is placed before a function
name that is provided by the user to create a user-defined function. In python, a
function is a logical unit of code containing a sequence of statements indented
under a name given using the “def” keyword.
Flow of Execution
The flow of execution basically refers to the order in which statements are executed.
That is to say, execution always starts at the first statement of the program.
Moreover, statements execute one at a time. It happens in order, from top to bottom.

Further, functions definitions do not alter the flow of execution of the program.
However, it remembers the statements inside the function do not execute until the
functions is called.
Moreover, function calls are similar to a bypass in the flow of execution. Thus, in
place of going to the next statement, the flow will jump to the first line of the called
function. Then, it will execute all the statements there. After that, it will come back to
pick up where it left off.

It is essential to remember that when reading a program, do not read it from top to
bottom. Instead, keep following the flow of execution. This will ensure that one reads
the def statements as they are scanning from top to bottom.

However, one must skip the statements of the function definition until they reach a
point where that function is called.

PARAMETERSANDARGUMENTS:
A Parameters are passed during the definition of function while Arguments are
passed during the function call.

Example :

1. //here a and b are parameters 


2. //function definition 
3. def add(a,b): 
4. return a+b 
5.  
6. // 12 and 13 are arguments  
7. //function call 
8. result=add(12,13) 
9. print(result) //result is 25 

Python Iterators

An iterator is an object that contains a countable number of values.

An iterator is an object that can be iterated upon, meaning that you can traverse
through all the values.

Technically, in Python, an iterator is an object which implements the iterator


protocol, which consist of the methods __iter__() and __next__().
UPDATING VARIABLES ON PYTHON:
If you try to update a variable that doesn’t exist, you get an error because Python
evaluates the expression on the right side of the assignment operator before it
assigns the resulting value to the name on the left. Before you can update a
variable, you have to initialize it, usually with a simple assignment. In the above
example, x was initialized to 6.
Updating a variable by adding 1 is called an increment; subtracting 1 is called
a decrement. Sometimes programmers also talk about bumping a variable, which
means the same as incrementing it by 1.
Python Loops

Python has two primitive loop commands:

 while loops
 for loops

The while Loop

With the while loop we can execute a set of statements as long as a condition is


true.

Example

Print i as long as i is less than 6:

i = 1
while i< 6:
  print(i)
  i += 1
OUTPUT:
1
2
3
4
5
The while loop requires relevant variables to be ready, in this example we need to
define an indexing variable, i, which we set to 1

 Python Infinite Loop


An Infinite Loop in Python is a continuous repetitive conditional loop that gets

executed until an external factor interferes in the execution flow, like insufficient

CPU memory, a failed feature/ error code that stopped the execution, or a new

feature in the other legacy systems that needs code integration. 

Code:

And then, the definite number of lines get printed as below in the output.

Finishing iterations with continue


Sometimes, you are in a loop and want to finish the current iteration and
immediately jump to the next. In that case, you can use the continue statement to
skip to the next iteration without finishing the body of the loop for the current
iteration.
Here is an example of a loop that copies its input until the user types “done”, but
treats lines that start with the hash character as lines not to be printed (kind of like
Python comments).
Here is a sample run of this new program with continue added:

>hello there
hello there
> # don't print this
> print this!
print this!
> done
Done!
All the lines are printed except the one that starts with the hash sign because when
the continue is executed, it ends the current iteration and jumps back to
the while statement to start the next iteration, thus skipping the print statement.
Definite loops using for
Sometimes we want to loop through a set of things such as a list of words, the lines
in a file, or a list of numbers. When we have a list of things to loop through, we
can construct a definite loop using a for statement. We call the while statement
an indefinite loop because it simply loops until some condition becomes False,
whereas the for loop is looping through a known set of items so it runs through as
many iterations as there are items in the set.
The syntax of a for loop is similar to the while loop in that there is a for statement
and a loop body:
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends:
print('Happy New Year:', friend)
print('Done!')
In Python terms, the variable friends is a list1 of three strings and the for loop goes
through the list and executes the body once for each of the three strings in the list
resulting in this output:
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!
Translating this for loop to English is not as direct as the while, but if you think of
friends as a set, it goes like this: "Run the statements in the body of the for loop
once for each friend in the set named friends."
Looking at the for loop, for and in are reserved Python keywords,
and friend and friends are variables.
for friend in friends:
print('Happy New Year:', friend)
In particular, friend is the iteration variable for the for loop. The
variable friend changes for each iteration of the loop and controls when
the for loop completes. The iteration variable steps successively through the three
strings stored in the friends variable.
Loop patterns
Often we use a for or while loop to go through a list of items or the contents of a
file and we are looking for something such as the largest or smallest value of the
data we scan through.
These loops are generally constructed by:
 Initializing one or more variables before the loop starts
 Performing some computation on each item in the loop body, possibly
changing the variables in the body of the loop
 Looking at the resulting variables when the loop completes
We will use a list of numbers to demonstrate the concepts and construction of these
loop patterns.
Counting and summing loops
For example, to count the number of items in a list, we would write the
following for loop:
count = 0
foritervar in [3, 41, 12, 9, 74, 15]:
count = count + 1
print('Count: ', count)
We set the variable count to zero before the loop starts, then we write a for loop to
run through the list of numbers. Our iteration variable is named itervar and while
we do not use itervar in the loop, it does control the loop and cause the loop body
to be executed once for each of the values in the list.
In the body of the loop, we add 1 to the current value of count for each of the
values in the list. While the loop is executing, the value of count is the number of
values we have seen "so far".
Once the loop completes, the value of count is the total number of items. The total
number "falls in our lap" at the end of the loop. We construct the loop so that we
have what we want when the loop finishes.
Another similar loop that computes the total of a set of numbers is as follows:
total = 0
foritervar in [3, 41, 12, 9, 74, 15]:
total = total + itervar
print('Total: ', total)
In this loop we do use the iteration variable. Instead of simply adding one to
the count as in the previous loop, we add the actual number (3, 41, 12, etc.) to the
running total during each loop iteration. If you think about the variable total, it
contains the "running total of the values so far". So before the loop starts total is
zero because we have not yet seen any values, during the loop total is the running
total, and at the end of the loop total is the overall total of all the values in the list.
As the loop executes, total accumulates the sum of the elements; a variable used
this way is sometimes called an accumulator.
Neither the counting loop nor the summing loop are particularly useful in practice
because there are built-in functions len() and sum() that compute the number of
items in a list and the total of the items in the list respectively.
Maximum and minimum loops
To find the largest value in a list or sequence, we construct the following loop:
largest = None
print('Before:', largest)
foritervar in [3, 41, 12, 9, 74, 15]:
if largest is None or itervar> largest :
largest = itervar
print('Loop:', itervar, largest)
print('Largest:', largest)
When the program executes, the output is as follows:
Before: None
Loop: 3 3
Loop: 41 41
Loop: 12 41
Loop: 9 41
Loop: 74 74
Loop: 15 74
Largest: 74
The variable largest is best thought of as the "largest value we have seen so far".
Before the loop, we set largest to the constant None. None is a special constant
value which we can store in a variable to mark the variable as "empty".
Before the loop starts, the largest value we have seen so far is None since we have
not yet seen any values. While the loop is executing, if largest is None then we
take the first value we see as the largest so far. You can see in the first iteration
when the value of itervar is 3, since largest is None, we immediately set largest to
be 3.
After the first iteration, largest is no longer None, so the second part of the
compound logical expression that checks itervar> largest triggers only when we
see a value that is larger than the "largest so far". When we see a new "even larger"
value we take that new value for largest. You can see in the program output
that largest progresses from 3 to 41 to 74.
At the end of the loop, we have scanned all of the values and the
variable largest now does contain the largest value in the list.
To compute the smallest number, the code is very similar with one small change:
smallest = None
print('Before:', smallest)
foritervar in [3, 41, 12, 9, 74, 15]:
if smallest is None or itervar< smallest:
smallest = itervar
print('Loop:', itervar, smallest)
print('Smallest:', smallest)
Again, smallest is the "smallest so far" before, during, and after the loop executes.
When the loop has completed, smallest contains the minimum value in the list.
Again as in counting and summing, the built-in functions max() and min() make
writing these exact loops unnecessary.
The following is a simple version of the Python built-in min() function:
defmin(values):
smallest = None
for value in values:
if smallest is None or value < smallest:
smallest = value
return smallest
In the function version of the smallest code, we removed all of the print statements
so as to be equivalent to the min function which is already built in to Python

STRINGS :

A string is a sequence
A string is a sequence of characters. You can access the characters one at a time
with the bracket operator:
>>>fruit = 'banana'
>>>letter = fruit[1]
The second statement extracts the character at index position 1 from
the fruit variable and assigns it to the letter variable.
The expression in brackets is called an index. The index indicates which character
in the sequence you want (hence the name).
But you might not get what you expect:
>>>print(letter)
a
For most people, the first letter of "banana" is b, not a. But in Python, the index is
an offset from the beginning of the string, and the offset of the first letter is zero.
>>>letter = fruit[0]
>>>print(letter)
b
So b is the 0th letter ("zero-eth") of "banana", a is the 1th letter ("one-eth"),
and n is the 2th ("two-eth") letter.

String Indexes
You can use any expression, including variables and operators, as an index, but the
value of the index has to be an integer. Otherwise you get:
>>>letter = fruit[1.5]
TypeError: string indices must be integers
Getting the length of a string using len
len is a built-in function that returns the number of characters in a string:

>>>fruit = 'banana'
>>>len(fruit)
6
To get the last letter of a string, you might be tempted to try something like this:
>>>length = len(fruit)
>>>last = fruit[length]
IndexError: string index out of range
The reason for the IndexError is that there is no letter in 'banana' with the index 6.
Since we started counting at zero, the six letters are numbered 0 to 5. To get the
last character, you have to subtract 1 from length:
>>>last = fruit[length-1]
>>>print(last)
a
Alternatively, you can use negative indices, which count backward from the end of
the string. The expression fruit[-1] yields the last letter, fruit[-2] yields the second
to last, and so on
Looping and counting
The following program counts the number of times the letter a appears in a string:
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(count)
This program demonstrates another pattern of computation called a counter. The
variable count is initialized to 0 and then incremented each time an a is found.
When the loop exits, count contains the result: the total number of a's.
String comparison
The comparison operators work on strings. To see if two strings are equal:
if word == 'banana':
print('All right, bananas.')
Other comparison operations are useful for putting words in alphabetical order:
if word <'banana':
print('Your word,' + word + ', comes before banana.')
elif word >'banana':
print('Your word,' + word + ', comes after banana.')
else:
print('All right, bananas.')
Python does not handle uppercase and lowercase letters the same way that people
do. All the uppercase letters come before all the lowercase letters, so:
Your word, Pineapple, comes before banana.
A common way to address this problem is to convert strings to a standard format,
such as all lowercase, before performing the comparison. Keep that in mind in case
you have to defend yourself against a man armed with a Pineapple
string methods
Strings are an example of Python objects. An object contains both data (the actual
string itself) and methods, which are effectively functions that are built into the
object and are available to any instance of the object.
Python has a function called dir which lists the methods available for an object.
The type function shows the type of an object and the dir function shows the
available methods.
>>>stuff = 'Hello world'
>>>type(stuff)
<class'str'>
>>>dir(stuff)
['capitalize', 'casefold', 'center', 'count', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'format_map',
'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable',
'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower',
'lstrip', 'maketrans', 'partition', 'replace', 'rfind',
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
>>>help(str.capitalize)
Help on method_descriptor:

capitalize(...)
S.capitalize() ->str

Return a capitalized version of S, i.e. make the first character


have upper case and the rest lower case.
>>>
While the dir function lists the methods, and you can use help to get some simple
documentation on a method
Calling a method is similar to calling a function (it takes arguments and returns a
value) but the syntax is different. We call a method by appending the method name
to the variable name using the period as a delimiter.
For example, the method upper takes a string and returns a new string with all
uppercase letters:
Instead of the function syntax upper(word), it uses the method
syntax word.upper().
>>>word = 'banana'
>>>new_word = word.upper()
>>>print(new_word)
BANANA
This form of dot notation specifies the name of the method, upper, and the name of
the string to apply the method to, word. The empty parentheses indicate that this
method takes no argument.
A method call is called an invocation; in this case, we would say that we are
invoking upper on the word.
For example, there is a string method named find that searches for the position of
one string within another:
>>>word = 'banana'
>>>index = word.find('a')
>>>print(index)
1
Parsing strings
Often, we want to look into a string and find a substring. For example if we were
presented a series of lines formatted as follows:
From stephen.marquard@ uct.ac.za Sat Jan  5 09:14:16 2008
and we wanted to pull out only the second half of the address (i.e., uct.ac.za) from
each line, we can do this by using the find method and string slicing.
First, we will find the position of the at-sign in the string. Then we will find the
position of the first space after the at-sign. And then we will use string slicing to
extract the portion of the string which we are looking for.
>>>data = 'From [email protected] Sat Jan 5 09:14:16 2008'
>>>atpos = data.find('@')
>>>print(atpos)
21
>>>sppos = data.find(' ',atpos)
>>>print(sppos)
31
>>>host = data[atpos+1:sppos]
>>>print(host)
uct.ac.za
>>>
We use a version of the find method which allows us to specify a position in the
string where we want find to start looking. When we slice, we extract the
characters from "one beyond the at-sign through up to but not including the space
character".

You might also like