Search

What Is User Input in Python?

Developers need to communicate with users to collect data or to generate results. Many applications today use different ways to request a certain form of input from the user. Python offers us integrated features to take the input. The latest version of Python uses the input() method while the earlier version uses the raw_input() method. To do this, we have to click the Enter button after entering the value from the keyboard. The input() function then reads the user’s value. The input function reads a line from the console, then converts it to a string, and returns it. Syntax of input() Function:The syntax of input() function is: input(prompt) In the console, the prompt string is printed and the user is given the command to enter the value. You should print some useful information to help the user enter the expected value. Getting User Input in Python:The input() function receives the user input from the keyboard and stores it into a variable name. Here str is a variable and the print() function prints it to the screen. The input() function delays execution of a program to allow the user to type the input from the keyboard. On pressing Enter, all characters are reads and returns as a string.String input from user:Example:Here is an example of getting the user input and printing it on the console. str = input(“Enter your name: “)  print(str) Output: Enter your name: Joseph  Joseph Float Input from user:We will use float() function to convert the received input into a float value. Example:value = float(input("Enter a value: "))  print(value) Output: Enter a value: 200.99  200.99 How to get an Integer as the User Input?The input function converts whatever you enter as an input into a string. If you enter an integer value, the input() function will convert it to a string. To use the integers, we can use the built-in functions to convert it into an int. Example: value =input("Enter an integer:\n")  value =int(value)  print(f'The entered number is {value} and its square is {value ** 2}') Output: Enter an integer:  10  The entered number is 10 and its square is 100 Example: # take multiple inputs in array   input_str_array = input().split()   print("array:", input_str_array)   # take multiple inputs in array   input_int_array = [ int(x) for x in input().split()]   print("array:", input_int_array) Output: 10 20 30 40 50 60 70  array: ['10', '20', '30', '40', '50', '60', '70']  10 20 30 40 50 60 70  array: [10, 20, 30, 40, 50, 60, 70]Python user input and EOFError Example: EOFError in python is one of the exceptions to handle errors and is raised in scenarios such as the interruption of the input() function in both python version 2.7 and python version 3.6, as well as other versions after version 3.6 or when the input() function reaches the unexpected end of the file in python version 2.7, i.e. the functions do not read any data before the end of the input is encountered.  Methods such as read() must return a string that is empty at the end of the file, which is inherited in Python from the exception class that is inherited in BaseException class. This mistake often happens with online IDEs. If the input() function did not read any data then the python code will throw an exception i.e. EOFError. value =input("Please enter an integer:\n")  print(f'You entered {value}') Output: Enter a value: Traceback (most recent call last):  File “example.py”, line 1, in <module>  value = input(“Please enter an integer: “)  EOFError Working of EOFError in Python: The BaseException class inherits the EOFError class as the base class of the Exception class. EOFError technically is not an error, but an exception. When the built-in functions, such as the input() function or read() function returns a string that is empty without reading any data, the EOFError exception is raised. This exception is raised if our software tries to retrieve anything and make changes to it, but if no data is read and a string is returned, the EOFError exception is raised. Steps to Avoid EOFError in Python: If End of file Error or EOFError occurs, the exception EOFError is raised without reading any information by the input() function. We should try to enter something like CTRL + Z or CTRL + D before submitting the End of file exception to prevent the raising of this exception. Example: try:  data = raw_input ("Do you want to continue?: ")  except EOFError:  print ("Error: No input or End Of File is reached!")  data = ""  print data Output: The input provided by the user is being read which is: Hello this is demonstration of EOFError Exception in Python.  The input provided by the user is being read which is: EOF when reading a line. Explanation: In the above program, try to prevent the EOFError exception with an empty string, which doesn't print the error message of the End Of File and rather prints the personalised message that is shown in the program and prints the same on the output. You can use the try and catch block if the exception EOFError is processed. Python User Input Choice Example: Python provides a multiple-choice input system. You have to first get the keyboard input by calling the input() function. Then evaluate the choice by using the if-elif-else structure. value1 = input("Please enter first integer:\n")  value2 = input("Please enter second integer:\n")   v1 = int(value1)  v2 = int(value2)   choice = input("Enter 1 for addition.\nEnter 2 for subtraction.\nEnter 3 for Multiplication:\n")  choice = int(choice)   if choice == 1:  print(f'You entered {v1} and {v2} and their addition is {v1 + v2}')  elif choice == 2:  print(f'You entered {v1} and {v2} and their subtraction is {v1 - v2}')  elif choice == 3:  print(f'You entered {v1} and {v2} and their multiplication is {v1 * v2}')  else:  print("Wrong Choice, terminating the program.")  Output: Please enter first integer:  20  Please enter second integer:  10  Enter 1 for addition.  Enter 2 for subtraction.  Enter 3 for Multiplication:  2  You entered 20 and 10 and their subtraction is 10Python raw_input() function: Python raw_input function is a built-in function used to get the values from the user. This function is used only in the older versions of Python i.e. Python 2.x version.  Two functions are available in Python 2.x to take the user value. The first is the input function and the second is the raw_input() function.  The raw_input function in python 2.x is recommended for developers. This is because the input function is vulnerable in version 2.x of Python.Python 2.x environment setup: Python 2 must be installed in your system in order to use the raw input() function . Use python2 instead of python or Python3 if you run your program from a terminal. Therefore, the execution sample command is: $python2 example.py It depends on how your python have installed. In conclusion, you must run your program using the version python 2.x if you use raw_input function. You can modify your python compiler if you use PyCharm IDE. Go to File -> Configuration -> Project -> Project Interpreter for that purpose. Then select python 2.x from the list.Example 1: We will see a code written in Python 2.x version. name = raw_input(‘Enter your name : ‘)  print ‘Username : ‘, name Output: Enter your name : Steve  Username : Steve Example 2: # input() function in Python2.x   value1 = raw_input("Enter the name: ")   print(type(value1))   print(value1)   value2 = raw_input("Enter the number: ")   print(type(value2))   value2 = int(value2)   print(type(value2))   print(value2)Output: Enter the name: Jenny  <type ‘str’>  Jenny  Enter the number: ‘9876’  <type ‘str’>  <type ‘int’>  9876 The "Jenny" value is taken from the user in the value1 variable here and stored in the value1. String for raw input function is always the type of value stored. The value “9876” is taken from the user and stored in the variable value2. The variable value2 type is a string now and the type needs to be converted to an integer with int(). The value2 variable saves an integer type for the value "9876." The function raw input() was deactivated and removed from Python 3. You can update now if you're still on a Python 2.x. Conclusion: A basic framework for user input is provided by Python. The input function reads and converts a line from the console into a string. The input function converts all the information it receives to a string format. To convert the input to the correct format, we use a conversion type. It is used mainly to provide the user with an option of action and then adjust the program flow accordingly. The software, therefore, waits for the user’s input indefinitely. If the user did not enter the value in time, it would have been good to have a timeout and default value. EOFError technically is not an error, but an exception. When a string that is open without reading data is returned by inbuilt functions, such as input() or read(), then the exception with the EOFError is raised. 

