'Python Notes Unit 2
'Python Notes Unit 2
UNIT 2
FUNCTIONS:
Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.
Syntax of Function
deffunction_name(parameters):
"""docstring"""
statement(s)
FUNCTION CALLS:
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
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.
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.
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
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 has a built-in module that you can use for mathematical tasks.
Math Methods
Method Description
RANDOM NUMBERS:
Python Random Module
Python has a built-in module that you can use to make random numbers.
Method Description
getstate() Returns the current internal state of the random number generator
defprint_lyrics():
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.
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 :
Python Iterators
An iterator is an object that can be iterated upon, meaning that you can traverse
through all the values.
while loops
for loops
Example
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
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
Code:
And then, the definite number of lines get printed as below in the output.
>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