You are on page 1of 6

Note: All functions in this document, not covered in ICS 104 lectures are optional

String constants

Some string constants defined in the string module are:

constant value
ascii_lowercase 'abcdefghijklmnopqrstuvwxyz'

ascii_uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

ascii_letters The concatenation of the ascii_lowercase and ascii_uppercase constants

digits '0123456789'
punctuation  '!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~.'

Pseudo-random numbers
 Random numbers are used in games, simulations, testing, security, and privacy applications.
 Python has a built-in random module that you can use to make pseudorandom numbers.
 Some functions of the random module:

Method Description Comment

seed(x) Initialize the random number generator The seed function seeds the


pseudorandom number generator,
taking a value as an argument,. If
the seed function is not called
prior to using random functions,
the default is to use the current
system time in milliseconds from
epoch (1970). A particular seed is
used to generate same random
sequences.

random() Returns a pseudo-random float number in [0.0, 1.0)

uniform(x, y) Returns a pseudo-random floating-point number in [x,  x <= y or y <= x


y]  x and y may be float or
integer values

Alternatively: To return a float value x in the range [a,


b) use:
r = random()
x = a + (b – a)* r

randint(a, b) returns a pseudorandom integer in [a, b]  a and b must be integers


 a <= b

randrange(b) returns a pseudorandom integer in [0, b)  b must be an integer


 0<b

Page 1 of 6
randrange(a,  b) returns a pseudorandom integer in [a, b)  a and b must be integers
 a<b

randrange(a, b , d) returns a pseudorandom integer in  a, b, d must be integers


[a, a+d, a+2*d, a+ 3*d, …, b)  if a < b, d is positive
 if a > b, d is -ve

choice(sequence) returns a random element from the given sequence

choices(sequence, k = n) returns a list of n possibly non-distinct random elements Since k is a keyword-only


from the given sequence argument, it is necessary to
use keywords such as k = 3 

k may be greater than


len(sequence)

sample(sequence, k) returns a list of k distinct random elements from the This method does not change the
given sequence, provided the sequence has distinct original sequence.
elements. k <= len(sequence)

shuffle(sequence)  reorganizes the order of the items in a sequence The original sequence is
modified, a new list is not
returned.

 Use the random.sample function when you want to choose multiple random items from a sequence without
including duplicates.
 Use random.choices function when you want to choose multiple items out of a sequence including . The
chosen items may include duplicates.

Example:

import random
list1 = list(range(10))
print(random.sample(list1, 10))
# Possible output: [6, 9, 0, 2, 4, 3, 5, 1, 8, 7]
print(random.choices(list1, k=10))
# Possible output: [5, 9, 5, 2, 7, 6, 2, 9, 9, 8]
-------------------------------------------------------------------------------------------------------------------
The shuffle function is used to re-arrange the elements of a sequence

import random
mylist = ["apple", "banana", "pineapple", "mango", "orange"]
random.shuffle(mylist)
print(mylist)

Possible output:
['mango', 'banana', 'pineapple', 'orange', 'apple']

Page 2 of 6
Randomly selecting an item from a sequence

from random import choice


companies = ['Aramco', 'STC', 'Mobily', 'Saudia', 'SABIC','Almarai']
print('Randomly selecting a company from a list: ', choice(companies))

Possible output:
Randomly selecting a company from a list: Mobily

How to generate a random letter in Python:


 Method 1: Using string and choice function of string and random modules respectively
import string
import random
randomLetter = random.choice(string.ascii_letters)
print(randomLetter)

Method 2: Using the random module only


import random
# Randomly generate a ascii value from 'a' to 'z' and 'A' to 'Z'
randomLowerLetter = chr(random.randint(ord('a'), ord('z')))
randomUpperLetter = chr(random.randint(ord('A'), ord('Z')))
print(randomLowerLetter, randomUpperLetter)

Alternatively, use:
from random import randint
characters = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ"
    n = len(characters)
    r = randint(0, n - 1)
    print(characters[r]) 