What Is User Input in Python?

5K
  • by Abhresh S
  • 24th Mar, 2021
  • Last updated on 24th Mar, 2021
  • 7 mins read
What Is User Input in Python?

Developers need to communicate with users to collect data or to generate results. Many applications today use different ways to request a certain form of input from the user. Python offers us integrated features to take the input. The latest version of Python uses the input() method while the earlier version uses the raw_input() method. 

To do this, whave to click the Enter button after entering the value from the keyboard. The input() function then reads the user’s value. The input function reads a line from the console, then converts it to a string, and returns it. 

Syntax of input() Function:

The syntax of input() function is: 

input(prompt) 

In the console, the prompt string is printed and the user is given the command to enter the value. You should print some useful information to help the user enter the expected value. 

Getting User Input in Python:

The input() function receives the user input from the keyboard and stores it into a variable name. Herestris a variable and the print() function prints it to the screen. Getting User Input in Python

The input() function delays execution of a program to allow the user to type the input from the keyboard. On pressing Enter, all characters are reads and returns as a string.

String input from user:

Example:

Here is an example of getting the user input and printing it on the console. 

str = input(“Enter your name: “) 
print(str) 

Output: 

Enter your name: Joseph 
Joseph 

Float Input from user:

We will use float() function to convert the received input into a float value. 

Example:

value = float(input("Enter a value: ")) 
print(value) 

Output: 

Enter a value: 200.99 
200.99 

How to get an Integer as the User Input?

The input function converts whatever you enter as an input into a string. If you enter an integer value, the input() function will convert it to a string. 

To use the integers, we can use the built-in functions to convert it into an int. 

Example: 

value =input("Enter an integer:\n") 
value =int(value) 
print(f'The entered number is {value} and its square is {value ** 2}') 

Output: 

Enter an integer: 
10 
The entered number is 10 and its square is 100 

Example: 

# take multiple inputs in array  
input_str_array = input().split()  
print("array:", input_str_array)  
# take multiple inputs in array  
input_int_array = [ int(x) for x in input().split()]  
print("array:", input_int_array) 

Output: 

10 20 30 40 50 60 70 
array: ['10', '20', '30', '40', '50', '60', '70'] 
10 20 30 40 50 60 70 
array: [10, 20, 30, 40, 50, 60, 70]

Integer as the User Input example

Python user input and EOFError Example: 

EOFError in python is one of the exceptions to handlerrors and is raised in scenarios such as the interruption of the input() function in both python version 2.7 and python version 3.6, as well as other versions after version 3.6 or when the input() function reaches the unexpected end of the file in python version 2.7, i.e. the functions do not read any data before the end of the input is encountered.  

Methods such as read() must return a string that is empty at the end of the file, which is inherited in Python from the exception class that is inherited in BaseException class. This mistake often happens with online IDEs. 

If theinput()function did not read any data then the python code will throw an exception i.e. EOFError. 

value =input("Please enter an integer:\n") 
print(f'You entered {value}') 

Output: 

Enter a value: Traceback (most recent call last): 
File “example.py”, line 1, in <module> 
value = input(“Please enter an integer: “) 
EOFError 

Working of EOFError in Python: 

  1. The BaseException class inherits the EOFError class as the base class of the Exception class. 
  2. EOFError technically is not an error, but an exception. When the built-in functions, such as the input() function or read() function returns a string that is empty without reading any data, the EOFError exception is raised. 
  3. This exception is raised if our software tries to retrieve anything and make changes to it, but if no data is read and a string is returned, the EOFError exception is raised. 

Steps to Avoid EOFError in Python: 

If End of file Error or EOFError occurs, the exception EOFError is raised without reading any information by the input() function. We should try to enter something like CTRL + Z or CTRL + D before submitting the End of file exception to prevent the raising of this exception. 

Example: 

try: 
data = raw_input ("Do you want to continue?: ") 
except EOFError: 
print ("Error: No input or End Of File is reached!") 
data = "" 
print data 

Output: 

The input provided by the user is being read which is: Hello this is demonstration of EOFError Exception in Python. 
The input provided by the user is being read which is: EOF when reading a line. 

Explanation: In the above program, try to prevent the EOFError exception with an empty string, which doesn't print the error message of the End Of File and rather prints the personalised message that is shown in the programand prints the same on the output.

You can use the try and catch block if the exception EOFError is processed. 

Python User Input Choice Example: 

Python provides a multiple-choice input system. You have to first get the keyboard input by calling theinput()function. Then evaluate the choice by using the if-elif-else structure. 

value1 =input("Please enter first integer:\n") 
value2 =input("Please enter second integer:\n") 
v1 =int(value1) 
v2 =int(value2) 
choice =input("Enter 1 for addition.\nEnter 2 for subtraction.\nEnter 3 for Multiplication:\n") 
choice =int(choice) 
ifchoice ==1: 
print(f'You entered {v1} and {v2} and their addition is {v1 + v2}') 
elifchoice ==2: 
print(f'You entered {v1} and {v2} and their subtraction is {v1 - v2}') 
elifchoice ==3: 
print(f'You entered {v1} and {v2} and their multiplication is {v1 * v2}') 
else: 
print("Wrong Choice, terminating the program.") 

Output: 

Please enter first integer: 
20 
Please enter second integer: 
10 
Enter 1 for addition. 
Enter 2 for subtraction. 
Enter 3 for Multiplication: 
2 
You entered 20 and 10 and their subtraction is 10

 User Input Choice Example

Python raw_input() function: 

Python raw_input function is a built-in function used to get the values from the user. This function is used only in the older versions of Python i.e. Python 2.x version.  

  • Two functions are available in Python 2.x to take the user value. The first is the input function and the second is the raw_input() function.  
  • The raw_input function in python 2.x is recommended for developers. This is because the input function is vulnerable in version 2.x of Python.

Python 2.x environment setup: 

Python 2 must be installed in your system in order to use the raw input()function. Use python2 instead of python or Python3 if you run your programfrom a terminal. Therefore, the execution sample command is: 

$python2 example.py 

It depends on how your python haveinstalled. In conclusion, you must run your programusing the version python 2.x if you use raw_input function. 

You can modify your python compiler if you use PyCharm IDE. Go to File -> Configuration -> Project -> Project Interpreter for that purpose. Then selectpython 2.x from the list.

Example 1: 

We will see a code written in Python 2.x version. 

name = raw_input(‘Enter your name : ‘) 
print ‘Username : ‘, name 

Output: 

Enter your name : Steve 
Username : Steve 

Example 2: 

# input() function in Python2.x  
value1 = raw_input("Enter the name: ")  
print(type(value1))  
print(value1)  
value2 = raw_input("Enter the number: ")  
print(type(value2))  
value2 = int(value2)  
print(type(value2))  
print(value2)

Output: 

Enter the name: Jenny 
<type ‘str’> 
Jenny 
Enter the number: 9876 
<type ‘str’> 
<type ‘int’> 
9876 

The "Jenny" value is taken from the user in the value1variable here and stored in the value1. String for raw input function is always the type of value stored. The value 9876 is takenfrom the user and storedin the variable value2. The variable value2 type is a string now and the type needs to be converted to an integer with int(). The value2 variable saves an integer type for the value "9876." 

The function raw input() was deactivated and removed from Python 3. You can update now if you're still on a Python 2.x. 

Conclusion: 

  • A basic framework for user input is provided by Python. The input function reads and converts a line from the console into a string. 
  • The input function converts all the information it receives to a string format. To convert the input to the correct format, we use a conversion type. 
  • It is used mainly to provide the user with an option of action and then adjust the programflow accordingly. 
  • The software, therefore, waits for the user’s input indefinitely. If the user did not enter the value in time, it would have been good to have a timeout and default value. 
  • EOFError technically is not an error, but an exception. When a string that is open without reading data is returned by inbuilt functions, such as input() or read(), then the exception with the EOFError is raised. 
Abhresh

Abhresh S

Freelance Corporate Trainer

An Online Technical Trainer by profession! And Content writer by hobby! Interested in sharing quality knowledge to make the Industry grow better towards better success and better tomorrow! With a Guru Mantra of - "Keep Learning & Keep Practicing".

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

9 Stupendous Technologies You Might Be Using In Near Future

