Python Notes 6
Python Notes 6
Most programs perform tasks that are large enough to be broken down into several subtasks.
For this reason, programmers usually break down their programs into small manageable
pieces known as functions.
A function is a group of statements that exist within a program for the purpose of performing a specific
task.
Instead of writing a large program as one long sequence of statements, it can be written as
several small functions, each one performing a specific part of the task.
These small functions can then be executed in the desired order to perform the overall task.
A program that has been written with each task in its own function is called a modularized
program.
-
Benefits of Modularizing a Program with Functions
Simpler Code:
A program’s code tends to be simpler and easier to understand when it is broken down into
functions.
Code Reuse :
Functions also reduce the duplication of code within a program. If a specific operation is
performed in several places in a program, a function can be written once to perform that operation,
then be executed any time it is needed.
Better Testing:
Programmers can test each function in a program individually, to determine whether it
correctly performs its operation. This makes it easier to isolate and fix errors.
Easier Facilitation of Teamwork
Functions also make it easier for programmers to work in teams. When a program is developed
as a set of functions that each performs an individual task, then different programmers can be
assigned the job of writing different functions.
When you call a void function, it simply executes the statements it contains and then
terminates.
When you call a value-returning function, it executes the statements that it contains, then
returns a value back to the statement that called it. The input function is an example of a value-
returning function. The int and float functions are also examples of value-returning functions.
Function Names:
Python requires that you follow the same rules that you follow when naming variables, which we
recap here:
1. You cannot use one of Python’s key words as a function name.
2. A function name cannot contain spaces.
3. The first character must be one of the letters a through z, A through Z, or an underscore
character (_).
4. After the first character you may use the letters a through z or A through Z, the digits 0 through
9, or underscores.
5. Uppercase and lowercase characters are distinct.
def function_name():
statement
statement
etc.
The first line is known as the function header. It marks the beginning of the function definition.
Beginning at the next line is a set of statements known as a block. A block is simply a set of statements
that belong together as a group. These statements are performed any time the function is executed.
Notice in the general format that all of the statements in the block are indented. This indentation is
required, because the Python interpreter uses it to tell where the block begins and ends.
Let’s look at an example of a function. Keep in mind that this is not a complete program. We will show
the entire program in a moment.
def message():
print('I am Arthur,')
print('King of the Britons.')
This code defines a function named message. The message function contains a block with two
statements. Executing the function will cause these statements to execute.
Calling a Function
A function definition specifies what a function does, but it does not cause the function to execute. To
execute a function, you must call it. This is how we would call the message function:
message()
When a function is called, the interpreter jumps to that function and executes the statements in its
block. Then, when the end of the block is reached, the interpreter jumps back to the part of the
program that called the function, and the program resumes execution at that point. When this
happens, we say that the function returns.
Program 1
def message():
print('I am Arthur,')
print('King of the Britons.')
message()
Program Output
I am Arthur,
King of the Britons.
Program 2
def main():
print('I have a message for you.')
message()
print('Goodbye!')
def message():
print('I am Arthur,')
print('King of the Britons.')
main()
Program Output
I have a message for you.
I am Arthur,
King of the Britons.
Goodbye!
Program 3
def main():
startup_message()
input('Press Enter to see Step 1.')
step1()
input('Press Enter to see Step 2.')
step2()
input('Press Enter to see Step 3.')
step3()
input('Press Enter to see Step 4.')
step4()
def startup_message():
print('This program tells you how to disassemble laundry dryer.')
print('There are 4 steps in the process.')
print()
def step1():
print('Step 1: Unplug the dryer and move it away from the wall.')
print()
def step2():
print('Step 2: Remove the six screws from the back of the dryer.')
print()
def step3():
print('Step 3: Remove the back panel from the dryer.')
print()
def step4():
print('Step 4: Pull the top of the dryer straight up.')
main()
Program Output
This program tells you how to disassemble a laundry dryer.
There are 4 steps in the process.
Press Enter to see Step 1. Enter
Step 1: Unplug the dryer and move it away from the wall.
Press Enter to see Step 2. Enter
Step 2: Remove the six screws from the back of the dryer.
An error will occur if a statement in one function tries to access a local variable that belongs to
another function. For example, look at Program 4.
Program 4
def main():
get_name()
print('Hello', name) # This causes an error!
def get_name():
name = input('Enter your name: ')
main()
This program has two functions: main and get_name. The name variable is assigned a value that is
entered by the user. This statement is inside the get_name function, so the name variable is local to
that function. This means that the name variable cannot be accessed by statements outside the
get_name function.
The main function calls the get_name function. Then, the statement tries to access the name variable.
This results in an error because the name variable is local to the get_name function, and statements in
the main function cannot access it.
In addition, a local variable cannot be accessed by code that appears inside the function at a point
before the variable has been created. For example:
def bad_function():
print('The value is', val) # This will cause an error!
val = 99
Because a function’s local variables are hidden from other functions, the other functions may have
their own local variables with the same name. For example,
Program 5
def main():
texas()
california()
def texas():
birds = 5000
print('Texas has', birds, 'birds.')
def california():
birds = 8000
print('California has', birds, 'birds.')
main()
Program Output
Texas has 5000 birds.
California has 8000 birds.
Passing Arguments to Functions
Sometimes it is useful not only to call a function, but also to send one or more pieces of data
into the function.
Pieces of data that are sent into a function are known as arguments.
The function can use its arguments in calculations or other operations.
If you want a function to receive arguments when it is called, you must equip the function with
one or more parameter variables.
A parameter variable, often simply called a parameter, is a special variable that is assigned the
value of an argument when a function is called.
Here is an example of a function that has a parameter variable:
def show_double(number):
result = number * 2
print(result)
This function’s name is show_double. Its purpose is to accept a number as an argument and display
the value of that number doubled. Look at the function header and notice the word number that
appear inside the parentheses. This is the name of a parameter variable. This variable will be assigned
the value of an argument when the function is called.
Program 6
def show_double(number):
result = number * 2
print(result)
show_double(5)
Often it’s useful to write functions that can accept multiple arguments.
Program 7
def show_sum(num1, num2):
result = num1 + num2
print(result)
def main():
print('The sum of 12 and 45 is')
show_sum(12, 45)
main()
Program Output
The sum of 12 and 45 is
57
Program 8
def cal_avg(num1, num2, num3):
result = (num1 + num2 + num 3)/3
print(result)
def avg():
print('Average is')
cal_avg(12, 45, 50)
avg()
This program demonstrates passing two string arguments to a function.
Program 9
def reverse_name(first, last):
print(last, first)
def main():
first = input('Enter your first name: ')
last = input('Enter your last name: ')
print('Your name reversed is')
reverse_name(first, last)
main()
Keyword Arguments
Previous programs demonstrate how arguments are passed by position to parameter variables in a
function. Most programming languages match function arguments and parameters this way.
In addition to this conventional form of argument passing, the Python language allows you to write an
argument in the following format, to specify which parameter variable the argument should be passed
to:
parameter_name=value
In this format, parameter_name is the name of a parameter variable, and value is the value being
passed to that parameter. An argument that is written in accordance with this syntax is known as a
keyword argument.
Program 10
def show_interest(principal, rate, periods):
interest = principal * rate * periods
print('The simple interest will be $‘ , interest)
def main():
show_interest (rate=0.01, periods=10, principal=10000.0)
main()
Program Output
The simple interest will be $1000.00.
Program 11
def reverse_name(first, last):
print(last, first)
def main():
first_name = input('Enter your first name: ')
last_name = input('Enter your last name: ')
print('Your name reversed is')
reverse_name(last=last_name, first=first_name)
main()
Program Output
Enter your first name: Matt Enter
Enter your last name: Hoyle Enter
Your name reversed is
Hoyle Matt
Global Variables:
A variable created by an assignment statement that is written outside all the functions in a program
file is called global variable. A global variable can be accessed by any statement in the program file,
including the statements in any function.
Program 12
my_value = 10
def show_value():
print(my_value)
show_value()
Program Output
10
Program 13
number = 0
def show_number():
print('The number you entered is', number)
def main():
number = int(input('Enter a number: '))
show_number()
main()
Program Output
Enter a number: 55 Enter
The number you entered is 55
Program 14
def sum(num1, num2):
result = num1 + num2
return result
def main():
first_age = int(input('Enter your age: '))
second_age = int(input("Enter your best friend's age: "))
total = sum(first_age, second_age)
print('Together you are', total, 'years old.')
main()
Although this function does what it sets out to do, it can be simplified. Because the return statement
can return the value of an expression, you can eliminate the result variable and rewrite the function
as:
def sum(num1, num2):
return num 1 + num 2
This version of the function does not store the value of num1 + num2 in a variable. Instead, it takes
advantage of the fact that the return statement can return the value of an expression. This version of
the function does the same thing as the previous version, but in only one step.
Returning Strings
So far, you’ve seen examples of functions that return numbers. You can also write functions that
return strings. For example, the following function prompts the user to enter his or her name, then
returns the string that the user entered:
def get_name():
name = input('Enter your name: ')
return name
Returning Boolean Values
Python allows you to write Boolean functions, which return either True or False.
You can use a Boolean function to test a condition, then return either True or False to indicate
whether the condition exists.
Boolean functions are useful for simplifying complex conditions that are tested in decision and
repetition structures.
def is_even(number):
if (number % 2) == 0:
status = True
else:
status = False
return status
Returning Multiple Values
In Python, however, you are not limited to returning only one value. You can specify multiple
expressions separated by commas after the return statement, as shown in this general format:
return expression1, expression2, etc.
def get_name():
first = input('Enter your first name: ')
last = input('Enter your last name: ')
return first, last
Program 15: Calculating real roots of the quadratic equation
import math
def quadratic_roots(a, b, c):
discriminant = b**2 - 4*a*c # Calculate the discriminant
# Check if the discriminant is negative (no real roots)
if discriminant < 0:
return "No real roots"
# Calculate the two roots
root1 = (-b + math.sqrt(discriminant)) / (2 * a)
root2 = (-b - math.sqrt(discriminant)) / (2 * a)
return root1, root2
Many of the functions in the math module
Math Module Description
Function
acos(x) Returns the arc cosine of x, in radians.
asin(x) Returns the arc sine of x, in radians.
atan(x) Returns the arc tangent of x, in radians.
ceil(x) Returns the smallest integer that is greater than or equal to x.
cos(x) Returns the cosine of x in radians.
degrees(x) Assuming x is an angle in radians, the function
returns the angle converted to degrees.
exp(x) Returns e^x
floor(x) Returns the largest integer that is less than or equal to x.
hypot(x, y) Returns the length of a hypotenuse that extends from (0, 0) to (x,y)
log(x) Returns the natural logarithm of x.
log10(x) Returns the base-10 logarithm of x.
radians(x) Assuming x is an angle in degrees, the function returns the
angle converted to radians.
sin(x) Returns the sine of x in radians.
sqrt(x) Returns the square root of x.
tan(x) Returns the tangent of x in radians.
Program 16
def main():
number = float(input('Enter a number: '))
square_root = math.sqrt(number)
print('The square root of', number, '0 is', square_root)
main()
Program Output
Enter a number: 25 Enter
The square root of 25.0 is 5.0
Program 17
import math
def main():
a = float(input('Enter the length of side A: '))
b = float(input('Enter the length of side B: '))
c = math.hypot(a, b)
print('The length of the hypotenuse is', c)
main()
Random in Python
The random module in Python is useful for generating random numbers in various programming
scenarios. Some common applications include:
1. Generating scratch cards for online lotteries.
2. Creating CAPTCHA codes.
3. Generating OTPs (One-Time Passwords).
4. Games like LUDO, where dice rolls require random numbers (between 1 and 6).
Functions in the random Module
The random module offers multiple functions to generate random numbers.
randrange():
This function generates a random number between a specified lower limit (inclusive) and upper limit
(exclusive). For example, using randrange(20) will generate a random number between 0 and 19.
Example Code to Generate a Random Number from 0 to 19
import random
a = random.randrange(20)
print(a)
This code will generate a random number between 0 (inclusive) and 20 (exclusive).
Important Notes on randrange()
The lower limit of randrange() is 0 by default if not specified.
randrange() excludes the upper limit, so it will always generate numbers one less than the specified
upper limit.
Example of random()
import random
a = random.random()
print(a)
This code will print a random float in the range [0.0, 1.0).
randint():
The randint() function provides a more straightforward approach to generate random integers within
a specified range.
Syntax:
random.randint(L,U)
L- lower limit, U-upper limit including both.
a - The lower limit of the range, b- The upper limit of the range.
The function returns a float in the range [a, b], where a and b are inclusive. If a is greater than b,
Python will swap them internally.
Example of uniform()
import random
a = random.uniform(1.5, 5.5)
print(a)
This code will output a random floating-point number between 1.5 and 5.5, including both 1.5 and 5.5
as possible values.
choice():
The choice() function in Python’s random module is used to select a random item from a sequence,
such as a list, tuple, or string.
Syntax
random.choice(sequence)
sequence: This can be any non-empty sequence (like a list, tuple, or string) from which a random
element will be selected.
Example of choice()
import random
fruits = ["apple", "banana", "cherry", "date"]
selected_fruit = random.choice(fruits)
print(selected_fruit)
import random
letter = random.choice("ABCDEFG")
print(letter)
shuffle():
The shuffle() function in Python's random module is used to randomly reorder the elements of a list
in place. This means it modifies the original list by shuffling the elements randomly.
Syntax
random.shuffle(sequence)
sequence: This is the list (or any mutable sequence) to be shuffled. shuffle() does not work on
immutable sequences like tuples or strings.
Example of shuffle()
import random
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)
This code will print the numbers list in a random order, such as [3, 1, 5, 2, 4]. Every time you run it,
the order may differ.
Lambda Function:
Python Lambda Functions are anonymous functions means that the function is without a name. As
we already know the def keyword is used to define a normal function in Python. Similarly,
the lambda keyword is used to define an anonymous function in Python.
Syntax
lambda arguments : expression
Program 1
# Define a function using 'def'
def f(x):
return x + 6
print(f(3.14))
# Define the same function using 'lambda'
f = lambda x: x+6
print(f(3.14))
Program 2
f = lambda x : x + 10
print(f(5))
Program 3
f = lambda x, y : x * y
print(f(5, 6))
Program 4
g = lambda a, b, c : a + b + c
print(g(5, 6, 2))
SymPy Module:
SymPy is a powerful Python library for symbolic mathematics. It provides tools for performing
algebraic manipulations, calculus operations, solving equations, and much more. Below are various
examples demonstrating different functionalities of SymPy.
Define symbolic variables using the keyword symbols:
import sympy as sp
x, y, z = sp.symbols('x y z')
The factor()function in SymPy is used to factorize algebraic expressions. It breaks down expressions
into irreducible factors over various domains. The expand()function in SymPy is used to expand the
expressions.
import sympy as sp Output:
x = sp.symbols('x')
exp1 = x**2 - 3*x - 4 (x - 4)*(x + 1)
exp2=(x-4)*(x-1/5) x**2 - 4.2*x + 0.8
factored_exp1 = sp.factor(exp1)
expanded_exp2 = sp.expand(exp2)
print(factored_exp1)
print(expanded_exp2)
Calculus:
The real power of a symbolic computation system such as SymPy is the ability to do all sorts of
computations symbolically. SymPy can simplify expressions, compute derivatives, integrals, and
limits, solve equations, work with matrices, and much, much more, and do it all symbolically.
Find derivative, integration, limits, solve quadratic equation:
# import everything from sympy module
from sympy import *
Solving Equations:
To solve equations in Python using the sympy library, you can follow these steps:
1. Import the necessary functions from sympy.
2. Define the symbolic variables.
3. Define the equation.
4. Use the solve function to solve the equation.
Example 1: Solving a Linear Equation
Solve the equation 2x+3=7.
import sympy as sp
x = sp.symbols('x') # Define the variable
equation = sp.Eq(2 * x + 3, 7) # Define the equation
solution = sp.solve(equation, x) # Solve the equation
print("The solution to the equation is: x =",solution) # Print the solution
import sympy as sp
x = sp.symbols('x') # Define the variable
equation = sp.Eq(x**2 - 4 * x + 3, 0) # Define the equation
solution = sp.solve(equation, x) # Solve the equation
print("The solutions to the equation x^2 - 4x + 3 = 0 are: x = ",solution)
# Print the solution
Output:
The solutions to the equation x^2 - 4x + 3 = 0 are: x = [1, 3]
import sympy as sp
x, y = sp.symbols('x y') # Define the variables
equations = [sp.Eq(2 * x + 3 * y, 6), sp.Eq(x - y, 2)] # Define the system of equations
solution = sp.solve(equations, (x, y)) # Solve the system of equations
print("The solutions to the system of equations are: x =", solution[x], "y =", solution[y])
# Print the solution
Output:
The solutions to the system of equations are: x = 12/5 y = 2/5
print("The solutions to the equation sin(x) = 1/2 are: x =", solution) # Print the solution
Output:
The solutions to the equation sin(x) = 1/2 are: x = [0.523598775598299, 2.61799387799149]