# Generate 10 random sentences


from random import choice
article = ["the", "a", "one", "some"]
noun = ["boy", "girl", "woman", "man", "teacher"]
verb = ["drove", "ran", "walked"]
prep =["to", "from"]
noun2 = ["school", "shop", "hospital"]
for k in range(10):
string = ""
string1 = choice(article)
string2 = choice(noun)
string3 = choice(verb)
string4 = choice(prep)
string5 = choice(noun2)
string = string + string1.capitalize() + " " + string2 + " "\
+ string3 + " " + string4 + " "\
+ string1 + " " + string5 + "."
print(string)

Possible output:
One woman walked from one shop.
The girl ran from the shop.
Page 3 of 6
One girl drove to one school.
The teacher walked from the shop.
Some boy ran to some hospital.
A girl walked from a shop.
Some girl ran from some shop.
A girl ran from a hospital.
The woman ran from the school.
Some girl drove from some hospital.

Randomly selecting multiple distinct items from a sequence


from random import sample
companies = ['Aramco', 'STC', 'Mobily', 'Saudia', 'SABIC','Almarai']
print('Randomly selecting 3 companies from a list: ', sample(companies, 3))

Possible output:
Randomly selecting 3 companies from a list: ['SABIC', 'Mobily', 'Saudia']
-----------------------------------------------------------------------------------------
#Generate 5 distinct random integers in [10, 30) using the sample method
from random import sample
randomList = sample(range(10, 30), 5)
print(randomList)

Possible output:
[21, 25, 28, 16, 24]
----------------------------------------------------------------------------------------------------------------------------------------------------------------
# Generate a list of 10 distinct random numbers in [0, 1000) , but each integer in the
# list must #be divisible by 5
from random import sample
myList = sample(range(0, 1000, 5), 10)
print(myList)

Possible output:
[825, 930, 960, 55, 360, 435, 135, 690, 995, 180]

Generating a list of random integer numbers with possible duplicates

#Generate 5 random integers in [10, 30) using the choices method


from random import sample
randomList = choices(range(10, 30), k = 5)
print(randomList)

Possible outputs:
[24, 22, 23, 23, 12]
[21, 27, 19, 24, 29]
----------------------------------------------------------------------------------------

Page 4 of 6
# Creates a list of 16 random integers in the range 1 to 30 inclusive. List may contain
#duplicates
from random import randint
randomList = []
for i in range(16):
n = randint(1,30)
randomList.append(n)

print(randomList)

Possible output:
[10, 10, 8, 9, 27, 6, 30, 21, 17, 14, 9, 6, 25, 1, 27, 7]

How to generate a random string that may contain duplicate characters


import string
import random
characters = string.ascii_letters + string.digits + string.punctuation
myString = ""
charactersLength = len(characters)
myStringLength = 12 # can have different positive value
for k in range(myStringLength):
randomCharacter = random.choice(characters)
myString += randomCharacter

print(myString)

Possible output:
ntcchk:c4/al

-----------------------------------------------------------------------------------------

Note: The above program can be written as:

import string
import random
characters = string.ascii_letters + string.digits + string.punctuation
myStringLength = 12 # can have different positive value
myString = ''.join(random.choice(characters) for k in range(myStringLength))
print(myString)
-----------------------------------------------------------------------------------------
import string
import random
characters = string.ascii_letters + string.digits + string.punctuation
myString = ""
myStringLength = 12 # can have different positive value
randomCharacterList = random.choices(characters, k = myStringLength)
# Convert list to string
for element in randomCharacterList:
myString += str(element)

print(myString)

Page 5 of 6
How to generate a random string that has no duplicate characters
import string
import random
characters = string.ascii_letters + string.digits + string.punctuation
myString = ""
myStringLength = 12 # can have different positive value
randomCharacterList = random.sample(characters, myStringLength)
# Convert list to string
for element in randomCharacterList:
myString += str(element)

print(myString)

Possible output:
-{~o:4E*U9@>

Page 6 of 6

You might also like