0% found this document useful (0 votes)
11 views

Python - Objective 07

The document discusses how to handle user inputs in Python programs. It provides sample code that gets input from the user using the input function, and also shows how to validate inputs using a while loop to ensure only valid data is accepted. The code examples get string and numeric inputs and check them for validity before returning the value.

Uploaded by

instructor Amer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Python - Objective 07

The document discusses how to handle user inputs in Python programs. It provides sample code that gets input from the user using the input function, and also shows how to validate inputs using a while loop to ensure only valid data is accepted. The code examples get string and numeric inputs and check them for validity before returning the value.

Uploaded by

instructor Amer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Learn how

[Header text] to handle user inputs Craig’n’Dave


Craig’n’Dave

TRY
Sample program:
# Handle user inputs

# Function to return an input


def GetInput():
print("1. Option 1")
print("2. Option 2")
print("3. Option 3")
Choice = input("Enter an option number: ")
return Choice

# 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

INVESTIGATE This program gets an input from the user.

Understand how the code works:


• It is good practice to have a function that handles getting an input from the user, returning
# Handle user inputs
the option they have chosen. You could cast the option to another data type before
returning it if that is useful. This example returns a string.
# Function to return an input
• It might seem more obvious to use an integer for a numbered choice, but keyboard inputs
def GetInput():
are always a string.
print("1. Option 1")
print("2. Option 2")
print("3. Option 3") • The options are presented to the user with print statements.
Choice = input("Enter an option number: ")
return Choice
• input is used to pause the execution of the program until an input is
# Main program entered. You can include a prompt for the user too.
Choice = GetInput() • The input is put into a variable called, “Choice”.
print("You chose option {}".format(Choice)) • Choice is returned.

• Choice becomes an input from the user.

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

# Function to return a valid input


def GetInput():
print("a. Option A")
print("b. Option B")
Valid = False
Choice = ""
while not Valid:
Choice = input("Enter an option number: ")
if Choice == "1" or Choice == "2":
Valid = True
else:
print("Invalid option chosen. Try again.")
return Choice

# 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

INVESTIGATE This program validates the input.

Understand how the code works:


• You cannot guarantee the user will enter a valid option. A program needs to either
# Handle user inputs sanitise or validate inputs to prevent the program crashing.
• Sanitising means changing the input into a valid option.
# Function to return a valid input • Validation means preventing invalid inputs or handling them in such a way that the user
def GetInput(): is prompted to enter their input again.
print("a. Option A")
print("b. Option B") • Since you can never tell how many invalid inputs a user may make before entering a valid
Valid = False one, validation requires a while loop; while not Valid means while Valid is false.
Choice = "" (or in other words, while the input is not valid).
while not Valid:
Choice = input("Enter an option number: ")
if Choice == "1" or Choice == "2": • A selection statement is used to check if the input made is valid.
Valid = True • You could do this with the condition in the while loop instead, but this
else: approach gives you more flexibility in handling invalid options.
print("Invalid option chosen. Try again.")
return Choice

# 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

# Function to return an input


def GetInput():
print("What do you think the dice roll will be?")
ValidChoice = False
while not ValidChoice:
Choice = input("Enter a guess between 1 and 6: ")
if Choice.isnumeric():
ValidChoice = True
if not ValidChoice:
print("Invalid choice.")
return Choice

# 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

INVESTIGATE This program checks a user input against a dice roll.

Understand how the code works:


# Handle user inputs
import random
2. return
# Function to ValidChoice
an holds
inputwhether the validation checks have been passed. Until an input has been entered it is not passed.
def GetInput():
print("What do you think the dice roll will be?")
ValidChoice = False 3. While the Choice is not valid…
while not ValidChoice:
Choice = input("Enter a guess between 1 and 6: ") 4. …get the user input.
if Choice.isnumeric():
ValidChoice = True
if not ValidChoice: 5. Check if the input is a number.
print("Invalid choice.") 6. If it is, the input is valid.
return Choice

# 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()

REASON Why is line 3 necessary?

Why is line 4 necessary?

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.

X = float(input("Enter the number of miles: "))

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

MAKE # Guess the number problem


import random
Guess the number problem:
1 point. # Function to return valid input
The computer guesses a number between 1 and 100. def GetInput():

The player must try and guess the number in as few


attempts as possible. Number = input("Enter a number: ")
When the user enters a number they are told if the guess is
too high or too low until the number is guessed correctly.
# Type check
The player is told how many guesses they made. Write a if Number.isnumeric():
program to play the game. ValidInput = True

ValidInput = False
# Validation
while not ValidInput:

return int(Number)

To help you get started,


here is all the code you
need for the first function
with the statements
jumbled up.

PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave

# Subroutine to play guess the number


MAKE
PlayerGuess = GetInput()
Guess the number problem:
1 point. def GuessTheNumber():

The computer guesses a number between 1 and 100.


The player must try and guess the number in as few # Continue playing until player wins
attempts as possible. while PlayerGuess != CPU:
When the user enters a number they are told if the guess is
too high or too low until the number is guessed correctly.
The player is told how many guesses they made. Write a # Initialise variables
program to play the game. random.seed()
CPU = random.randint(1,100)
PlayerGuess = 0
GuessCount = 0

GuessCount = GuessCount + 1

print("You've got it, I chose {}. It took you {} guesses.".format(CPU, GuessCount))

# Check if guess is too high or low


if PlayerGuess < CPU:
print("Too low.")
Here is all the code you elif PlayerGuess > CPU:
need for the second print("Too high.")
function and the main
program with the
statements jumbled up. # Main program
GuessTheNumber()
PYTHON T I M E
Learn how
[Header text] to handle user inputs Craig’n’Dave
Craig’n’Dave

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.

Car park problem:


3 points.
A local car park has the following charges:
Up to 1 hour £1.50
Up to 2 hours £2.90
Up to 3 hours £3.90
Up to 4 hours £4.50
4 hours + £8.00
Between 8pm and 6am Free
Disabled users Free for the first 3 hours
Additional hours charged
Write a program that allows the user to input the time they arrive, the time they leave and whether they are a disabled blue badge
holder. The program outputs the total charge for parking. The times are entered using the 24-hour clock in the format 00:00. E.g. 6pm
would be entered as 18:00.

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:

Input 1 Input 2 Expected output Pass/Fail Test

Problem:

Input 1 Input 2 Expected output Pass/Fail Test

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

Complete all the requirements for the problems you solved?

Start your programs with a comment to describe what they do?

Use a subroutine for the main algorithm in your code?

Use a comment to describe what the subroutine does?

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?

Use variable names that describe the data they hold?

Validate or sanitise the user inputs?

Test your programs against different types of data to check they work?

PYTHON T I M E

You might also like