Open In App

Input and Output in Python

Last Updated : 19 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Understanding input and output operations is fundamental to Python programming. With the print() function, you can display output in various formats, while the input() function enables interaction with users by gathering input during program execution.

Python Basic Input and Output

In this introductory guide, we’ll explore the essentials of Python’s basic input and output functionalities, empowering you to efficiently interact with users and display information.

Print Output in Python

At its core, printing output in Python is straightforward, thanks to the print() function. This function allows us to display text, variables, and expressions on the console. Let’s begin with the basic usage of the print() function:

How to Print Output in Python

In this example, “Hello, World!” is a string literal enclosed within double quotes. When executed, this statement will output the text to the console.

Python3
print("Hello, World!")

Output
Hello, World!



Print Single and Multiple variable in Python

The code assigns values to variables name and age, then prints them with labels.

Python3
name = "Alice"
age = 30
print("Name:", name, "Age:", age)

Output
Name: Alice Age: 30



Format Output Handling in Python

Output formatting in Python with various techniques including the format() method, manipulation of the sep and end parameters, f-strings, and the versatile % operator. These methods enable precise control over how data is displayed, enhancing the readability and effectiveness of your Python programs.

Example 1: Using Format()

Python3
amount = 150.75
print("Amount: ${:.2f}".format(amount))

Output
Amount: $150.75



Example 2: Using sep and end parameter

Python3
# end Parameter with '@'
print("Python", end='@')
print("GeeksforGeeks")


# Seprating with Comma
print('G', 'F', 'G', sep='')

# for formatting a date
print('09', '12', '2016', sep='-')

# another example
print('pratik', 'geeksforgeeks', sep='@')

Output
Python@GeeksforGeeks
GFG
09-12-2016
pratik@geeksforgeeks



Example 3: Using f-string

Python3
name = 'Tushar'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")

Output
Hello, My name is Tushar and I'm 23 years old.



Example 4: Using % Operator

We can use ‘%’ operator. % values are replaced with zero or more value of elements. The formatting using % is similar to that of ‘printf’ in the C programming language.

  • %d –integer
  • %f – float
  • %s – string
  • %x –hexadecimal
  • %o – octal
Python3
# Taking input from the user
num = int(input("Enter a value: "))

add = num + 5

# Output
print("The sum is %d" %add)

Output

Enter a value: 50The sum is 55

Take Multiple Input in Python

The code takes input from the user in a single line, splitting the values entered by the user into separate variables for each value using the split() method. Then, it prints the values with corresponding labels, either two or three, based on the number of inputs provided by the user.

Python3
# taking two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)
 
# taking three inputs at a time
x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)

Output

Enter two values: 5 10
Number of boys: 5
Number of girls: 10
Enter three values: 5 10 15
Total number of students: 5
Number of boys is : 10
Number of girls is : 15

Take Conditional Input from user in Python

In this example, the program prompts the user to enter their age. The input is converted to an integer using the int() function. Then, the program uses conditional statements to check the age range and prints a message based on whether the user is a minor, an adult, or a senior citizen.

Python3
# Prompting the user for input
age_input = input("Enter your age: ")

# Converting the input to an integer
age = int(age_input)

# Checking conditions based on user input
if age < 0:
    print("Please enter a valid age.")
elif age < 18:
    print("You are a minor.")
elif age >= 18 and age < 65:
    print("You are an adult.")
else:
    print("You are a senior citizen.")

Output

Enter your age: 22
You are an adult.

Taking input in Python

Python input() function is used to take user input. By default, it returns the user input in form of a string. 

Syntax: input(prompt)

How to Take Input in Python

The code prompts the user to input their name, stores it in the variable “name”, and then prints a greeting message addressing the user by their entered name.

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

Output

Enter your name: GeeksforGeeks
Hello, GeeksforGeeks ! Welcome!

How to Change the Type of Input in Python

By default input() function helps in taking user input as string. If any user wants to take input as int or float, we just need to typecast it.

How to Print Names in Python

The code prompts the user to input a string (the color of a rose), assigns it to the variable color, and then prints the inputted color.

Python3
# Taking input as string
color = input("What color is rose?: ")
print(color)

Output

What color is rose?: Red
Red

How to Print Numbers in Python

The code prompts the user to input an integer representing the number of roses, converts the input to an integer using typecasting, and then prints the integer value.

Python3
# Taking input as int
# Typecasting to int
n = int(input("How many roses?: "))
print(n)

Output

How many roses?: 8
8

How to Print Float/Decimal Number in Python

The code prompts the user to input the price of each rose as a floating-point number, converts the input to a float using typecasting, and then prints the price.

