Python User Input

Python User Input, Read Input, input() function, print() function, validate user input in Python, input type check, and read specific input.

Python User Input

Like all high-level languages, Python is easy to read, takes less time to write, and is portable. Python language has two versions: Python 2 and Python 3. Python 2.x is legacy, Python 3.x is the present and future of the language.

Python 2 is no longer in development and all new features will be added in Python 3.

Reading input from the keyboard:

In Python 2 the following two functions are available to read dynamic input from the keyboard.

1. raw_input()
2. input()

1. raw_input():

This function always reads the data from the keyboard in the form of String Format. We have to convert that string type to our required type by using the corresponding typecasting methods.

Example:

x=raw_input(“Enter A Number: “)
print(type(x)) It will always print str type only for any input type

2. input():

input() function can be used to read data directly in our required format.We are not required to perform type casting.

x=input(“Enter A Value”)
type(x)
10 ===> int
“gcreddy”===>str
10.5===>float
True==>bool

Note: But in Python 3 we have only input() function and raw_input() function is not available. Python3 input() function behaviour exactly same as raw_input() function of Python2. raw_input() function of Python 2 is renamed as input() function in Python3

Input using the input( ) function (Python 3)

val=input(“Enter a Value: “)

It stops execution of the program and waits for uer input, suppose I am entering – India

print (val)

It will display/print, India

print (type(val))

It will print type of val, <class ‘str’>

val=input(1234)
print (val) #1234
print (type(val)) #<class ‘str’>

val=input(10.244)
print (val) #10.244
print (type(val)) #<class ‘str’>

val=input(True)
print (val) #True
print (type(val)) #<class ‘str’>

Read Integer Type Data:

x=int(input(“Enter a Value: “))

print(x)

print(type(x)) #int

Read Float Type Data

x=float(input(“Enter a Value: “))

print(x)

print(type(x)) #int

Python Output Using print() function:

We use the print() function to output data to the standard output device (screen).

Example1:

print(“This is G C Reddy’s Python Tutorial”)

Output is: This is G C Reddy’s Python Tutorial

Example2:

x = 100
print(“The value of x is: “, x)

Output is: The value of a is: 100


Python Tutorial

Python Full Course Video

Follow me on social media: