COSC 1306 COMPUTER SCIENCE AND PROGRAMMING Jehan-François Pâris jfparis@uh.edu Fall 2017 1
THE ONLINE BOOK CHAPTER V MODULES
The problem Writing from scratch Reinventing the wheel Better to use already written code Packaged for our convenience into modules
Two big advantages Writing programs take less time Some of the work was done for us We can trust that code Faster execution Most modules are written in C/C++ Much faster than native Python
What is a module? A file containing Python code designed to be used by other users Ready-to-use functions: math.sin(), … New object definitions: turtle.Screen, turtle.Turtle, … Constants math.pi
Where to find the right modules? On-line Python documentation https://docs.python.org/3/ Global Python Module Index https://docs.python.org/3/py-modindex.html Python books Googling "Python 3 random"
Using modules Must first import the module import turtle import math import random Can mow use objects, functions and constants defined in the imported modules Must prefix names with module name turtle.Turtle, math.sin(), random.random(), math.pi
The math module import math Contains function definitions Power and logarithmic functions math.sqrt(), … Trigonometric functions Functions to convert degrees into radians (and radians into degrees) Hyperbolic functions Special functions
Random module import random Many functions for generating pseudo-random numbers Not really random Result of deterministic arithmetic operations Just appear to be random
A warning "Any one who considers arithmetical methods of producing random digits is, of course, in a state of sin. For, as has been pointed out several times, there is no such thing as a random number– there are only methods to produce random numbers, and a strict arithmetic procedure of course is not such a method.“ John von Neumann
Generating integer RNs random.randomrange(low_end, high_end) Generates uniformly distributed integer random values from low_end (included) to high_end (excluded) random.randomrange(1, 5) will generate vinteger values between 1 and 4
Generating floating-point RNs random.random() Generates uniformly distributed random values from 0 (included) to 1.0 (excluded) That is, [0. 1) To generate random values from min to max, use random.uniform(min, max)