Input from User in Python – input() function

If you have to take user input from keyboard in Python that can be done using input() function. Python input() function takes the entered value and returns it as a string once user presses Enter.

Syntax of input() function

The syntax of Python input() function is

input(msg)

Here msg is the optional string that is displayed on the console.

User input in Python example

val = input('Please enter your name: ')
print('Entered Value- ', val)

Output

Please enter your name: knpcode
Entered Value- knpcode

Input as number in Python

Note that input() function always returns entered value as string. If you want to get the value as integer or float you need to convert it explicitly.

val = input('Please enter a number: ')
# Convert to int
val = int(val)
# now use in arithmetic operation
print(val+5)

Output

Please enter a number: 8
13

You can use int() function along with the input() function to shorten the code-

val = int(input('Please enter a number: '))
# now use in arithmetic operation
print(val+5)

For float numbers you can use float() function

val = float(input('Please enter a number: '))
# now use in arithmetic operation
print(val+5)

Multiple values as input in Python

You can write separate input() functions to take more than one inputs from user. But Python provides a shorter version by using for loop along with input() function to take multiple inputs. Entered values are parsed as separate values by using split() method which considers space as delimiter by default. Therefore separate the separate inputs by space.

num1, num2, num3 = [int(x) for x in input('Please enter three integers: ').split()]
print('Sum of entered numbers-', (num1+num2+num3))

Output

Please enter three integers: 4 5 6
Sum of entered numbers- 15

Related Posts

  • Python I/O – Open, Read, Write Files
  • Python Program to Read a File
  • Python Program to Write a File
  • Python Program to Append to a File
  • That’s all for the topic Input from User in Python – input() function. If something is missing or you have something to share about the topic please write a comment.


    You may also like

  • Java Spliterator With Examples
  • Java Immutable Set With Examples
  • Type Casting And Type Conversion in Java
  • Merging PDFs in Java Using iText
  • Spring Component Scanning Example
  • Sequence File Format in Hadoop
  • Leave a Reply

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

    This site uses Akismet to reduce spam. Learn how your comment data is processed.