Subscribe to our Youtube Channel To Learn Free Python Course and More
Input and Output
In this section, we will learn about how to take input and give output in Python. Till now we were writing static programs, it means that we were not taking any input from the user.
But in the real world, A developer often interacts with the user, in order to get data or show the user some result. For example, you are making a program which takes a name as an input from the user and shows a greeting message with the user’s name on the screen. For this program, you need to know two things. First, how to take input from the user and second is how to show output.
Python provides lots of built-in functions. We will discuss Functions in detail later in the course. But for now, Functions are a reusable unit of code that is designed to perform single or related actions. You have already seen a print() function that is used to show output. Similarly, there is built-in function input() for taking input from the user.
How to Take Input from the User
How to Take Input from the User
We will use Python’s built-in function input() for taking input from the user. Let’s see how it works.
Input takes a string as an optional parameter. Usually it's a description of what input you want to take from the user. See the below example.
# get the name from a user
name = input('Enter your name : ')
Enter your name :
When you try to run this program the following thing will happen:
- When you execute input() function, the program will stop until the user provides the required input.
- Once user enters the name it will save it in the variable name. How To Show Output Now we have the user input that we can show on the input. To show input on the screen we use Python’s built-in function print() is used
- In print function, you can pass multiple objects in the print functions
# print() function
print(2, 'helo', 3, True)
# Output: 2 hello 3 True
a = 2,
print('a =', a)
# Output
# a = 2
Using sep and end parameter in print function.
sep
The sep parameter is used to separate objects. Default value is a space character(‘ ‘).
# sep
print(2, 'Hello', 3, True, sep=', ')
# Output: 2, Hello, 3, True
end
The end parameter is printed at the last.
# end
a = 'Hello world'
print('a =', a, end='!')
# Output: a = Hello world!
print('code =', 3, sep='0', end='0')
# output: code =030
Top comments (0)