2

Python - Input and Output

 2 years ago
source link: https://dev.to/introschool/python-input-and-output-3amc
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Input and Output

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 : 
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit fullscreen mode

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK