Skip to content Skip to sidebar Skip to footer

C++ if Input<1 Ask for the Input Again

Python Beginner

A Complete Guide to User Input in Python

Learning about the Python input function in detail forth with its many utilize-cases

Photo by Kaitlyn Baker on Unsplash

User input is critical for building interactive programs. Every programming language has its unique implementation of an input interface. C++ has scanf, Java has the Scanner class, and Cherry-red has gets.

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

Every bit always, Python provides a elementary framework for getting user input in the form of the input() function.

The input part reads a line from the console, converts information technology into a cord, and returns it.

In this tutorial, nosotros will embrace the input() part in particular using a variety of use-cases. We will discuss the several forms in which input tin can be and how to parse this input into our required format with the help of code snippets.

Source: Giphy

Syntax

input([prompt])

Here,
prompt: an optional string argument, used to display a message for the user. Case: 'Enter Proper name:'

When the input() part is called, the program menstruum halts until the user enters some input. The user and so adds some information and presses the Enter key. The input function returns to the program with the entered string.

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

Output:

Source: Author

Input Type

The input function converts all data that information technology receives into the string format. Permit united states of america accept a look:

Output:

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

We used the type part to cheque the object's data blazon. Every bit you can see above, it does not matter whether we enter a number or a character string. Both of them return as 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() office.

Output:

            Enter first num: x
Enter second num: v
Type of num_1: <class 'int'>
Type of num_2: <grade 'int'>
The sum of given numbers is : 15

int(cord) converts the given string to an integer blazon.

Accept a float input from the user

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

Output:

            Enter value: 5.6
Blazon of float_1: <class 'float'>
Twice the given numbers is : xi.2

User Input Exception Handling

A common issue with type-conversion is the ValueError exception.

When the user enters input that cannot be converted into the given blazon, we get a ValueError exception.

For example, the user enters a random cord for historic period.

            num = int(input('Enter historic period: '))          

Here, the int() role expects an integer value wrapped inside a string. Any other type of value volition issue in an mistake. Look what happens when we enter 'nope' as input.

Output:

            Enter historic period: nope            ---------------------------------------------------------
ValueError Traceback (nearly contempo call last)
<ipython-input-x-1fa1cb611d10> in <module>
----> one 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 volition utilise Python Exception Handling for this purpose. Take a look:

Once again if nosotros enter 'nope' equally input:

            Enter a number: nope
This is non a number.

In the above snippet, if the user enters a not-integer input, the code will heighten an exception. This exception is caught by the except statement where we impress: 'This is not a number'.

Because 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 again and again until they provide valid input.

Source: Writer

Multiple input values in a single line

We can besides ask for multiple values directly on a unmarried line with just ane call to the input() role. For case, let's get some information about a pupil from the user and store it in different variables.

Output:

            Enter educatee'southward name, age and score separated by space:Chaitanya xx 100
Student Name: Chaitanya
Educatee Age: 20
Pupil Score: 100

Here, we separated the input string past spaces using the divide() method.

Get a list of numbers every bit input

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

Let usa suppose that you lot need to enter a list of numbers and return their sum. Y'all are not enlightened of the number of elements in that list.How do we input this listing?

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

Output:

            Enter a list of numbers separated by infinite: 10 20 30 40 50 lx
Intermediate_list: ['10', '20', 'xxx', '40', '50', '60']
Number List: [10, twenty, 30, 40, 50, lx]
List sum: 210

In the lawmaking above:

  • input() returns a string containing numbers separated by spaces.
  • split() returns a listing of strings partitioned on the spaces.
  • map() performs int() operation on all the list 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 it encounters a newline character (when the user presses Enter central). Thus, if you effort to send multi-line information, input() will but render the first line.

To overcome this, we tin apply for-loop. Nosotros 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:

Conclusion

Python provides a simple framework for getting user input. The input function reads a line from the console, converts it into a cord, and returns information technology.

The input function converts all information that it receives into the cord format. We use type-conversion to catechumen the input into the required format.

Exceptions occurring due to invalid input can exist managed using the try-except block. The dissever and map functions help input multiple values in the same line.

Chaitanya Baweja aspires to solve real world problems with engineering science solutions. Follow his journey on Twitter and Linkedin.

alliehadd1958.blogspot.com

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

Post a Comment for "C++ if Input<1 Ask for the Input Again"