Python User Inputted Invalid Command How to Ask for Input Again
Python Beginner
A Consummate Guide to User Input in Python
Learning about the Python input function in detail along with its many apply-cases
User input is disquisitional for edifice interactive programs. Every programming language has its unique implementation of an input interface. C++ has scanf
, Java has the Scanner
class, and Ruby has gets
.
While in most cases, this input stems from the keyboard, other forms like mouse clicks, track-pad, sensors, etc. are besides possible.
As ever, Python provides a unproblematic framework for getting user input in the form of the input()
function.
The input function reads a line from the console, converts it into a string, and returns information technology.
In this tutorial, we volition comprehend the input()
part in detail using a variety of employ-cases. We volition discuss the several forms in which input can exist and how to parse this input into our required format with the help of lawmaking snippets.
Syntax
input([prompt])
Here,
prompt: an optional cord argument, used to display a message for the user. Example: 'Enter Name:'
When the input()
part is called, the program catamenia halts until the user enters some input. The user then adds some information and presses the Enter
key. The input function returns to the programme with the entered cord.
entered_value = input('Enter some value: ')
impress(entered_value)
Output:
Input Type
The input role converts all data that it receives into the string format. Let us take a wait:
Output:
Enter name: Chaitanya Baweja
Enter age: 20
data_type of name: <class 'str'>
data_type of age: <class 'str'>
We used the blazon function to cheque the object's data type. Equally you lot tin can see higher up, it does non thing whether we enter a number or a grapheme string. Both of them return every bit string objects.
Accept an integer input from the user
As input()
role returns everything as a cord, we need to perform some explicit type-conversion for accepting integers. Hither, we will use the int()
part.
Output:
Enter first num: x
Enter second num: 5
Type of num_1: <class 'int'>
Blazon of num_2: <class 'int'>
The sum of given numbers is : 15
int(string)
converts the given string to an integer type.
Accept a float input from the user
Similarly, nosotros tin can get a float value using the float()
office.
Output:
Enter value: five.6
Type of float_1: <course 'bladder'>
Twice the given numbers is : 11.2
User Input Exception Handling
A common event with type-conversion is the ValueError exception.
When the user enters input that cannot be converted into the given type, we get a ValueError exception.
For instance, the user enters a random cord for age.
num = int(input('Enter age: '))
Here, the int()
part expects an integer value wrapped inside a string. Any other blazon of value volition consequence in an error. Look what happens when nosotros enter 'nope'
as input.
Output:
Enter historic period: nope ---------------------------------------------------------
ValueError Traceback (most recent call terminal)
<ipython-input-10-1fa1cb611d10> in <module>
----> 1 num_1 = int(input('Enter age: '))ValueError: invalid literal for int() with base 10: 'nope'
To ensure that the user enters valid data, nosotros need to handle many such errors that ordinarily occur with user input. We will use Python Exception Handling for this purpose. Take a wait:
Again if nosotros enter 'nope'
as input:
Enter a number: nope
This is not a number.
In the above snippet, if the user enters a non-integer input, the lawmaking will raise an exception. This exception is defenseless by the except statement where we impress: 'This is not a number'
.
Because of this endeavour-except block, our program will not crash on wrong user input.
We tin can use the exception cake along with a loop. Thus, the user will be prompted once again and over again until they provide valid input.
Multiple input values in a unmarried line
We tin also inquire for multiple values direct on a single line with but one call to the input()
function. For example, permit's get some data about a student from the user and store it in different variables.
Output:
Enter pupil's proper noun, age and score separated by space:Chaitanya 20 100
Pupil Name: Chaitanya
Pupil Age: xx
Pupil Score: 100
Here, we separated the input string by spaces using the carve up()
method.
Get a list of numbers as input
Simply what happens when you are non aware of the number of input values?
Let usa suppose that yous need to enter a listing of numbers and render their sum. You are not aware of the number of elements in that list.How practise we input this list?
Nosotros use both the split and the map role. The separate()
method volition divide the entered string into a list of strings. Then, the map()
office will perform the int
operation on all the list elements.
Output:
Enter a list of numbers separated by infinite: 10 xx xxx 40 50 60
Intermediate_list: ['10', '20', 'thirty', '40', 'l', '60']
Number List: [10, 20, 30, forty, 50, 60]
List sum: 210
In the code to a higher place:
-
input()
returns a string containing numbers separated past spaces. -
split()
returns a list of strings partitioned on the spaces. -
map()
performsint()
operation on all the list elements and returns a map object. -
list()
office converts the map object back into a listing.
Multi-Line input from a user
The input()
function returns whenever it encounters a newline graphic symbol (when the user presses Enter
key). Thus, if you attempt to send multi-line information, input()
will only render the kickoff line.
To overcome this, we tin can use for-loop. We get one line of input per iteration and stop when we receive an empty line ('Press Enter on an empty line'). We combine all these lines in a list.
Output:
Decision
Python provides a simple framework for getting user input. The input function reads a line from the panel, converts it into a string, and returns information technology.
The input function converts all information that it receives into the string format. We utilize type-conversion to catechumen the input into the required format.
Exceptions occurring due to invalid input can exist managed using the effort-except block. The split and map functions help input multiple values in the same line.
Chaitanya Baweja aspires to solve real earth issues with engineering solutions. Follow his journey on Twitter and Linkedin.
Source: https://towardsdatascience.com/a-complete-guide-to-user-input-in-python-727561fc16e1
0 Response to "Python User Inputted Invalid Command How to Ask for Input Again"
Post a Comment