Python Print and Input

In this tutorial, you will learn about the print() function to display output to the screen and the input() function to take input from the user.

Python print()

The print() function prints specified values and variables to the screen.

# print a string
print('Harry Potter')

# print a number
print(50)

number = 400

# print a variable
print(number)

goals = '100'
# strings and variables in the same line
print('Ronaldo has reached ', goals, ' goals')

Output:

Harry Potter
50
400
Ronaldo has reached 100 goals

Here,

  • The first print statement prints a string, the second prints an integer, and the third one prints a variable.
  • The final print statement takes a string variable and prints it along with the rest of the string in the statement.

You must have noticed that the print statement automatically prints the output on the next line.


input() Function

We can use the input() function to take input from the user.

# take user input
name = input()
print(name)

Printing Message Before Input

We can also print a message inside the input() function to let users know what they need to enter.

# displaying prompt message before taking input
name = input("Enter name: ")
print(name)

Output

Enter name: Felix
Felix

Numeric Input

In Python, the input() function always takes input as a string. We can check this by using the type() function.

# print the type of input.
number = input("Enter a number: ")
print(type(number))

Output

<class 'str'>

Here, <class 'str'> means it's a string.

As we can't directly take numeric inputs using the input() function, we need to convert the string to integers or float.

# take input 
number = input("Enter a number: ")
# convert numeric string to integer
number = int(number)

Here, we converted a number in string format to an integer.

We can also simplify the code above as

# take input and convert it to int
number = int(input("Enter a number: "))

Similarly, we can use the float() function to convert a numeric string to a floating-point number.

# take input and convert it to float
number = float(input("Enter a number: "))
print(type(number))

If we enter a non-numeric string and try to convert it into a number, we get an error.

# take input and convert it to float
number = float(input("Enter a number: "))
print(type(number))

Output

Enter a number: Harry
Traceback (most recent call last):
  File "", line 1, in 
ValueError: could not convert string to float: 'Harry'
Did you find this article helpful?