Our lives have made a 360 degree turn in the past decade. Technology is making us move at break neck speed and our lives are all about going somewhere and getting things done. The internet brought the world closer and it has been predicted that it will lead to the democratization of the world. While until a few years back we needed our PCs and laptops to get online, today we can do so with the touch of a button on our smartphones. Indeed, the smartphone has now become the most popular device in many parts of the world. Mobile technology is exactly what the name implies; technology that is mobile, portable and you can carry around in your pocket. A smartphone with an internet connection is all you need to get all your work done. Android and iOS are changing the way we live, eat, sleep, work and even travel. As consumerism grows so does the mobile technology, giving us better, richer and safer experiences than ever before. You will no longer be standing in a checkout line: The future of easy shopping is upon us. With the right app, you will soon be scanning your product and getting it delivered across to your address, which is already stored in the app and the payment would be deducted from your account which is already linked to this app. Of course, the app knows all about your shopping preferences and would suggest possible online stores if you do not get in at the store. Wearable technology: Google Glass and Apple Watch are not the only wearable technology out there. Medical wearable trends are fast changing the landscape of healthcare with such things as computer pills that when ingested send a patient’s medical information to a health centre wirelessly or artificial pancreas that monitor a patient’s glucose levels and also injects insulin at defined intervals. In fact, the future might be even more high-tech with a camera for a contact lens and a microphone under the skin. Your vehicle, a Wi-Fi hotspot: Your car might soon be an escape into a sci-fi movie. GPS enabled location trackers are already widely used but now your vehicle might have wi-fi and enhanced location guidance that may be displayed on the windshield. Data transfer between devices: You are working on your laptop, now on your phone and now on your tablet. There will soon be apps that will allow you to seamlessly move between devices without disrupting your work. No keys future: How many times have you locked yourself out of your house or your car? If carrying a hundred keys around is not exactly your cup of tea then you might as well make your smartphone your best friend since it might be all that you need to open your house, locker, car, safe or any other lock. No more charging: A charge less phone is a complete killjoy. But what if your phone charged by itself without a charger? This ‘”dream come true” situation might soon become a reality with a phenomenon called Piezoelectricity that converts mechanical movements into electric current. So your phone will charge as you are texting or talking. Now that is really a dream come true! Don’t like to type? Then just think: Technology that uses electroencephalography (EEG) might soon hit the market where in devices will be able to read your brain waves and allow interaction with phones or computers or other devices. Advent of the 5G: Once in every 5 years, cellular standards take a quantum leap and the 5G promises to be the most futuristic of them all in terms of power and functionality. This standard is expected to deliver higher speed internet services and greater levels of AI capabilities. No communication barriers: You will soon understand as many languages as you want due to the instant translation apps that will be available on your phone. Global communication barriers will be brought down as people can connect across geographies and text each other in multiple languages. The number of mobile users is expected to reach 5 billion by the year 2020 and this means better connectivity and infrastructure even in the remotest parts of the world. Technology is bringing the world closer and with such advances as interactive t-shirts, USB drives in ornaments and ear patches with voice recognition, the future of mobile technology will be you!
9 Stupendous Technologies You Might Be Using In Ne...

Our lives have made a 360 degree turn in the past ... Read More

Scala In Demand Technologies Built On Scala

The term Scala originated from “Scalable language” and it means that Scala grows with you. In recent times, Scala has attracted developers because it has enabled them to deliver things faster with fewer codes. Developers are now much more interested in having Scala training to excel in the big data field. The Scala community has grown over the years and it has now become a standard for enterprise, start-ups and universities alike. Scala is now being used by many companies and individuals to build their own new ideas. Play Framework, Akka, Apache Spark, etc are some of the tools and projects created using Scala. Scala is now the next wave of computation engines and more importance has been given to the speed processing rather than the size of the batch, and the ability to process event streaming in real-time. 1.Apache Spark Apache Spark can be considered as the replacement of MapReduce. In late 2013, Cloudera, the largest Hadoop vendor supported the idea of replacing MapReduce with Apache Spark. Spark is developed by AMPLab and it is a fast and general purpose engine for large-scale data processing. Spark effectively provides an alternative for Hadoop’s two stage MapReduce model. It has improved the performance of certain applications to 100 times with its fine grain operators, in-memory caching of intermediate data, and data flow optimization. 2. Scalding Scalding has been introduced and maintained by Twitter. It provides full benefits of Scala syntax and functional operations. Scala is a powerful language for solving functional problems. Scalding makes comprehensive use of Scala and it is an extension to cascading that enables application development with Scala. If we focus on the benefits of Scalding, data applications can be built with Scala. With simple and concise syntax code becomes easier to interpret. Scalding has filled the benefits of cascading application framework. 3. Apache Kafka Built and maintained by LinkedIn, Apache Kafka is a distributed streaming platform. Apache Kafka allows the user to publish and subscribe streams of data, just like a messaging system. Kafka is responsible for handling hundred of megabytes of read-write traffic per second from thousand of clients. It is also empowered by Scala and we can see the influence of the language. Real-time data pipelines and streaming apps can be built by using Apache Kafka. Yahoo Kafka Manager is also written in Scala and the web console is built using Play Framework. The Kafka Manager is being used by many teams including the Media Analytics team. It interacts with an actor-based, in-memory model built with Akka and Apache Curator. 4. Finagle Built by the people at twitter, Finagle can be considered as one of the best case using Scala. It is used to build high-concurrency servers and is an extensible RPC system for JVM. Finagle was intended to provide high performance, concurrency along with Scala and Java idiomatic APIs. Finagle is known for the optimal use of available system resources and high scalability through concurrency. It uses safe, simple and clean concurrent programming model which is based on Futures. All these results in safe and modular programs.
Scala In Demand Technologies Built On Scala

The term Scala originated from “Scalable languag... Read More

Web Development Using PHP And MySQL

PHP (or PHP Hypertext Preprocessor) is a server-side scripting language that is used to create dynamic web pages that can interact with databases. It is a widely-used open source language that is specifically used for web application development and can be embedded within HTML. Why PHP? The distinguishing feature of PHP is that the scripting code is executed on the server, which generates HTML that is sent back to the client. The client receives the result of executing the script without knowing the underlying code. Developers can configure the web server to process all the HTML files (containing the PHP script). PHP course is easy to learn for any newcomer, but also offers advanced programming features. Using PHP with a database system PHP, as a scripting language, is popular among web developers because of its ability to interact with database systems including Oracle and MySQL. This article discusses the use of PHP scripting language with the MySQL database. Any website can require a variety of data or information to display and to retrieve them from the database. This can include display of a simple list to the running of the website based on data stored in the database. Listed below are some examples where PHP and MySQL can be used together: • Digital Ad banners, where the PHP script can be used to retrieve a digital banner from the database, which then selects a random banner from its table records and sends it back to the calling script. The PHP script can also maintain a count of banner views and clicks from the website. • Internet forums or digital boards, which use PHP and MySQL to store and retrieve user messages. • Website designing, where the design of an entire website can be changed using a couple of PHP scripts, instead of changing and uploading each web page. The PHP script can access the MySQL database to retrieve all information about the web page. Setting up the MySQL database The procedure of setting up the MySQL database varies according to the host. Every database would require a user name and password, in order to access the database. Database administration can be done using PHP scripts or using a program like PHPMyAdmin. The next step is to create the database tables for storing the website information. Creating a database table using PHPMyAdmin is also simple. Alternatively, one can create and configure the entire database using the following PHP script: CREATE TABLE tablename { Fields } Where the Fields are coded as fieldname type(length) extra_info Example: first varchar(15) NOT NULL The following command is used in the PHP script to connect to the MySQL database: mysql_connect(localhost,$username,$password); where: • localhost is the server address on which the web site is running, • $username is the user name for the database access • $password is the password for the database access Executing PHP commands After configuring and connecting to the MySQL database, you can start executing PHP commands on the server. Following are the 2 methods of executing a PHP command: • Entering the command in PHP using the following syntax: Mysql_query($query) This form of command can be used to repeat the command simply by changing the variable. • Defining the command as a variable. The result of the operation will be assigned to the variable. Data input and output Inserting data using PHP is identical to the procedure of data input using HTML pages. The advantage of using PHP is that the script does not need to be changed for each new piece of input data. Users can also input their own data on the web page. Following is an example of an HTML page with textboxes that can be used to enter data in a form: Alternatively, you can use variables to input information into the database. Example: $first=$_POST[‘first’]; $last=$_POST[‘last’]; $phone=$_POST[‘phone’]; $mobile=$_POST[‘mobile’]; $fax=$_POST[‘fax’]; $email=$_POST[’email’]; $web=$_POST[‘web’]; … $query = “INSERT INTO contacts VALUES (”,’$first’,’$last’,’$phone’,’$mobile’,’$fax’,’$email’,’$web’)”; mysql_query($query); This script is saved in the insert.php file, which can be called from the HTML form. Using this method, data entered in the web page form is stored in the defined variables, which are then passed to the PHP. To display (or output) the entered data using PHP, you can use the following MySQL command with the result assigned to the variable. $query=”SELECT * FROM contacts”; $result=mysql_query($query); PHP provides 2 submission methods, GET and POST to get the data submitted by the form into your PHP script. GET method displays the variables and the data in the page address, while they are invisible in the POST method. For example, a script can be created that will display different web pages depending on the clicked link. yourpage.php?user=david (to show David’s page) yourpage.php?user=tom (to show Tom’s page)
3969
Web Development Using PHP And MySQL

PHP (or PHP Hypertext Preprocessor) is a server-si... Read More

20% Discount