Saturday, September 4, 2021

John Ludhi/nbshare.io: How To Take User Input From The Command Line

How To Take User Input From The Command Line

Python provides developers with built-in functions that can be used to get input directly from users and interact with them using the command line (or shell as it is often called). Python 2 programmers use the function raw_input() to accomplish this task. Python 3 introduced the new input() function. The two functions have the same semantics.

Consider the following Python 3 code:

name = input('Enter your name: ')

This will display the sentence ‘Enter your name:’ as a prompt in the shell. Python will then wait until the user types something on the command line, followed by hitting the enter key. Whatever the user types will be the return value of the input() function. It is important to note that this value will always be treated as a string by Python. In our current example, the string will be assigned to the variable ‘name’. To produce the same result in Python 2 we can just replace the input() function with raw_input().

Enter your name: |

The user’s input will be entered on the same line, after the ‘Enter your name: ’ prompt. If we wanted the user to type in the next line we could add this to the input()

name = input('Enter your name:\n')

Now, the cursor has been moved to a new line and the program waits for the user to enter something there

Enter your name: 
|

Since all values entered by the user are returned as strings to the program, we have to be careful about how we store them. For example, consider an application where the program asks information from the user so that it can create a purchase order:

item = input("Please enter the Item you would like to purchase: ")
quantity= input("Please enter a Quantity for the item: ")

Output:

Please enter the Item you would like to purchase: |

The program waits until the user types an answer to the first prompt. If the user enters, for example, the word ‘Apples’, the program will store this value in the ‘item’ variable and will continue to the next prompt:

item = input("Please enter the Item you would like to purchase:  ")
quantity = input("Please enter a Quantity for the item: ")

Ouput:

Please enter the Item you would like to purchase: Apples
Please enter a Quantity for the item: |

If the user enters a quantity and hits the enter key, this value will be stored as a string in the variable ‘quantity’ and the program will continue. Since we probably will need to multiply the quantity with the price of the item in order to present the final cost to the user, we need to convert the string that is returned from the input() function into a float or an integer. We can do this by using the built-in float() or int() functions.

item = input("Please enter the Item you would like to purchase:  ")
quantity = float( input("Please enter a Quantity for the item: ") )

Output:

Please enter the Item you would like to purchase: Apples
Please enter a Quantity for the item: 3.0

Now the value of the variable ‘quantity’ is a float.

Since we didn’t use any type conversion for the variable ‘item’ its value remains a string. At this point, we can consider using the strip() function to get rid of any unwanted spaces that the user might accidentally add in the beginning or end of the item’s name.

item = input("Please enter the Item you would like to purchase:  ").strip()
quantity = float( input("Please enter a Quantity for the item: ") )

Output:

Please enter the Item you would like to purchase: Apples
Please enter a Quantity for the item: 3.0

We can use the information the user gave us to display in the shell the final cost of the purchase. If each apple costs $1, then we can multiply the value of the ‘quantity’ variable with this cost and get a float number.

item = input("Please enter the Item you would like to purchase:  ")
quantity = float( input("Please enter a Quantity for the item: ") )
price = 1;

Output:

Please enter the Item you would like to purchase: Apples
Please enter a Quantity for the item: 3.0
cost = price * quantity
print('The final cost is: %s' % cost)

The print() function replaces the %s placeholder with the float value stored in the ‘cost’ variable. The output the user will see at the end of the program will be:

The final cost is: 3.0

How to take user Input in Python 2

The above code is written in Python 3. To produce the same result in Python 2, we can replace the input() function with raw_input(), and the print() function with the print statement.

Although the above flow seems very simple, there are many ways that things can go wrong. This is because users may intentionally or accidentally type values that can cause the program to fail. Here is an example:

item = input("Please enter the Item you would like to purchase:  ")
quantity = float( input("Please enter a Quantity for the item: ") )
price = 1

Output:

Please enter the Item you would like to purchase: Apples
Please enter a Quantity for the item: +++
cost = price * quantity
print('The final cost is: %s' % cost)

The user has entered the sequence ‘+++’ instead of a number value as the quantity for the item. Now, when we try to use the float() function with this input, Python will produce a ValueError, since the sequence ‘+++’ can’t be converted to a float value. To protect the program against this kind of input errors, we must add some code for error handling using the format of try and except, as below.

item = input("Please enter the Item you would like to purchase:  ")
try:
quantity = float( input("Please enter a Quantity for the item: ") )
except ValueError:
print('Please enter a number for the quantity')

Now, if the user enters a value that can’t be converted to a float, the program will ‘catch’ the error and print a relevant message for the user.

However, we are not done yet. After the program catches the error, we need to go back again to the state where we ask the user to enter a quantity, because we need this input to present the final cost. This flow must be repeated no matter how many times the user types something that can cause the program to fail.

To achieve this we can add a loop:

while True:
try:
quantity = float( input("Please enter a Quantity for the item: ") )
break
except ValueError:
print("Please enter a number for the quantity")

When the program receives a valid value we ‘break’ the loop. While the value is invalid however, we print() the error message and continue to ask for the input().

The final flow will look like this:

item = input("Please enter the Item you would like to purchase:  ")
while True:
try:
quantity = float( input("Please enter a Quantity for the item: ") )
break;
except ValueError:
print("Please enter a number for the quantity")
price = 1


Please enter the Item you would like to purchase: Apples
Please enter a Quantity for the item: +++
cost = price * quantity
print('The final cost is: %s' % cost)

Again, we can replace the input() function with raw_input(), and the print() function with the print statement to achieve the same flow in Python 2.



    from Planet Python
    via read more

    No comments:

    Post a Comment

    TestDriven.io: Working with Static and Media Files in Django

    This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...