Python3
# Taking input as float
# Typecasting to float
price = float(input("Price of each rose?: "))
print(price)

Output

Price of each rose?: 50.30
50.3

Find DataType of Input in Python

In the given example, we are printing the type of variable x. We will determine the type of an object in Python.

Python3
a = "Hello World"
b = 10
c = 11.22
d = ("Geeks", "for", "Geeks")
e = ["Geeks", "for", "Geeks"]
f = {"Geeks": 1, "for":2, "Geeks":3}


print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))

Output

<class 'str'>
<class 'int'>
<class 'float'>
<class 'tuple'>
<class 'list'>
<class 'dict'>



Previous Article
Next Article

Similar Reads

Generate two output strings depending upon occurrence of character in input string in Python
Given an input string str[], generate two output strings. One of which consists of that character that occurs only once in the input string and the second consists of multi-time occurring characters. Output strings must be sorted. Examples: Input : str = "geeksforgeeks" Output : String with characters occurring once: "for". String with characters o
4 min read
Python String Input Output
Python's print() method is used to show program output, whereas the input() function is used for collecting user input. Python starts to accept all input as strings; other data types require specific conversion. We will learn the fundamental input/output processes in Python in this tutorial. We'll talk about many uses of the Python programming lang
6 min read
Different Input and Output Techniques in Python3
An article describing basic Input and output techniques that we use while coding in python. Input Techniques 1. Taking input using input() function -&gt; this function by default takes string as input. Example: C/C++ Code #For string str = input() # For integers n = int(input()) # For floating or decimal numbers n = float(input()) 2. Taking Multipl
3 min read
SciPy - Input and Output
In this article, we learn about SciPy input and output. In order to handle inputs and outputs of multiple formats, Scipy.io package provides multiple methods. Some of the formats that can be handled by the Scipy.io package are: MatlabNetcdfIDLArffMatrix MarketWave Among this Matlab is the format which is used very frequently. Now let's see the func
2 min read
Biopython - Sequence input/output
Biopython has an inbuilt Bio.SeqIO module which provides functionalities to read and write sequences from or to a file respectively. Bio.SeqIO supports nearly all file handling formats used in Bioinformatics. Biopython strictly follows single approach to represent the parsed data sequence to the user with the SeqRecord object. SeqRecord SeqRecord o
3 min read
Output of python program | Set 13(Lists and Tuples)
Prerequisite: Lists and Tuples 1) What is the output of the following program? C/C++ Code List = [True, 50, 10] List.insert(2, 5) print(List, &quot;Sum is: &quot;, sum(List)) a) [True, 50, 10, 5] Sum is: 66 b) [True, 50, 5, 10] Sum is: 65 c) TypeError: unsupported operand type(s) for +: 'int' and 'str' d) [True, 50, 5, 10] Sum is: 66 Ans. (d) Expla
3 min read
Output of Python Programs | Set 18 (List and Tuples)
1) What is the output of the following program? C/C++ Code L = list('123456') L[0] = L[5] = 0 L[3] = L[-2] print(L) a) [0, '2', '3', '4', '5', 0] b) ['6', '2', '3', '5', '5', '6'] c) ['0', '2', '3', '5', '5', '0'] d) [0, '2', '3', '5', '5', 0] Ans. (d) Explanation: L[0] is '1' and L[5] is '6', both of these elements will be replaced by 0 in the Lis
3 min read
Output of Python Programs | Set 22 (Loops)
Prerequisite: Loops Note: Output of all these programs is tested on Python3 1. What is the output of the following? mylist = ['geeks', 'forgeeks'] for i in mylist: i.upper() print(mylist) [‘GEEKS’, ‘FORGEEKS’]. [‘geeks’, ‘forgeeks’]. [None, None]. Unexpected Output: 2. [‘geeks’, ‘forgeeks’] Explanation: The function upper() does not modify a string
2 min read
Output of Python Programs | Set 24 (Dictionary)
Prerequisite : Python-Dictionary 1. What will be the output? dictionary = {&quot;geek&quot;:10, &quot;for&quot;:45, &quot;geeks&quot;: 90} print(&quot;geek&quot; in dictionary) Options: 10 False True Error Output: 3. True Explanation: in is used to check the key exist in dictionary or not. 2. What will be the output? dictionary ={1:&quot;geek&quot;
2 min read
Output of Python Programs | (Dictionary)
Prerequisite: Dictionary Note: Output of all these programs is tested on Python3 1.What is the output of the following of code? a = {i: i * i for i in range(6)} print (a) Options: a) Dictionary comprehension doesn’t exist b) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6:36} c) {0: 0, 1: 1, 4: 4, 9: 9, 16: 16, 25: 25} d) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg