0% found this document useful (0 votes)
23 views6 pages

Python Module Import and Output Exercises

This lab manual document describes Lab 11 on Python modules. The objectives are to import functions, statements, and variables from modules. It discusses how modules allow code reuse by grouping related functions together and importing them into other files rather than copying code. Examples are provided on importing a prime number checking function defined in another file and using it to check if a user-input number is prime. Various ways of importing modules like using import, from/import, and importing all with * are also described.

Uploaded by

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

Python Module Import and Output Exercises

This lab manual document describes Lab 11 on Python modules. The objectives are to import functions, statements, and variables from modules. It discusses how modules allow code reuse by grouping related functions together and importing them into other files rather than copying code. Examples are provided on importing a prime number checking function defined in another file and using it to check if a user-input number is prime. Various ways of importing modules like using import, from/import, and importing all with * are also described.

Uploaded by

Muaath Muqibel
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Course Name/ Code Lab Manual

CS111
Date: 5/13/22

Department of Forensic Computing and Cyber Security


College of Computer Science and Information Technology

Lab11 :  python modules

1. Objectives
This lab is designed to achieve the following goals:
• Be able to import function, statement and variable from modules.

Lab Learning Outcomes (LLO)


 Be able to use the basic concepts of Python to solve problems.
 Understand Python code and explain what the set of instructions do
 Test and debug Python programs to validate syntax and semantic errors

2. Requirements
Using Python 3 IDLE

3. Description
 Last time we created lots of functions to calculate things like Factorial .
 If we had to write every part of a big program, it would take a really
long time Instead, whenever possible we should use functions that
other people have already written.
 This not only saves time, but if it is widely used then it is probably
efficient and well tested.
 Related functions are grouped together, say one for mathematical
functions, one for network connections etc.
 These groups of functions go by different names in various languages:
libraries, packages and modules.
 Python uses a hierarchical system where functions are grouped into
modules, which in turn are grouped into packages
Create Python modules
Say we write a function to test if a number is prime
def isPrime (N):
Course Name/ Code Lab Manual
CS111
Date: 5/13/22

i=2
while i∗∗2 <= N:
if N % i == 0:
return False # Not a prime
i=i+1
return True # Is a prime

 We save this in a file, say [Link] Later we might want to use this
function in a second file
 Rather than copying and pasting the function, we can just import it
Importing Modules in Python
import prime
i = input (”Enter a number : ”)
if prime . isPrime ( i ):
print (”Prime number”)
else :
print (”Not a prime number”)
4 ways to import modules in python:
 Python import statement
 Import with renaming
 Python from...import statement
 Import all *
Scripts and modules
Course Name/ Code Lab Manual
CS111
Date: 5/13/22

In Python programming you will often hear of both “scripts” and “modules”. They
are really the same thing — just a file with Python code in it.
The only difference is really in intent.
 A “script” is a file with Python code that is intended to be run as a program, and
it will typically contain a number of program statements and some print
commands to show the output of the calculations.
 A “module”, on the other hand, is a file with Python code that is intended as
building blocks that other code can build on. It will typically contain a number
of functions (or in more complex code “classes” which we won’t cover in this
course).
Modules are typically not intended to be run directly. Instead their functionality is
intended to be “imported” into scripts or other modules so their code can be reused
there. This way, other modules do not have to contain copies of the code, they can
use then code in other files.
4. Assessment

Exercise 1:
Open a new file in IDLE (“New Window” in the “File” menu) and save it as [Link] in
the directory where you keep the files you create for this course. Then copy the functions
you wrote for Exercise 3: (menu Writing) from lab 9. into this file and save it.
Now open a new file and save it in the same directory. You should now be able to import
your own module like this:
import lab11
Try the following and write what you find.
print(dir(lab11))
['Factorial', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'add', 'divide', 'max', 'multiply', 'subtract', 'sum_number']
Use the function Factorial to calculate (3)
print([Link](3))
Write 3 more different ways to import Factorial ()
Course Name/ Code Lab Manual
CS111
Date: 5/13/22

Exercise 2:
A. What is the output of the following piece of code?
from math import factorial
print([Link](5))
a) 120
b) Nothing is printed
c) Error, method factorial doesn’t exist in math module
d) Error, the statement should be: print(factorial(5))

B. What is the output of print([Link](4.5))?


a) 24
b) 120
c) error
d) 24.0

C. What is the output of the following piece of code?


import datetime
d=[Link](2017,06,18)
print(d)
a) Error
b) 2017-06-18
c) 18-06-2017
d) 06-18-2017
D. What this code show?
import datetime
tday=[Link]()
print(tday)

E. What is the output of the code shown below?


import random
[Link](2,3,4)
Course Name/ Code Lab Manual
CS111
Date: 5/13/22

a) An integer other than 2, 3 and 4


b) Either 2, 3 or 4
c) Error
d) 3 only
F. What is the output of the code shown below?

import sys
[Link](“hello”)
a) ‘hello’
b) ‘hello\n’
c) hello
d) hello5
What is the output shape of the code shown?
import turtle
t=[Link]()
for i in range(0,4):
[Link](100)
[Link](120)
a) square
b) rectangle
c) triangle
d) kite
What is the output of the code shown below?
from platform import platform
print(platform())
What is the output of the code shown below?
from platform import machine
print(machine())

What is the output of the code shown below?


Course Name/ Code Lab Manual
CS111
Date: 5/13/22

from platform import processor


print(processor())
What is the output of the code shown below?

from platform import system

print(system())

Common questions

Powered by AI

The hierarchical system for organizing functions into modules and packages offers benefits such as improved code organization, ease of use, enhanced modularity, and reusability. However, potential drawbacks include increased complexity in dependency management and the risk of namespace conflicts. This system also requires an initial learning curve to understand the appropriate structuring and interaction between different packages and modules, which can be challenging for beginners. Overall, when used correctly, this system contributes to scalable and maintainable code .

The import mechanism in Python enhances functionality by allowing scripts and modules to reuse code from other files without duplicating it. There are four primary ways to import in Python: using the simple import statement (e.g., 'import module_name'), importing with renaming (e.g., 'import module_name as alias'), importing specific attributes from a module (e.g., 'from module_name import attribute'), and using the wildcard '*' to import all module attributes (e.g., 'from module_name import *'). These methods provide flexibility and help manage namespace, optimizing code reuse and modularity .

Scripts and modules both consist of Python code but serve distinct purposes. A script is meant to be executed directly, often containing program statements and print commands to display outputs, whereas a module typically consists of functions meant to be imported and reused in other scripts or modules. While modules are generally not intended to be run directly, they act as building blocks for other programs, promoting code reuse and separation of concerns. Understanding their distinct roles helps in proper program structuring, ensuring that code is organized efficiently and effectively .

Using functions from existing modules is beneficial because these functions are often reliable, efficient, and well-tested, which can save significant development time and effort. This practice also encourages a modular approach to programming, improving code readability and maintainability. Additionally, leveraging established modules means contributing to and relying on community-supported functionalities, reducing the likelihood of errors and bugs in new code, as these modules are continuously optimized and reviewed by a large user base .

The 'datetime' module in Python provides classes for manipulating dates and times, offering a more precise and efficient way to handle temporal data. The code 'tday=datetime.date.today()' retrieves the current local date, providing output in the format 'YYYY-MM-DD'. This functionality facilitates tasks that involve comparing or calculating dates and times without manually parsing strings or numbers, significantly easing date-related operations in programs .

Errors from incorrect module imports or function calls in Python include 'ModuleNotFoundError', which occurs when attempting to import a nonexistent module, and 'AttributeError', which happens when a non-existent function is called from a module. For example, 'from math import factorial' followed by 'print(math.factorial(5))' results in 'NameError' because the 'math' module is not referenced during import; it should be 'print(factorial(5))'. These errors highlight the importance of correct syntax and understanding of module and attribute namespaces .

The 'random.choice()' function selects a random element from a non-empty sequence, such as a list. In the document, the statement 'random.choice(2,3,4)' causes an error because 'choice()' expects a single iterable argument (such as a list or tuple), not multiple individual numbers. Correct usage would be 'random.choice([2, 3, 4])', which would then randomly return either 2, 3, or 4 .

Organizing functions into modules and packages allows for greater efficiency and reusability of code. Modules and packages ensure that related functions are grouped together, which simplifies code management and reduces redundancy by allowing code to be imported instead of rewritten. This organization also facilitates testing and debugging due to the compartmentalization of function implementations, which are often well-tested in widely-used modules. This hierarchical organization supports structured program development and enables more scalable and maintainable code bases .

The Python 'turtle' module uses loops and directional commands to move the turtle object on a graphical interface, allowing it to draw shapes. In the provided loop code, the turtle moves forward by 100 units and then turns left by 120 degrees in a loop that executes four times. This sequence results in the drawing of a triangle, as the sum of the angles in the commands creates a closed three-sided figure with 120-degree internal angles at each vertex .

Using 'sys.stderr.write()' in a Python program will output text directly to the standard error stream without adding a newline, unlike 'print()' which sends output to the standard output stream and typically appends a newline after the text by default. For instance, 'sys.stderr.write("hello")' will output 'hello', whereas 'print("hello")' outputs 'hello\n', with an additional newline at the end .

You might also like