How to take input in python

Developers usually need to interact with users to obtain data or provide some result. Most programs today use dialog boxes to ask users to provide some type of input. Python provides us with two built-in functions to read keyboard input.

  • input ( prompt )
  • raw_input ( prompt )

input ( ): This function first accepts user input and then evaluates the expression, which means that Python will automatically recognize whether the user input is a string or a number or a list. If the input provided is incorrect, python will raise a syntax error or exception. E.g -

# Python program showing
# a use of input()

val = input("Enter your value: ")
print(val)

How the input function works in Python :

 

  • When input() function executes program flow will be stopped until the user has given an input.
  • The text or message display on the output screen to ask a user to enter input value is optional i.e. the prompt, will be printed on the screen is optional.
  • Whatever you enter as input, input function convert it into a string. if you enter an integer value still input() function convert it into a string. You need to explicitly convert it into an integer in your code using typecasting.

Code:

# Program to check input
# type in Python

num = input ("Enter number :")
print(num)
name1 = input("Enter name : ")
print(name1)

# Printing type of input value
print ("type of number", type(num))
print ("type of name", type(name1))

raw_input ( ) : This function is suitable for older versions (such as Python 2.x). This function completely accepts the content entered from the keyboard, converts it into a string, and then returns it to the variable we want to store. E.g -

# Python program showing
# a use of raw_input()

g = raw_input("Enter your name : ")
print g

Here, g is a variable which will get the string value, typed by user during the execution of program. Typing of data for the raw_input() function is terminated by enter key. We can use raw_input() to enter numeric data also. In that case we use typecasting.

Submit Your Programming Assignment Details