If Input Not Correct Format Give Input Again Python
eight
INPUT VALIDATION
Input validation code checks that values entered by the user, such as text from the input() role, are formatted correctly. For example, if you want users to enter their ages, your code shouldn't take nonsensical answers such every bit negative numbers (which are outside the range of acceptable integers) or words (which are the wrong data type). Input validation tin can also prevent bugs or security vulnerabilities. If you implement a withdrawFromAccount() role that takes an argument for the amount to subtract from an business relationship, you lot demand to ensure the amount is a positive number. If the withdrawFromAccount() function subtracts a negative number from the account, the "withdrawal" will end up calculation money!
Typically, we perform input validation past repeatedly asking the user for input until they enter valid text, equally in the following example:
while True:
print('Enter your historic period:')
age = input()
try:
age = int(historic period)
except:
print('Please utilise numeric digits.')
continue
if age < 1:
print('Delight enter a positive number.')
continue
break
impress(f'Your age is {age}.')
When you run this program, the output could wait similar this:
Enter your age:
five
Please use numeric digits.
Enter your age:
-2
Please enter a positive number.
Enter your age:
xxx
Your age is 30.
When you run this code, you'll be prompted for your age until you lot enter a valid one. This ensures that by the time the execution leaves the while loop, the historic period variable volition incorporate a valid value that won't crash the programme later on on.
However, writing input validation lawmaking for every input() call in your programme quickly becomes tedious. Too, y'all may miss certain cases and allow invalid input to pass through your checks. In this affiliate, you'll acquire how to use the third-political party PyInputPlus module for input validation.
The PyInputPlus Module
PyInputPlus contains functions similar to input() for several kinds of data: numbers, dates, email addresses, and more. If the user e'er enters invalid input, such as a desperately formatted date or a number that is outside of an intended range, PyInputPlus will reprompt them for input just like our code in the previous section did. PyInputPlus also has other useful features like a limit for the number of times it reprompts users and a timeout if users are required to respond inside a time limit.
PyInputPlus is non a part of the Python Standard Library, then yous must install it separately using Pip. To install PyInputPlus, run pip install --user pyinputplus from the command line. Appendix A has complete instructions for installing 3rd-political party modules. To check if PyInputPlus installed correctly, import it in the interactive trounce:
>>> import pyinputplus
If no errors announced when you import the module, it has been successfully installed.
PyInputPlus has several functions for different kinds of input:
inputStr() Is like the born input() function simply has the general PyInputPlus features. You tin also pass a custom validation function to it
inputNum() Ensures the user enters a number and returns an int or float, depending on if the number has a decimal point in it
inputChoice() Ensures the user enters ane of the provided choices
inputMenu() Is similar to inputChoice(), but provides a bill of fare with numbered or lettered options
inputDatetime() Ensures the user enters a engagement and fourth dimension
inputYesNo() Ensures the user enters a "yep" or "no" response
inputBool() Is similar to inputYesNo(), but takes a "Truthful" or "False" response and returns a Boolean value
inputEmail() Ensures the user enters a valid electronic mail address
inputFilepath() Ensures the user enters a valid file path and filename, and tin can optionally check that a file with that name exists
inputPassword() Is like the built-in input(), but displays * characters every bit the user types so that passwords, or other sensitive information, aren't displayed on the screen
These functions volition automatically reprompt the user for equally long as they enter invalid input:
>>> import pyinputplus as pyip
>>> response = pyip.inputNum()
v
'five' is not a number.
42
>>> response
42
The every bit pyip code in the import argument saves us from typing pyinputplus each time nosotros desire to telephone call a PyInputPlus office. Instead nosotros can use the shorter pyip proper name. If you have a look at the example, you see that unlike input(), these functions render an int or float value: 42 and 3.14 instead of the strings '42' and '3.xiv'.
Just equally you can pass a string to input() to provide a prompt, you lot can pass a string to a PyInputPlus function's prompt keyword argument to brandish a prompt:
>>> response = input('Enter a number: ')
Enter a number: 42
>>> response
'42'
>>> import pyinputplus as pyip
>>> response = pyip.inputInt(prompt='Enter a number: ')
Enter a number: cat
'true cat' is not an integer.
Enter a number: 42
>>> response
42
Utilise Python's help() office to find out more about each of these functions. For example, help(pyip.inputChoice) displays aid information for the inputChoice() function. Consummate documentation can be plant at https://pyinputplus.readthedocs.io/.
Unlike Python's born input(), PyInputPlus functions have several additional features for input validation, as shown in the side by side section.
The min, max, greaterThan, and lessThan Keyword Arguments
The inputNum(), inputInt(), and inputFloat() functions, which take int and float numbers, also take min, max, greaterThan, and lessThan keyword arguments for specifying a range of valid values. For example, enter the following into the interactive beat:
>>> import pyinputplus equally pyip
>>> response = pyip.inputNum('Enter num: ', min=4)
Enter num:3
Input must be at minimum four.
Enter num:iv
>>> response
four
>>> response = pyip.inputNum('Enter num: ', greaterThan=four)
Enter num: 4
Input must be greater than 4.
Enter num: 5
>>> response
5
>>> response = pyip.inputNum('>', min=4, lessThan=vi)
Enter num: 6
Input must be less than 6.
Enter num: 3
Input must be at minimum 4.
Enter num: 4
>>> response
4
These keyword arguments are optional, just if supplied, the input cannot be less than the min statement or greater than the max argument (though the input can be equal to them). Also, the input must be greater than the greaterThan and less than the lessThan arguments (that is, the input cannot be equal to them).
The blank Keyword Argument
By default, bare input isn't allowed unless the blank keyword argument is ready to Truthful:
>>> import pyinputplus as pyip
>>> response = pyip.inputNum('Enter num: ')
Enter num:(bare input entered here)
Blank values are not allowed.
Enter num: 42
>>> response
42
>>> response = pyip.inputNum(blank=True)
(blank input entered here)
>>> response
''
Use blank=True if yous'd similar to make input optional so that the user doesn't need to enter anything.
The limit, timeout, and default Keyword Arguments
Past default, the PyInputPlus functions will continue to enquire the user for valid input forever (or for as long every bit the program runs). If you'd like a function to stop request the user for input after a certain number of tries or a certain amount of time, you tin can utilise the limit and timeout keyword arguments. Pass an integer for the limit keyword argument to decide how many attempts a PyInputPlus role will make to receive valid input before giving upward, and pass an integer for the timeout keyword statement to determine how many seconds the user has to enter valid input before the PyInputPlus part gives up.
If the user fails to enter valid input, these keyword arguments will cause the function to raise a RetryLimitException or TimeoutException, respectively. For case, enter the following into the interactive shell:
>>> import pyinputplus as pyip
>>> response = pyip.inputNum(limit=2)
blah
'blah' is not a number.
Enter num: number
'number' is not a number.
Traceback (about recent telephone call last):
--snip--
pyinputplus.RetryLimitException
>>> response = pyip.inputNum(timeout=10)
42 (entered after 10 seconds of waiting)
Traceback (about recent phone call last):
--snip--
pyinputplus.TimeoutException
When you utilise these keyword arguments and too pass a default keyword argument, the function returns the default value instead of raising an exception. Enter the following into the interactive crush:
>>> response = pyip.inputNum(limit=2, default='Northward/A')
howdy
'hi' is not a number.
earth
'world' is non a number.
>>> response
'Due north/A'
Instead of raising RetryLimitException, the inputNum() office simply returns the string 'N/A'.
The allowRegexes and blockRegexes Keyword Arguments
You can also use regular expressions to specify whether an input is allowed or not. The allowRegexes and blockRegexes keyword arguments take a list of regular expression strings to determine what the PyInputPlus function will take or reject every bit valid input. For example, enter the following code into the interactive shell so that inputNum() will accept Roman numerals in addition to the usual numbers:
>>> import pyinputplus as pyip
>>> response = pyip.inputNum(allowRegexes=[r'(I|5|X|L|C|D|Yard)+', r'zero'])
XLII
>>> response
'XLII'
>>> response = pyip.inputNum(allowRegexes=[r'(i|v|ten|fifty|c|d|m)+', r'zero'])
xlii
>>> response
'xlii'
Of course, this regex affects only what messages the inputNum() function volition take from the user; the function will still accept Roman numerals with invalid ordering such as 'XVX' or 'MILLI' because the r'(I|V|X|Fifty|C|D|M)+' regular expression accepts those strings.
You tin can also specify a list of regular expression strings that a PyInputPlus role won't accept by using the blockRegexes keyword argument. Enter the following into the interactive shell so that inputNum() won't accept even numbers:
>>> import pyinputplus as pyip
>>> response = pyip.inputNum(blockRegexes=[r'[02468]$'])
42
This response is invalid.
44
This response is invalid.
43
>>> response
43
If you specify both an allowRegexes and blockRegexes statement, the allow listing overrides the cake list. For case, enter the post-obit into the interactive shell, which allows 'caterpillar' and 'category' but blocks anything else that has the word 'cat' in information technology:
>>> import pyinputplus as pyip
>>> response = pyip.inputStr(allowRegexes=[r'caterpillar', 'category'],
blockRegexes=[r'cat'])
true cat
This response is invalid.
catastrophe
This response is invalid.
category
>>> response
'category'
The PyInputPlus module's functions can save you from writing tedious input validation lawmaking yourself. Just there'due south more to the PyInputPlus module than what has been detailed here. Yous can examine its full documentation online at https://pyinputplus.readthedocs.io/.
Passing a Custom Validation Part to inputCustom()
Yous tin can write a function to perform your own custom validation logic by passing the function to inputCustom(). For example, say you want the user to enter a serial of digits that adds up to 10. At that place is no pyinputplus.inputAddsUpToTen() function, but y'all can create your own office that:
- Accepts a single string argument of what the user entered
- Raises an exception if the string fails validation
- Returns None (or has no return statement) if inputCustom() should return the cord unchanged
- Returns a not-None value if inputCustom() should return a dissimilar string from the one the user entered
- Is passed equally the first argument to inputCustom()
For example, we can create our own addsUpToTen() function, and then pass it to inputCustom(). Notation that the function call looks similar inputCustom(addsUpToTen) and non inputCustom(addsUpToTen()) because nosotros are passing the addsUpToTen() function itself to inputCustom(), not calling addsUpToTen() and passing its render value.
>>> import pyinputplus equally pyip
>>> def addsUpToTen(numbers):
...numbersList = list(numbers)
...for i, digit in enumerate(numbersList):
...numbersList[i] = int(digit)
...if sum(numbersList) != 10:
...heighten Exception('The digits must add upwards to x, not %s.' %
(sum(numbersList)))
...render int(numbers) # Return an int form of numbers.
...
>>> response = pyip.inputCustom(addsUpToTen) # No parentheses after
addsUpToTen here.
123
The digits must add up to 10, not 6.
1235
The digits must add up to ten, not 11.
1234
>>> response # inputStr() returned an int, not a cord.
1234
>>> response = pyip.inputCustom(addsUpToTen)
howdy
invalid literal for int() with base ten: 'h'
55
>>> response
The inputCustom() function also supports the full general PyInputPlus features, such as the blank, limit, timeout, default, allowRegexes, and blockRegexes keyword arguments. Writing your ain custom validation function is useful when it'southward otherwise difficult or impossible to write a regular expression for valid input, equally in the "adds up to ten" example.
Project: How to Go along an Idiot Busy for Hours
Let'south utilize PyInputPlus to create a unproblematic plan that does the post-obit:
- Ask the user if they'd similar to know how to keep an idiot decorated for hours.
- If the user answers no, quit.
- If the user answers yep, get to Stride i.
Of grade, we don't know if the user will enter something besides "yes" or "no," then we need to perform input validation. It would besides be convenient for the user to exist able to enter "y" or "north" instead of the full words. PyInputPlus's inputYesNo() role will handle this for us and, no matter what example the user enters, return a lowercase 'yes' or 'no' string value.
When you run this program, it should look like the post-obit:
Want to know how to keep an idiot busy for hours?
sure
'sure' is not a valid yeah/no response.
Want to know how to go along an idiot decorated for hours?
yes
Want to know how to continue an idiot busy for hours?
y
Want to know how to proceed an idiot busy for hours?
Yep
Want to know how to proceed an idiot busy for hours?
Yep
Desire to know how to proceed an idiot busy for hours?
YES!!!!!!
'YES!!!!!!' is not a valid yep/no response.
Desire to know how to go on an idiot busy for hours?
TELL ME HOW TO KEEP AN IDIOT BUSY FOR HOURS.
'TELL ME HOW TO Proceed AN IDIOT BUSY FOR HOURS.' is non a valid yeah/no response.
Want to know how to keep an idiot busy for hours?
no
Give thanks you lot. Have a nice day.
Open up a new file editor tab and save information technology as idiot.py. So enter the post-obit code:
import pyinputplus as pyip
This imports the PyInputPlus module. Since pyinputplus is a bit much to blazon, we'll use the name pyip for short.
while True:
prompt = 'Want to know how to keep an idiot busy for hours?\due north'
response = pyip.inputYesNo(prompt)
Adjacent, while True: creates an space loop that continues to run until information technology encounters a interruption statement. In this loop, we call pyip.inputYesNo() to ensure that this function call won't return until the user enters a valid answer.
if response == 'no':
intermission
The pyip.inputYesNo() call is guaranteed to simply return either the string aye or the cord no. If it returned no, then our program breaks out of the infinite loop and continues to the last line, which thanks the user:
print('Thank you. Have a nice day.')
Otherwise, the loop iterates once once again.
You can as well make use of the inputYesNo() office in non-English language languages by passing yesVal and noVal keyword arguments. For example, the Spanish version of this programme would have these 2 lines:
prompt = '¿Quieres saber cómo mantener ocupado a un idiota durante horas?\n'
response = pyip.inputYesNo(prompt, yesVal='sí', noVal='no')
if response == 'sí':
Now the user can enter either sí or s (in lower- or uppercase) instead of aye or y for an affirmative answer.
Project: Multiplication Quiz
PyInputPlus's features can be useful for creating a timed multiplication quiz. By setting the allowRegexes, blockRegexes, timeout, and limit keyword argument to pyip.inputStr(), you can exit most of the implementation to PyInputPlus. The less lawmaking y'all need to write, the faster y'all tin write your programs. Permit's create a program that poses 10 multiplication problems to the user, where the valid input is the trouble's correct reply. Open a new file editor tab and save the file as multiplicationQuiz.py.
Commencement, we'll import pyinputplus, random, and time. We'll proceed rails of how many questions the plan asks and how many correct answers the user gives with the variables numberOfQuestions and correctAnswers. A for loop volition repeatedly pose a random multiplication problem 10 times:
import pyinputplus as pyip
import random, time
numberOfQuestions = 10
correctAnswers = 0
for questionNumber in range(numberOfQuestions):
Inside the for loop, the program will pick two single-digit numbers to multiply. We'll utilize these numbers to create a #Q: Due north × Northward = prompt for the user, where Q is the question number (1 to ten) and N are the two numbers to multiply.
# Option two random numbers:
num1 = random.randint(0, 9)
num2 = random.randint(0, nine)
prompt = '#%southward: %s 10 %s = ' % (questionNumber, num1, num2)
The pyip.inputStr() function will handle most of the features of this quiz program. The argument we pass for allowRegexes is a list with the regex string '^%s$', where %s is replaced with the correct answer. The ^ and % characters ensure that the answer begins and ends with the correct number, though PyInputPlus trims any whitespace from the outset and terminate of the user's response beginning just in case they inadvertently pressed the spacebar before or after their answer. The statement nosotros pass for blocklistRegexes is a listing with ('.*', 'Incorrect!'). The starting time cord in the tuple is a regex that matches every possible string. Therefore, if the user response doesn't match the right answer, the program volition reject any other answer they provide. In that example, the 'Incorrect!' string is displayed and the user is prompted to answer once more. Additionally, passing 8 for timeout and 3 for limit volition ensure that the user only has 8 seconds and 3 tries to provide a correct answer:
attempt:
# Correct answers are handled by allowRegexes.
# Wrong answers are handled by blockRegexes, with a custom bulletin.
pyip.inputStr(prompt, allowRegexes=['^%s$' % (num1 * num2)],
blockRegexes=[('.*', 'Incorrect!')],
timeout=8, limit=3)
If the user answers later the 8-2nd timeout has expired, even if they answer correctly, pyip.inputStr() raises a TimeoutException exception. If the user answers incorrectly more than three times, it raises a RetryLimitException exception. Both of these exception types are in the PyInputPlus module, so pyip. needs to prepend them:
except pyip.TimeoutException:
impress('Out of fourth dimension!')
except pyip.RetryLimitException:
impress('Out of tries!')
Recall that, just like how else blocks can follow an if or elif block, they can optionally follow the final except block. The code inside the following else block will run if no exception was raised in the effort cake. In our example, that ways the code runs if the user entered the correct answer:
else:
# This block runs if no exceptions were raised in the attempt block.
print('Right!')
correctAnswers += 1
No thing which of the iii messages, "Out of time!", "Out of tries!", or "Correct!", displays, let'due south identify a ane-second interruption at the stop of the for loop to requite the user time to read information technology. Subsequently the program has asked ten questions and the for loop continues, let's show the user how many correct answers they made:
time.slumber(1) # Cursory pause to let user see the issue.
print('Score: %south / %s' % (correctAnswers, numberOfQuestions))
PyInputPlus is flexible enough that you can use information technology in a wide variety of programs that take keyboard input from the user, as demonstrated past the programs in this chapter.
Summary
It's easy to forget to write input validation code, but without information technology, your programs will almost certainly have bugs. The values you expect users to enter and the values they actually enter can be completely different, and your programs need to be robust enough to handle these infrequent cases. You tin apply regular expressions to create your ain input validation code, but for common cases, it'south easier to utilise an existing module, such as PyInputPlus. You lot tin can import the module with import pyinputplus every bit pyip so that y'all tin can enter a shorter proper noun when calling the module'due south functions.
PyInputPlus has functions for entering a variety of input, including strings, numbers, dates, yes/no, True/False, emails, and files. While input() ever returns a string, these functions return the value in an appropriate data type. The inputChoice() part allow you to select one of several pre-selected options, while inputMenu() as well adds numbers or letters for quick selection.
All of these functions take the following standard features: stripping whitespace from the sides, setting timeout and retry limits with the timeout and limit keyword arguments, and passing lists of regular expression strings to allowRegexes or blockRegexes to include or exclude particular responses. You'll no longer need to write your own boring while loops that check for valid input and reprompt the user.
If none of the PyInputPlus module'due south, functions fit your needs, but you'd notwithstanding like the other features that PyInputPlus provides, you can call inputCustom() and pass your own custom validation role for PyInputPlus to employ. The documentation at https://pyinputplus.readthedocs.io/en/latest/ has a complete listing of PyInputPlus'due south functions and additional features. There's far more in the PyInputPlus online documentation than what was described in this chapter. At that place's no apply in reinventing the cycle, and learning to apply this module will save y'all from having to write and debug lawmaking for yourself.
Now that you have expertise manipulating and validating text, information technology'due south time to learn how to read from and write to files on your calculator'southward hard drive.
Practice Questions
i. Does PyInputPlus come with the Python Standard Library?
2. Why is PyInputPlus normally imported with import pyinputplus as pyip?
3. What is the deviation between inputInt() and inputFloat()?
4. How tin you ensure that the user enters a whole number between 0 and 99 using PyInputPlus?
five. What is passed to the allowRegexes and blockRegexes keyword arguments?
half dozen. What does inputStr(limit=3) practice if blank input is entered three times?
seven. What does inputStr(limit=3, default='hello') do if blank input is entered three times?
Practice Projects
For practice, write programs to do the following tasks.
Sandwich Maker
Write a program that asks users for their sandwich preferences. The program should use PyInputPlus to ensure that they enter valid input, such as:
- Using inputMenu() for a bread type: wheat, white, or sourdough.
- Using inputMenu() for a protein blazon: craven, turkey, ham, or tofu.
- Using inputYesNo() to ask if they want cheese.
- If so, using inputMenu() to ask for a cheese type: cheddar, Swiss, or mozzarella.
- Using inputYesNo() to enquire if they desire mayo, mustard, lettuce, or tomato plant.
- Using inputInt() to inquire how many sandwiches they want. Make sure this number is one or more.
Come up up with prices for each of these options, and have your plan display a full cost after the user enters their pick.
Write Your Ain Multiplication Quiz
To see how much PyInputPlus is doing for you lot, effort re-creating the multiplication quiz project on your ain without importing it. This program will prompt the user with x multiplication questions, ranging from 0 × 0 to 9 × 9. Y'all'll demand to implement the post-obit features:
- If the user enters the correct reply, the program displays "Right!" for 1 second and moves on to the side by side question.
- The user gets 3 tries to enter the right answer before the program moves on to the next question.
- Viii seconds later outset displaying the question, the question is marked as incorrect even if the user enters the right answer after the eight-second limit.
Compare your lawmaking to the code using PyInputPlus in "Projection: Multiplication Quiz" on page 196.
Source: https://automatetheboringstuff.com/2e/chapter8/
0 Response to "If Input Not Correct Format Give Input Again Python"
Post a Comment