0% found this document useful (0 votes)
19 views7 pages

Screenshot 2024-04-15 at 2.20.06 PM

Toktok

Uploaded by

medkarimji18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views7 pages

Screenshot 2024-04-15 at 2.20.06 PM

Toktok

Uploaded by

medkarimji18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

FERHAT ABBAS Sétif-1 University 1st year Engineering

Faculty of Technology Module: Computing 2


Department of Basic Education in Technology Year: 2023/2024

Practical Class N° 6 - Functions –

1. Introduction: When one starts writing big programs, it is preferable to avoid accumulating
large quantities of lines of code in a single file. An effective approach is to decompose the
program into subprograms with a well-defined and more elementary task. Furthermore, if the
same block of instructions appears multiple times in a program, it is better to define it once
and for all and avoid systematically repeating it. One solution in the Python language is to
define functions.
A.

B. The general syntax of a function in python is as follows:

def name(arg1, arg2, …, argN ) : Where

statement 1  name – the name of function;


 arg1, arg2, …, argN – functions
statement 2 parameters (if there are any);
 statement1, statement2, statementN –
... instructions that are implemented in the
statement N body of the function;
 value – the value returned by the
return value function. (if there are any);

Application 1: Run the code cell below to perform the creation of different functions:
>>> def Hello(): >>> def square(x):
print("Hello!") return x*x

>>> Hello() # call of the function >>> square(2) + 1

>>> def add(a, b): >>> def sqrt(x):


s=a+b return x ** 0.5
return s
>>>print(add(2,3)) >>> sqrt(25)

def square_and_cube(number):
square = number ** 2
cube = number ** 3
return square, cube
# function use
result_square, result_cube = square_and_cube(5)
print("Square:", result_square)
print("Cube:", result_cube)
1
FERHAT ABBAS Sétif-1 University 1st year Engineering
Faculty of Technology Module: Computing 2
Department of Basic Education in Technology Year: 2023/2024

Remarks:

1. The definition of a function starts with the keyword "def" and continues with the
name of the function. You should avoid reserved words (such as if, while...) and
special or accented characters.
2. the execution of a function's code only occurs when you explicitly call (invoke) the
function
3. The use of a function involves two steps:
a) Function Definition:
b) Function Call:

Application 2: Run the code cell below then try to comment every statement:
import math

# Part I: Define functions


def sqr(x):
return x ** 2

def area(r):
return math.pi * sqr(r)

def volume(r, h):


return area(r) * h

# Part II: Main script

# Read input from the user


r = float(input("Enter the radius of the cylinder (r > 0): "))
h = float(input("Enter the height of the cylinder (h > 0): "))

# Call the function to calculate the volume of the cylinder


cylinder_volume = volume(r, h)

# Display the result


print("The volume of the cylinder with radius ",r," and height ",h," is: ",cylinder_volume)

Remarks: ”parameters" and "arguments" :

 Parameters are the variables that are used in a function definition.


 Arguments are the actual values that are passed to a function when it is called.

2
FERHAT ABBAS Sétif-1 University 1st year Engineering
Faculty of Technology Module: Computing 2
Department of Basic Education in Technology Year: 2023/2024

Exercise 1 : Define a function named power that takes two parameters (base and exponent) and
returns the result of raising the base to the power of the exponent

1- Use the ** operator for exponentiation.


2- Use a loop
3- Modify the function to handle negative exponents.

2. Global and local variables:

In Python, variables can have different scopes, and the two main types of variable scopes are global
and local.

a) Global Variables: Variables that are created outside of a function (as in all of
the examples above) are known as global variables. Global variables can be
used by everyone, both inside of functions and outside.

Application 3: Run the code cell below


#1) Create a variable outside of a # 2) Create a variable inside a function, with
#function, and use it inside the function #the same name as the global variable
x = "awesome"
x = "awesome"
def myfunc(): def myfunc():
print("Python is " + x) x = "fantastic"
print("Python is " + x)
myfunc()
myfunc()

print("Python is " + x)
# 3) If you use the global keyword, the # 4) To change the value of a global variable
variable belongs to the global scope: inside a function, refer to the variable by using
the global keyword:
def myfunc():
global x x = "awesome"
x = "fantastic" def myfunc():
global x
myfunc() x = "fantastic"

print("Python is " + x) myfunc()

print("Python is " + x)

3
FERHAT ABBAS Sétif-1 University 1st year Engineering
Faculty of Technology Module: Computing 2
Department of Basic Education in Technology Year: 2023/2024

b) Local Variables: Local variables are declared inside a function and have a local scope.

Application 4: Run the code cell below


def calculate_sum(num1, num2):
local_variable = num1 + num2
return local_variable

result = calculate_sum(3, 4)
print(local_variable) # error

print(result) # Output: 7

