Python Input Output


Python is a versatile programming language with many built-in functions and modules to handle various input and output operations.4

Input and output, commonly abbreviated as I/O, are essential components of any programming language, and Python offers a variety of ways to interact with files, console, and other data sources.

In this Chapter, we will explore different techniques to perform input and output operations in Python.

 

Console Input and Output


One of the most basic ways to interact with Python programs is through the console, also known as the command-line interface.

Python provides several built-in functions to interact with the console, including print(), input(), format(), and sys.stdout.write().

 

1. print()


The print() function is used to output data to the console.

It takes one or more arguments and prints them to the console, separated by spaces.

The print() function automatically adds a newline character at the end of the output.

Example:

name = "John"
age = 25
print("My name is", name, "and I am", age, "years old.")


Output:

My name is John and I am 25 years old.


In the above example, we use the print() function to output a message to the console. We use string concatenation to combine variables and strings.

The print() function automatically separates the arguments with a space and adds a newline character at the end.

 

2. input()


The input() function is used to accept user input from the console. It prompts the user to enter a value and returns a string containing the user's input.

Example:

name = input("Enter your name: ")
print("Hello", name)


Output:

Enter your name: John
Hello John


In the above example, we use the input() function to prompt the user to enter their name. The user enters their name, which is stored in the name variable. We use the print() function to output a message to the console, which includes the user's name.

 


 

© 2022-2023 All rights reserved.