Python - Objective 07
Python - Objective 07
TRY
Sample program:
# Handle user inputs
# Main program
Choice = GetInput()
print("You chose option {}".format(Choice))
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave
Although this program appears to work, it is very poor because it allows the user to
enter a number that is not between 1 and 3, or another character. Programs should
not allow invalid data entries because it can cause the program to crash.
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave
TRY
Sample program:
# Handle user inputs
# Main program
Choice = GetInput()
print("You chose option {}".format(Choice))
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave
# Main program • The use of a Boolean to indicate if the option is valid or not keeps the program easy to understand.
Choice = GetInput() • If the user entered 1 or 2 the choice was valid.
print("You chose option {}".format(Choice))
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave
TRY
Sample program:
# Handle user inputs
import random
# Main program
random.seed()
Roll = random.randint(1,6)
Choice = GetInput()
print("The roll was {}, you guessed {}".format(Roll, Choice))
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave
# Main program
random.seed() 7. If Choice is invalid, output a message and continue the iteration.
Roll = random.randint(1,6)
Choice = GetInput() 1. The program starts here by
generating
print("The roll was {}, you guessed a random number
{}".format(Roll, and
Choice))
getting the user input.
START
HERE
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave
INVESTIGATE
Learning points from this objective:
• Data input from a keyboard is always a string, even if a single character or digit is entered. Casting is used to change the string to another data type.
• You can never guarantee the user will enter data correctly.
• Invalid data will often crash a program if it is not trapped by sanitisation or validation techniques.
• Sanitisation means making data valid before the next process in a program. E.g. converting data to lowercase, removing spaces, having a default value if no
input is made etc.
• Validation means preventing invalid data or handling it in such a way to prevent continuation to the next process until it is valid.
• Validation checks include:
• Presence check - making sure data exists. E.g. the user has input something.
• Type check - the data is in the correct data type. E.g. a number has been entered and not a character.
• Range check - the data is within a range. E.g. If the options are 1-3 then only 1-3 are accepted.
• Length check - the data has the required number of characters. E.g. a password must be at least 8 characters long.
• Format check - the data is of a correct format. E.g. a date of birth is xx/xx/xxxx.
• Other types of validation include check digits, checksums, lookup checks and spell checks.
• Programmers should aim to make their programs as user-friendly as possible by thinking ahead to what inputs a user may make and what outputs would aid
the usability of a program.
• It is good practice to handle user inputs, sanitisation and validation in a function that returns the valid input.
• A while loop will be required for validation because it is not possible to know how many invalid inputs a user may make before a valid data entry.
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave
INVESTIGATE
Program comprehension: ITEM G = int(Input) in line 3 is an example of what?
1. def GramsToOunces():
2. Input = input("Enter grams: ")
3. G = int(Input) G <= 0 in line 4 is an example of what?
4. if G <= 0:
5. print("Invalid input.")
6. Input = input("Enter grams: ")
7. Oz = G * 0.035274
0.035274 in line 7 is an example of what?
8. print("{}g = {}Oz".format(G, Oz))
9. GramsToOunces()
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave
INVESTIGATE
Why are lines 4-6 a poor approach to validation, assuming the
Program comprehension: APPROACH
user always enters a number?
1. def GramsToOunces():
2. Input = input("Enter grams: ")
3. G = int(Input)
Suggest a more appropriate approach to lines 2-6.
4. if G <= 0:
5. print("Invalid input.")
6. Input = input("Enter grams: ")
7. Oz = G * 0.035274
What input validation techniques are necessary to prevent the
8. print("{}g = {}Oz".format(G, Oz))
program crashing?
9. GramsToOunces()
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave
INVESTIGATE
Keywords introduced in this objective:
X = input(Y) X becomes an input string from the keyboard using an optional prompt, Y.
Note that it is common in examinations and textbooks for the input to be combined with casting in one statement. E.g.
This is done for simplicity, but it is an extremely poor approach as it contains no input validation and an incorrect data type input will easily crash the program.
With programs in examinations, the focus is on the core purpose of the algorithm instead of validation in most cases. That doesn’t mean when you write your own
programs you shouldn’t code properly!
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave
ValidInput = False
# Validation
while not ValidInput:
return int(Number)
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave
GuessCount = GuessCount + 1
MAKE
Username problem:
1 point.
A program asks the user to enter their name and date of birth in the format dd/mm/yyyy. This is used to generate suggested usernames.
Suggestions include the name in lowercase concatenated to either their year of birth or an underscore and the number 1. E.g.
John Smith
22/12/1980
The suggestions would be: johnsmith1980 and johnsmith_1
Write a program to suggest usernames.
Automatic feeder:
1 point.
An automatic animal feeder dispenses different types of food and different quantities. “Breakfast” outputs hopper 1, “Lunch” outputs
hopper 2, “Dinner” outputs hopper 1 and hopper 2. The user can enter one of the three options and how much to dispense. E.g.
Breakfast
2
Would result in the output:
Hopper 1
Hopper 1
Write a program to simulate the automatic feeder.
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave
MAKE
Conversion utility problem:
2 points.
A utility program converts metric and imperial measurements. E.g. feet to meters, stones to kilograms. Research the different conversion
calculations and create the utility program. The user can select a conversion they require, input the value and the program outputs the
conversion.
PIN problem:
2 points.
A personal identification number (PIN) is four digits. E.g. 2345. Write a function that allows the user to enter a PIN. The program outputs,
“Hello” if the user enters the PIN correctly. If the user makes three incorrect attempts the program outputs, “Locked out”.
Adder problem:
2 points.
Write a program that repeatedly asks a user for a positive number until no number is entered. The program outputs the highest number,
the total and the average of the numbers entered.
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave
MAKE
Password problem:
3 points.
Write a function that returns a valid password a user has chosen. The password must be at least eight characters and must also contain at
least one uppercase, lowercase and number character.
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave
MAKE
Rock, paper, scissors problem:
3 points.
The computer and player choose one of rock, paper, or scissors. The output of the encounter is then displayed with rock beating scissors,
scissors beating paper, and paper beating rock. The winner scores 1 point for a win. The score for both players should be output. The
game is won when one player reaches 10 points.
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave
EVALUATE
Test tables:
Problem:
Problem:
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave
EVALUATE
Review your solutions:
Did you: Self-assess: Yes/No
Use a comment after each program branch to explain the purpose of the section?
Use a comment before each iteration to explain the purpose of the loop?
Test your programs against different types of data to check they work?
PYTHON T I M E