Python LEC 11 Random
Python LEC 11 Random
Lecture# 11
Lecture Content
1. Introduction to Module, Package, and Library
2. Introduction to Random module
Introduction to Module, Package, and Library:
If you want your code to be well organized, it’s a good idea to start by grouping
related code.
Python modules can get access to code from another module by importing the
file/function using import keyword.
Syntax
random.uniform(a, b)
a Required. A number specifying the lowest possible outcome
b Required. A number specifying the highest possible outcome
Example:
3. Randrange()
The randrange() method returns a randomly selected element from the specified
range.
Syntax
random. randrange(start, stop, step)
Example:
4. Randint()
The randint() method returns an integer number selected element from the
specified range.
Syntax
random.randint(start, stop)
Example:
5. Choice()
The choice() method returns a randomly selected element from the specified
sequence.
The sequence can be a string, a range, a list, a tuple or any other kind of
sequence.
Syntax
random.choice(sequence)
Example:
6. Shuffle()
The shuffle() method takes a sequence, like a list, and reorganize the order of
the items.
Syntax
random.shuffle(sequence)
Example:
7. Sample()
The sample() method returns a list with a randomly selection of a specified
number of items from a sequnce.
Note: This method does not change the original sequence.
Syntax
random.sample(sequence, k) { The size of the returned list }
Example:
EXERCISE:
1. Write a Python program that simulates rolling a six-sided dice. Each time
the program is run, it should generate a random number between 1 and 6 and
display the result.
2. Create a password generator that generates a random password of a specified
length. Ask the user for the desired password length and include a mix of
uppercase letters, lowercase letters, numbers, and special characters in the
generated password.
3. Make list of items given by user then shuffle the items randomly and print
the shuffled list.
4. Create a program that stores a collection of inspirational quotes in a list.
Each time the program is run, it should display a random quote from the list.