How to Read User Input in Python

Python Beginner

A Consummate Guide to User Input in Python

Learning about the Python input function in detail along with its many use-cases

Chaitanya Baweja

Photo by Kaitlyn Baker on Unsplash

User input is critical for edifice interactive programs. Every programming linguistic communication has its unique implementation of an input interface. C++ has scanf, Java has the Scanner course, and Scarlet has gets.

While in most cases, this input stems from the keyboard, other forms like mouse clicks, track-pad, sensors, etc. are also possible.

As always, Python provides a simple framework for getting user input in the form of the input() part.

The input function reads a line from the console, converts it into a string, and returns it.

In this tutorial, we will cove r the input() function in detail using a variety of utilise-cases. We volition discuss the several forms in which input tin can exist and how to parse this input into our required format with the help of lawmaking snippets.

Source: Giphy

Syntax

input([prompt])

Hither,
prompt: an optional string argument, used to display a message for the user. Instance: 'Enter Name:'

When the input() function is called, the program flow halts until the user enters some input. The user then adds some information and presses the Enter central. The input role returns to the program with the entered string.

              entered_value = input('Enter some value: ')
print(entered_value)

Output:

Source: Writer

Input Type

The input function converts all information that information technology receives into the cord format. Let us take a look:

Output:

              Enter proper name: Chaitanya Baweja
Enter age: xx
data_type of name: <class 'str'>
data_type of age: <class 'str'>

Nosotros used the type function to check the object's data type. Every bit you can come across above, it does not affair whether we enter a number or a character cord. Both of them return equally string objects.

Have an integer input from the user

As input() function returns everything every bit a string, we need to perform some explicit type-conversion for accepting integers. Here, we will use the int() function.

Output:

              Enter offset num: 10
Enter second num: 5
Type of num_1: <class 'int'>
Type of num_2: <course 'int'>
The sum of given numbers is : fifteen

int(string) converts the given string to an integer type.

Accept a float input from the user

Similarly, we can become a float value using the bladder() office.

Output:

              Enter value: v.vi
Type of float_1: <class 'bladder'>
Twice the given numbers is : 11.2

User Input Exception Handling

A common issue with blazon-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 string for historic period.

              num = int(input('Enter age: '))            

Hither, the int() function expects an integer value wrapped within a string. Any other type of value will result in an error. Look what happens when we enter 'nope' as input.

Output:

              Enter age: nope              ---------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-10-1fa1cb611d10> in <module>
----> 1 num_1 = int(input('Enter historic period: '))

ValueError: invalid literal for int() with base 10: 'nope'

To ensure that the user enters valid information, we need to handle many such errors that commonly occur with user input. Nosotros will use Python Exception Handling for this purpose. Have a look:

Again if we enter 'nope' as input:

              Enter a number: nope
This is non a number.

In the in a higher place snippet, if the user enters a non-integer input, the code will raise an exception. This exception is caught by the except statement where nosotros print: 'This is not a number'.

Considering of this endeavor-except block, our program will not crash on wrong user input.

Source: Giphy

We can use the exception block along with a loop. Thus, the user volition be prompted over again and again until they provide valid input.

Source: Author

Multiple input values in a single line

We tin can too ask for multiple values directly on a unmarried line with just one phone call to the input() part. For example, let'southward get some information nigh a student from the user and store it in unlike variables.

Output:

              Enter student'south name, age and score separated by space:Chaitanya twenty 100
Student Name: Chaitanya
Student Historic period: 20
Student Score: 100

Hither, nosotros separated the input string by spaces using the dissever() method.

Go a list of numbers as input

Just what happens when you lot are non aware of the number of input values?

Let us suppose that you demand to enter a listing of numbers and return their sum. You are not enlightened of the number of elements in that list.How practice we input this list?

We use both the split and the map function. The split() method will divide the entered string into a list of strings. Then, the map() function will perform the int operation on all the list elements.

Output:

              Enter a list of numbers separated by space: 10 20 30 40 50 60
Intermediate_list: ['10', '20', 'thirty', 'xl', '50', '60']
Number List: [ten, 20, 30, 40, 50, 60]
Listing sum: 210

In the lawmaking above:

  • input() returns a cord containing numbers separated by spaces.
  • separate() returns a list of strings partitioned on the spaces.
  • map() performs int() operation on all the listing elements and returns a map object.
  • list() part converts the map object back into a list.
Source: Giphy

Multi-Line input from a user

The input() office returns whenever information technology encounters a newline character (when the user presses Enter key). Thus, if you lot attempt to send multi-line information, input() volition merely return the start line.

To overcome this, we can use for-loop. Nosotros go 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:

Conclusion

Python provides a simple framework for getting user input. The input part reads a line from the console, converts it into a string, and returns it.

The input function converts all information that it receives into the string format. We apply blazon-conversion to convert the input into the required format.

Exceptions occurring due to invalid input tin be managed using the try-except cake. The split and map functions assistance input multiple values in the aforementioned line.

moodyhudinted.blogspot.com

Source: https://towardsdatascience.com/a-complete-guide-to-user-input-in-python-727561fc16e1

0 Response to "How to Read User Input in Python"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel