Contents
Python Basic Input and Output
Python Basic Input and Output
Input and output operations are fundamental to Python programming, allowing programs to interact with users. The print()
function displays information on the console, while the input()
function captures user input.
Displaying Output in Python
The print()
function in Python is the primary method to display output, including text, variables, and expressions.
Example:
print("Hello, World!")
Output:
Hello, World!
Printing Variables
You can print single or multiple variables, adding descriptive labels:
name = "Alice"
age = 30
print("Name:", name, "Age:", age)
Output:
Name: Alice Age: 30
Format Output Handling in Python
Python offers several ways to format output, including the format()
method, the sep
and end
parameters in print()
, f-strings, and the %
operator. Each method provides control over data display for enhanced readability.
- Using
format()
method:
amount = 150.75
print("Amount: ${:.2f}".format(amount))
Output:
Amount: $150.75
- Using
sep
andend
parameters:
# Using 'end' to connect lines
print("Python", end='@')
print("Programming")
# Using 'sep' for separator
print('G', 'F', 'G', sep='')
# Date formatting example
print('09', '12', '2023', sep='-')
Output:
Python@Programming
GFG
09-12-2023
- Using f-string:
name = 'Sam'
age = 25
print(f"Hello, My name is {name} and I'm {age} years old.")
Output:
Hello, My name is Sam and I'm 25 years old.
- Using
%
operator for formatting:
num = int(input("Enter a value: "))
add = num + 5
print("The sum is %d" % add)
Output:
Enter a value: 10
The sum is 15
Taking Multiple Inputs
The split()
method helps take multiple inputs in a single line, dividing the inputs into separate variables.
# Taking two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of apples:", x)
print("Number of oranges:", y)
Output:
Enter two values: 3 5
Number of apples: 3
Number of oranges: 5
Conditional Input Handling
You can prompt users for input, convert it to a specific data type, and handle conditions based on that input.
age = int(input("Enter your age: "))
if age < 18:
print("You are a minor.")
elif age < 65:
print("You are an adult.")
else:
print("You are a senior citizen.")
Output:
Enter your age: 22
You are an adult.
Converting Input Types
By default, the input()
function reads user input as a string. Convert it to other types like int
or float
if needed.
- Example to take string input:
color = input("What color is the sky?: ")
print(color)
- Example to take integer input:
count = int(input("How many stars?: "))
print(count)
- Example to take floating-point input:
price = float(input("Enter the price: "))
print(price)
Finding Data Type of a Variable
To determine the data type of a variable, use type()
.
Exanple:
a = "Hello"
b = 10
c = 12.5
d = ["apple", "banana"]
print(type(a)) # str
print(type(b)) # int
print(type(c)) # float
print(type(d)) # list
Output:
Taking input from console in Python
In Python, the Console (also referred to as the Shell) is a command-line interpreter. It processes commands entered by the user, one at a time, and executes them. If the command is error-free, the console runs it and displays the result; otherwise, it returns an error message. The prompt in the Python Console appears as >>>
, which indicates that it’s ready to accept a new command.
To start coding in Python, understanding how to work with the console is crucial. You can enter a command and press Enter to execute it. After a command has run, >>>
will reappear, indicating that the console is ready for the next command.
Accepting Input from the Console
Users can enter values in the Console, which can then be used within the program as needed. The built-in input()
function is used to capture user input.
# Capturing input
user_input = input("Enter something: ")
# Displaying output
print("You entered:", user_input)
You can convert this input to specific data types (integer, float, or string) by using typecasting.
1. Converting Input to an Integer : When you need to capture integer input from the console, you can convert the input to an integer using int()
. This example captures two inputs as integers and displays their sum.
# Taking integer inputs
number1 = int(input("Enter first number: "))
number2 = int(input("Enter second number: "))
# Printing the sum as an integer
print("The sum is:", number1 + number2)
2. Converting Input to a Float : To treat the input as a floating-point number, use the float()
function to cast the input.
# Taking float inputs
decimal1 = float(input("Enter first decimal number: "))
decimal2 = float(input("Enter second decimal number: "))
# Printing the sum as a float
print("The sum is:", decimal1 + decimal2)
3. Converting Input to a String: All inputs can be converted to strings, regardless of their original type. The str()
function is used for this purpose, though it’s also optional since input()
captures input as a string by default.
# Converting input to a string (optional)
text = str(input("Enter some text: "))
# Displaying the input as a string
print("You entered:", text)
# Or simply:
text_default = input("Enter more text: ")
print("You entered:", text_default)
Python Output using print() function
The print()
Function in Python
The print()
function in Python displays messages on the screen or any other standard output device. Let’s dive into the syntax, optional parameters, and examples that showcase various ways to use print()
in Python.
Syntax of print()
print(value(s), sep=' ', end='\n', file=file, flush=flush)
Parameters
1. value(s): Any number of values to print, which are converted to strings before display.
2. sep: Optional. Defines a separator between multiple values. Default is a space (‘ ‘).
3. end: Optional. Defines what to print at the end of the output. Default is a newline (‘\n’).
4. file: Optional. Specifies a file-like object to write the output to. Default is sys.stdout.
5. flush: Optional. A Boolean value indicating whether to forcibly flush the output. Default is False.
By calling print()
without arguments, you can execute it with empty parentheses to print a blank line.
Example of Basic Usage
first_name = "Sam"
age = 40
print("First Name:", first_name)
print("Age:", age)
Output:
First Name: Sam
Age: 40
How print()
Works in Python
You can pass different data types like variables, strings, and numbers as arguments. print()
converts each parameter to a string using str()
and concatenates them with spaces.
first_name = "Mona"
age = 28
print("Hello, I am", first_name, "and I am", age, "years old.")
String Literals in print()
\n
: Adds a new line.""
: Prints an empty line.
print("DataScienceHub \n is a great resource for learning.")
# Output:
# DataScienceHub
# is a great resource for learning.
Using the end
Parameter
The end
parameter lets you specify what appears after the output. By default, it’s set to \n
, but you can customize it.
print("Data Science is a growing field", end=" ** ")
print("Stay curious!")
# Output:
# Data Science is a growing field ** Stay curious!
Concatenating Strings in print()
You can concatenate strings directly within print()
.
print("Python is a powerful " + "programming language.")
# Output:
# Python is a powerful programming language.
Output Formatting with str.format()
Using str.format()
lets you format the output.
x, y = 5, 20
print("The values of x and y are {} and {}, respectively.".format(x, y))
# Output:
# The values of x and y are 5 and 20, respectively.
Combining print()
with input()
You can take input from the user and print it.
number = input("Please enter a number: ")
print("The number you entered is:", number)
Output:
Please enter a number: 50
The number you entered is: 50
Using flush
in print()
The flush
argument forces Python to write each character immediately, useful in cases like a countdown timer.
import time
countdown = 5
for i in reversed(range(countdown + 1)):
if i > 0:
print(i, end="...", flush=True)
time.sleep(1)
else:
print("Go!")
Using the sep
Parameter
The sep
argument allows you to customize the separator for multiple values.
day, month, year = 10, 10, 2024
print(day, month, year, sep="/")
# Output:
# 10/10/2024
File Argument in print()
The file
argument allows you to print to a file rather than the screen.
import io
# Create a virtual file
buffer = io.StringIO()
# Print to the buffer instead of standard output
print("Hello, Pythonistas!", file=buffer)
# Retrieve the contents of the buffer
print(buffer.getvalue())
Output:
Hello, Pythonistas!
In Python, presenting program output can take various forms: it can be printed in a readable format, written to a file, or customized based on user needs. Here’s an overview of Python’s formatting options:
Output Formatting in Python
Python offers several methods for string formatting:
1. String Modulo Operator (%)
2. format() Method
3. Formatted String Literals (f-strings)
Using the String Modulo Operator (%)
The %
operator can be used to format strings in a way similar to printf
in C. Although Python doesn’t have a printf()
function, the %
operator is overloaded to allow printf-style formatting.
Example:
# Formatting integers and floats
print("Books: %2d, Price: %5.2f" % (4, 32.75))
print("Total items: %3d, Cost: %6.2f" % (120, 49.90))
# Formatting octal and exponential values
print("%4o" % (25)) # Octal
print("%8.2E" % (457.12345)) # Exponential
Output:
Books: 4, Price: 32.75
Total items: 120, Cost: 49.90
31
4.57E+02
In %2d
, 2
specifies the width (padded with spaces if shorter). %5.2f
formats a float with width 5 and 2 decimal places.
Using the format()
Method
Introduced in Python 2.6, the format()
method offers flexibility in string formatting. {}
placeholders mark where values should be inserted, with the option to specify formatting details.
Example:
print("I enjoy {} with '{}'.".format("coding", "Python"))
print("{0} is the best {1}".format("Python", "language"))
print("{1} is popular for {0}".format("programming", "Python"))
Output:
I enjoy coding with 'Python'.
Python is the best language
Python is popular for programming
Combining Positional and Keyword Arguments:
# Positional and keyword arguments
print("Language: {0}, Version: {1}, {other}.".format("Python", "3.10", other="fun"))
print("Python:{0:2d}, Version:{1:5.2f}".format(12, 3.1415))
Output:
Language: Python, Version: 3.10, fun.
Python:12, Version: 3.14
Using Dictionaries with format()
You can also format strings with dictionary values by referencing keys within placeholders.
Example:
info = {'lang': 'Python', 'version': '3.10'}
print("Language: {0[lang]}, Version: {0[version]}".format(info))
Output:
Language: Python, Version: 3.10
Using Formatted String Literals (f-Strings)
Introduced in Python 3.6, f-strings allow embedding expressions directly in string literals, denoted by an f
prefix.
Example:
language = "Python"
version = 3.10
print(f"Language: {language}, Version: {version:.1f}")
Output:
Language: Python, Version: 3.1
String Methods for Formatting
Python provides methods like str.ljust()
, str.rjust()
, and str.center()
to align strings with padding.
Example:
text = "Python"
print("Center aligned:", text.center(20, '*'))
print("Left aligned:", text.ljust(20, '-'))
print("Right aligned:", text.rjust(20, '-'))
Output:
Center aligned: *******Python*******
Left aligned: Python--------------
Right aligned: --------------Python
Conversion Codes in Python Formatting
Below is a table of some conversion specifiers:
Code | Meaning |
---|---|
d | Decimal integer |
b | Binary format |
o | Octal format |
x/X | Hexadecimal format |
e/E | Exponential notation |
f/F | Floating-point decimal |
s | String |
% | Percentage |
How to set an input time limit in Python?
In this article, we will explain how to set an input time limit in Python. Python is an easy-to-learn programming language that is dynamically typed and garbage collected. Here, we will explore different methods to set an input time limit.
Methods to Set an Input Time Limit in Python
- Using the
inputimeout
module - Using the
select
module - Using the
signal
module - Using the
threading
module
Method 1: Set an Input Time Limit using the inputimeout
module
The inputimeout
module allows users to handle timed input across different platforms. To use this module, it must be installed first using the following command:
pip install inputimeout
Example:
from inputimeout import inputimeout, TimeoutOccurred
try:
# Take timed input using the inputimeout() function
response = inputimeout(prompt='What is your favorite color? ', timeout=5)
except TimeoutOccurred:
response = 'Time is up!'
print(response)
Method 2: Set an Input Time Limit using the select
module
The select
module provides a way to monitor input/output on multiple file descriptors. It is part of the Python standard library and doesn’t require installation. This method helps handle input with a timeout in a cross-platform way.
Example:
import sys
import select
print("What is your favorite color?")
print("You have 10 seconds to answer.")
# Wait for input with a 10-second timeout
ready, _, _ = select.select([sys.stdin], [], [], 10)
if ready:
print("Your favorite color is:", sys.stdin.readline().strip())
else:
print("Time's up!")
Method 3: Set an Input Time Limit using the signal
module
The signal
module in Python allows your program to handle asynchronous events such as timeouts. By setting an alarm signal, you can interrupt the input process after a specific time.
Example:
import signal
def timeout_handler(signum, frame):
print("\nTime's up!")
# Set the timeout signal handler
signal.signal(signal.SIGALRM, timeout_handler)
def get_input():
try:
print("What is your favorite color?")
print("You have 5 seconds to answer.")
signal.alarm(5) # Set a 5-second alarm
response = input()
signal.alarm(0) # Cancel the alarm if input is received
return response
except Exception:
return "No answer within time limit"
answer = get_input()
print("Your favorite color is:", answer)
Method 4: Set an Input Time Limit using the threading
module
The threading
module allows you to run multiple tasks simultaneously. By using a timer, you can create a time limit for input and interrupt it once the time has passed.
Example:
from threading import Timer
def time_up():
print("\nTime's up! You took too long to respond.")
def ask_question():
print("What is your favorite color?")
timer = Timer(5, time_up) # Set a 5-second timer
timer.start()
answer = input()
timer.cancel() # Cancel the timer if input is received on time
return answer
response = ask_question()
print("Your favorite color is:", response)
How to take integer input in Python?
In this article, we’ll cover how to take integer input in Python. By default, Python’s input()
function returns a string. To work with integers, we need to convert these inputs to integers using the int()
function.
Examples 1: Single Integer Input
# Take input from the user
value = input("Enter a number: ")
# Display data type before conversion
print("Type before conversion:", type(value))
# Convert to integer
value = int(value)
# Display data type after conversion
print("Type after conversion:", type(value))
Output:
Enter a number: 100
Type before conversion:
Type after conversion:
Example 2: Taking String and Integer Inputs Separately
# String input
string_value = input("Enter a word: ")
print("Type of string input:", type(string_value))
# Integer input
integer_value = int(input("Enter a number: "))
print("Type of integer input:", type(integer_value))
Output:
Enter the size of the list: 3
Enter list elements (space-separated): 8 16 24
The list is: [8, 16, 24]
Difference between input() and raw_input() functions in Python
Input Functions in Python
In Python, we can use two main functions to capture user input from the keyboard:
1. input ( prompt )
2. raw_input ( prompt )
input() Function
The input()
function allows the program to pause and wait for the user to enter data. It’s built into Python and available in both Python 2.x and 3.x. However, there’s a key difference:
- In Python 3.x,
input()
always returns the user input as a string. - In Python 2.x,
input()
returns data in the type entered by the user (e.g., numbers are returned as integers). Because of this, it’s often recommended to useraw_input()
instead in Python 2.x for better consistency and security.
Example in Python 3.x
# Python 3 example with input() function
name = input("Enter your name: ")
print("Data type:", type(name))
print("You entered:", name)
# Taking a number and converting it to an integer
number = input("Enter a number: ")
print("Data type before conversion:", type(number))
number = int(number)
print("Data type after conversion:", type(number))
print("You entered:", number)
Output:
Enter your name: Alice
Data type:
You entered: Alice
Enter a number: 42
Data type before conversion:
Data type after conversion:
You entered: 42
raw_input() Function
In Python 2.x, raw_input()
is used to take user input as a string, similar to the input()
function in Python 3.x. It’s the recommended method for general input in Python 2.x due to security vulnerabilities with input()
.
Example in Python 2.x with raw_input()
# Python 2 example with raw_input() function
name = raw_input("Enter your name: ")
print("Data type:", type(name))
print("You entered:", name)
# Taking a number and converting it to integer
number = raw_input("Enter a number: ")
print("Data type before conversion:", type(number))
number = int(number)
print("Data type after conversion:", type(number))
print("You entered:", number)
Differences Between input()
and raw_input()
in Python 2.x
input() | raw_input() |
---|---|
Takes user input and tries to evaluate it. | Takes user input as a string. |
Syntax: input(prompt) | Syntax: raw_input(prompt) |
May execute arbitrary code if not handled correctly. | Safer, as input is taken only as a string. |
Converts input into respective data type. | Returns the input as a string. |
Available in both Python 2.x and 3.x. | Available only in Python 2.x. |