Remarks: Scope of Parameters:


 Parameters have a local scope within the function. They are only accessible within the
function's code block.
 Modifying a parameter within the function doesn't affect variables outside the function
with the same name.
3. built-in functions: in python there are two type of functions :
a) User defined functions: are functions that are created by the programmer to perform a
specific task. These functions are defined using the def keyword
b) Built-in functions: in Python are functions that are pre-defined in the Python interpreter
and are always available for use without the need for explicit import.
Some Built-in functions in Python
int() len() lower()
float() max() print()
str() min() input()
abs() sum() type()
pow() list() range()
round() upper() id()

4. External functions: In Python, external functions typically refer to functions that are
defined outside the current script or module and are accessed through imports. There are
several ways to use external functions in Python. Remember to ensure that the external files or
libraries are in the same directory.
a) Importing Modules:
1 Define the functions in a separate Python file (module).
2 Use the import statement in your script to bring in the module.
3 Access the functions using the module name as a prefix.

4
FERHAT ABBAS Sétif-1 University 1st year Engineering
Faculty of Technology Module: Computing 2
Department of Basic Education in Technology Year: 2023/2024

Application 5: Write and save the following code in a file named “ mymodule.py”
# External module: mymodule.py

def my_function():
print("Hello from my_external_function!")

Application 6: Write the following code in new file then Run it.
# Main script
import mymodule

mymodule.my_function()

b) Importing Specific Functions:


You can import specific functions from a module using the from ... import ... syntax.

Application 7: Write and run the following code.


# Main script
from mymodule import my_function

my_function()

c) Using External Libraries:


1) External functions can also be part of external libraries or packages.
2) Libraries and packages are collections of modules that provide pre-written functions to perform
specific tasks.
3) Install the library using a package manager like pip.
4) Import and use functions from the library in your script.

Application 8: Write and run the following code.


import math
import time

result = math.sqrt(25)
print(result)

# display the time


current_time = time.time()
print("Current Time:", current_time)

5
FERHAT ABBAS Sétif-1 University 1st year Engineering
Faculty of Technology Module: Computing 2
Department of Basic Education in Technology Year: 2023/2024

Exercise 2: Factorial Function

Write a function called factorial that takes a non-negative integer as a parameter and returns its
factorial.

Exercise 3: Calculator Function

Write a function called calculator that takes two numbers and an operator (+, -, *, /) as
parameters and performs the corresponding operation. The function should return the result.

Exercise 4: Prime Number Checker

Write a function called is_prime that takes a positive integer as a parameter and returns True
if it is a prime number and False otherwise.

Exercise 5:
Write a Python script that accomplishes the following tasks:

Part I : Define the following functions :

1. : This function reads real numbers from the keyboard and stores them in a
list,
2. : This function calculates the average ̅ of the numbers in the list using
the formula:.

̅ ∑

3. : This function calculates the covariance of the list of numbers stored in


using the formula:

∑ ̅

Part II : Define the main script in which :

1. Reads an integer number from the keyboard.


2. Calls the function to read real numbers.
3. Calculates and displays the average of the numbers by calling the function
4. Calculates and displays the covariance of the numbers by calling the function .
5. Check your functions with the built-in functions in statistics module :
 𝑖𝑚𝑝𝑜𝑟𝑡 𝑠𝑡𝑎𝑡𝑖𝑠𝑡𝑖 𝑠 𝑎𝑠 𝑠𝑡
 𝑝𝑟𝑖 𝑡(𝑠𝑡. 𝑚𝑒𝑎 (𝐿))
 𝑝𝑟𝑖 𝑡(𝑠𝑡. 𝑣𝑎𝑟𝑖𝑎 𝑒(𝐿))

6
FERHAT ABBAS Sétif-1 University 1st year Engineering
Faculty of Technology Module: Computing 2
Department of Basic Education in Technology Year: 2023/2024

Exercise 6 :
Write a Python program that displays all narcissistic numbers less than .

Example:

(3: the number of digits in 153)

(5: the number of digits in 93084)

The program should use the following three functions:

 Decompose(a) : This function decomposes the number a into its digits (using the string type to
facilitate the task of decomposition) and stores the result in a list object.
 Is_narcissistic(a) : This function checks if a number is narcissistic.
 Narcissistics(a, b) : which displays all narcissistic numbers in the interval [a, b].

Homework

Write a Python script that propose the following menu to the user :

------------------------ Menu ---------------------------------

1. Read two natural number and ( ).


2. List of prime number within
3. List of perfect number within
4. List of the friend number within
5. Quit.

Reminder :

 is a prime number if the sum of its divisors equals .


 is a perfect number if the sum of its divisors equals .
 and are friends if sum of divisors of (without ) equals to and if sum of divisors of
(without ) equals to

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy