• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / How to Take User Input in Python

How to Take User Input in Python

Author: Aditya Raj
Last Updated: December 20, 2021

While programming , we often need to take user input in our programs. In this article, we will look at different ways to take user input in python. We will discuss ways to take different python literals such as string, integer and decimal values as input in our program.

How to take input in Python

We can use the input() method to take user input in python. 

The input() method, when executed, takes an option string argument which is shown as a prompt to the user. After taking input, the input() method returns the value entered by the user as a string. Even if the user enters a number or a punctuation mark, the input() method will always read the input as a string. You can observe this in the following example.

value = input("Please input a number:")
print("The data type of {} is {}".format(value, type(value)))

Output:

Please input a number:1243
The data type of 1243 is <class 'str'>

While execution of the input() method, the execution of the program is paused until the user presses the enter key after giving an input. Once the user presses the enter key, the input() method completes its execution.

How to take an integer input in Python

We have just seen that the input() method reads every value as a string. If we want to verify that the user has entered an integer, we can do it using the regular expressions.

We will use the re.match() method to verify if the given input is an integer or not. For this, we will pass the  regular expression for integer i.e “[-+]?\d+$” and the input string to re.match() method as input. If the input string contains characters other than decimal digits with – or + sign at the start, the re.match() method will return None. Otherwise, the match() method returns a match object. To check if the user input consists of only an integer, we can use the re.match() method as follows.

import re

flag = True
input_value = None
while flag:
    input_value = input("Please input a number:")
    match_val = re.match("[-+]?\\d+$", input_value)
    if match_val is None:
        print("Please enter a valid integer.")
    else:
        flag = False
number = int(input_value)
print("The input number is:", number)

Output:

Please input a number:Aditya
Please enter a valid integer.
Please input a number:PFB
Please enter a valid integer.
Please input a number:123.4
Please enter a valid integer.
Please input a number:+1234
The input number is: 1234

Here, we have used a while loop to prompt the user repeatedly for giving an integer input. We have checked the input value using the re.match() method. If the input is not correct, the while loop is executed again. Otherwise, the while loop is terminated as flag becomes False. Similarly, we can ask the user for a decimal number input using the re.match() method as discussed below.

How to take a decimal number as input in Python

Again, we will use the re.match() method to verify if the user has given a valid decimal number as input or not. For this, we will pass the  regular expression for decimal numbers i.e “[-+]?\\d+([/.]\\d+)?$” and the input string to the re.match() method as input. If the input string contains characters other than decimal digits with –  and + at start and an optional decimal point “.” between the digits, the re.match() method will return None. Otherwise, the match() method returns a match object. To check if the user input consists of only a decimal number, we can use the re.match() method as follows.

import re

flag = True
input_value = None
while flag:
    input_value = input("Please input a number:")
    match_val = re.match("[-+]?\\d+([/.]\\d+)?$", input_value)
    if match_val is None:
        print("Please enter a valid decimal number.")
    else:
        flag = False
number = float(input_value)
print("The input number is:", number)

Output:

Please input a number:Aditya
Please enter a valid decimal number.
Please input a number:PFB
Please enter a valid decimal number.
Please input a number:-123.456
The input number is: -123.456

Conclusion

In this article, we have seen various ways to take user input in python using the input() method. We also discussed validating the inputs using the re.match() method. To study more about validating strings in python, you can read this article on regular expressions in python. 

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us