Exercise 6
First Three Spaces
This question involves finding spaces in a string. In a file spaces.py
, write a program that reports the first three occurrence of a space, using a while loop:
Enter a string: This is the user's input
There's a space in position 4.
There's a space in position 7.
There's a space in position 11.
Make sure your program behaves correctly and doesn't give an error if there are less than three spaces in the string (but otherwise behaves the same).
Enter a string: This is the
There's a space in position 4.
There's a space in position 7.
Reading An Integer
This function takes care of the common task of asking the user to enter a number and using int to convert:
def read_integer(prompt):
"""
Read an integer from the user and return it.
"""
entered = input(prompt)
return int(entered)
It's also fairly common to want the user to enter a number in a specific range. For example, in the guessing game from assignment 1 question 4, you are asking the user to enter a number 1–100.
Improve the function read_integer
in a file read.py
so that takes three arguments: the prompt, a lower bound, and an upper bound on allowable numbers. The function should ask the user to enter values, until they enter one in the given range.
For example, calling read_integer("Enter your guess", 1, 100)
would produce user interaction like this:
Enter your guess (1-100): 102
Must be in the range 1-100
Enter your guess (1-100): 0
Must be in the range 1-100
Enter your guess (1-100): 12
In this case, the function should return 12.
Use a Module
Create a Python program dice.py
that simulates rolling dice. These are standard dice: when rolled, they show number from 1 to 6, each randomly with equal probability.
The random
module contains functions that generate random values. In this problem, you need random integers from 1 to 6. When the program is run, it should look like this:
How many dice? 3
Die 1: 1
Die 2: 5
Die 3: 3
Of course, the actual dice values should be random. Another run:
How many dice? 4
Die 1: 1
Die 2: 1
Die 3: 3
Die 4: 6
Submitting
Submit all of your work through CourSys.