Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How To Ask Users For Input Until They Provide a Valid Input?

#1
How To Ask Users For Input Until They Provide a Valid Input?

<div><p class="has-pale-cyan-blue-background-color has-background"><em><span class="has-inline-color has-black-color">To accept valid inputs from the user either use a <strong>While Loop With Custom Validations</strong> or use the <strong>PyInputPlus</strong> module to avoid tedious validation definitions. Some other methods may also fascinate you which have been discussed below.</span></em></p>
<p><strong>Problem: </strong>Given a user input; accept the input only if it is valid otherwise ask the user to re-enter the input in the correct format.</p>
<p>Any user input must be validated before being processed, without proper validation of user input the code is most certainly going to have errors or bugs. The values that you want a user to enter and the values that they provide as an input can be completely different. For example, you want a user to enter their age as a positive valid numerical value, in this case, your code should not accept any invalid input like a negative number or words.&nbsp;</p>
<p>#<em>note:&nbsp;</em> <em>In Python 2.7, raw_input() is used to get a user input whereas in python 3 and above input() is used to get user input. input() always converts the user input into a string, so you need to typecast it into another data type if you want to use the input in another format.</em></p>
<p><strong>Example:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">age = int(input("What is your age: "))
if age >= 18: print("You are an Adult!")
else: print("You are not an Adult!")</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">What is your age: 25
You are an Adult!</pre>
<p>However, the code does not work when the user enters invalid input. (This is what we want to avoid. Instead of an error, we want the user to re-enter a valid input.)</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">What is your age: twenty five
Traceback (most recent call last): File "C:/Users/Shubham-PC/PycharmProjects/pythonProject/main.py", line 1, in &lt;module> age = int(input("What is your age: "))
ValueError: invalid literal for int() with base 10: 'twenty five'</pre>
<p>Now that we have an overview of our problem, let us dive straight into the solutions.</p>
<p><strong>Let’s get a quick overview of the first two solutions discussed in this article:</strong></p>
<h2>Method 1: Implement Input Validation Using While Loop And Exception Handling</h2>
<p>The easiest solution is to accept user input in a <a href="https://blog.finxter.com/python-one-line-while-loop-a-simple-tutorial/" target="_blank" rel="noreferrer noopener" title="Python One Line While Loop [A Simple Tutorial]">while loop</a> within a <a href="https://blog.finxter.com/python-one-line-exception-handling/" target="_blank" rel="noreferrer noopener" title="Python One Line Exception Handling">try </a>statement and use continue when the user enters invalid input and <code>break</code> statement to come out of the loop once the user enters a valid or correct input value. </p>
<p>Let us have a look at the following code to understand this concept:</p>
<p> <iframe height="1000px" width="100%" src="https://repl.it/@finxter/userinput?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe> </p>
<p><em><strong>Exercise</strong>: Run the code and try to break it by using wrong inputs. What happens?</em></p>
<p>Here’s the code to copy&amp;paste:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">while True: try: age = int(input("What is your age: ")) except ValueError: print("Please Enter a valid age.") continue else: if age > 0: break else: print("Age should be greater than 0!")
if age >= 18: print("You are an adult!")
else: print("You are not an adult!")
</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">What is your age: twenty five
Please Enter a valid age.
What is your age: -25
Age should be greater than 0!
What is your age: 25
You are an adult!</pre>
<h2>Method 2: Using Python’s PyInputPlus module</h2>
<p>Another way of managing user inputs is by using the PyInputPlus module which contains functions for accepting specific data inputs from the user like numbers, dates, email addresses, etc. You can read more about this module in the official documentation <a href="https://pypi.org/project/PyInputPlus/">here</a>.</p>
<p>Using the PyInputPlus module function we can ensure that the user input is valid because if a user enters invalid input, PyInputPlus will prompt the user to re-enter a valid input. Let us have a look at the code given below to get a better grip on the usage of PyInputPlus for validating user input.&nbsp;&nbsp;</p>
<p><em>Disclaimer: PyInputPlus is not a part of Python’s standard library. Thus you have to install it separately using Pip.</em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pyinputplus as pyip # User is prompted to enter the age and the min argument ensures minimum age is 1
age = pyip.inputInt(prompt="Please enter your age: ", min=1)
if age >= 18: print("You are an Adult!")
else: print("You are not an Adult!")</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Please enter your age: -1
Number must be at minimum 1.
Please enter your age: twenty five 'twenty five' is not an integer.
Please enter your age: 25
You are an Adult!</pre>
<h2>Method 3: Implementing Recursion</h2>
<p>Another way of prompting the user to enter a valid input every time the user enters an invalid value is to make use of <a href="https://blog.finxter.com/recursion/"><strong>recursion</strong>.</a> Recursion allows you to avoid the use of a <a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops">loop</a>. However, this method works fine most of the time unless the user enters the invalid data too many times. In that case, the code will terminate with a <code>RuntimeError: maximum recursion depth exceeded</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def valid_input(): try: age = int(input("Enter your Age: ")) except ValueError: print("Please Enter a valid age. The Age must be a numerical value!") return valid_input() if age &lt;= 0: print("Your Age must be a positive numerical value!") return valid_input() else: return age x = valid_input()
if x >= 18: print("You are an Adult!")
else: print("You are not an Adult!")
</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Enter your Age: -1
Your Age must be a positive numerical value!
Enter your Age: twenty five
Please Enter a valid age. The Age must be a numerical value!
Enter your Age: 25
You are an Adult!</pre>
<h2>Method 4: A Quick Hack Using Lambda Function</h2>
<p>Though this method might not be the best in terms of code complexities, however, it might come in handy in situations where you want to use a function once and then throw it away after the purpose is served. Also, this method displays how long pieces of codes can be minimized, hence this method makes a worthy entry into the list of our proposed solutions.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">valid = lambda age: (age.isdigit() and int(age) > 0 and ( (int(age) >= 18 and "You are an Adult!") or "You are not an Adult")) or \ valid(input( "Invalid input.Please make sure your Age is a valid numerical vaule!\nPlease enter your age: "))
print(valid(input("Please enter your age: ")))</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Please enter your age: -1
Invalid input. Please make sure your Age is a valid numerical vaule!
Please enter your age: 0
Invalid input. Please make sure your Age is a valid numerical vaule!
Please enter your age: twenty five
Invalid input. Please make sure your Age is a valid numerical vaule!
Please enter your age: 25
You are an Adult!
</pre>
<h2>Conclusion</h2>
<p>Thus proper validation of user input is of utmost importance for a bug-free code and the methods suggested above might prove to be instrumental in achieving our cause. I prefer the use of PyInputPlus module since defining custom validations might get tedious in case of complex requirements. Also, the use of recursive methods must be avoided unless you are sure about your requirements since they require more memory space and often throw Stack Overflow Exceptions when operations are too large.&nbsp;</p>
<p>I hope you found this article helpful and it helps you to accept valid user inputs with ease. Stay tuned for more interesting stuff in the future!</p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>


https://www.sickgaming.net/blog/2020/08/...lid-input/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016