0% found this document useful (0 votes)
17 views6 pages

Python Input and Output Basics

The document explains input and output operations in Python, highlighting the use of the print() and input() functions for displaying output and gathering user input, respectively. It covers taking single and multiple inputs, typecasting inputs to different data types, and various output formatting techniques. Additionally, it provides examples for each concept to illustrate their usage in Python programming.

Uploaded by

mifapawan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views6 pages

Python Input and Output Basics

The document explains input and output operations in Python, highlighting the use of the print() and input() functions for displaying output and gathering user input, respectively. It covers taking single and multiple inputs, typecasting inputs to different data types, and various output formatting techniques. Additionally, it provides examples for each concept to illustrate their usage in Python programming.

Uploaded by

mifapawan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Input and Output in Python

Understanding input and output operations is fundamental to Python programming. With the
print() function, we can display output in various formats, while the input() function enables
interaction with users by gathering input during program execution.
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.
Example:
name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")
Output
Enter your name: Sachin
Hello, Sachin ! Welcome!
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.
Printing Output using print() 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:
In this example, "Hello, World!" is a string literal enclosed within double quotes. When
executed, this statement will output the text to the console.
print("Hello, World!")

Output
Hello, World!
Printing Variables
We can use the print() function to print single and multiple variables. We can print multiple
variables by separating them with commas. Example:
# Single variable
s = "Sachin"
print(s)
# Multiple Variables
s = "Ankita"
age = 25

1
city = "Prayagraj"
print(s, age, city)

Output
Sachin
Ankita 25 Prayagraj

Take Multiple Input in Python


We are taking multiple 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.
# taking two inputs at a time
x, y = input("Enter two values: ").split()
print("First Number: ", x)
print("Second Number: ", y)
# taking three inputs at a time
x, y, z = input("Enter three values: ").split()
print("First Number: ", x)
print("Second Number : ", y)
print("Third Number : ", z)
Output
Enter two values: 10 9
First Number: 10
Second Number: 9
Enter three values: 7 8 10
First Number: 7
Second Number: 8
Third Number: 10

2
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.
Print Names in Python
The code prompts the user to input a string , assigns it to the variable name and then prints the
inputted name.
# Taking input as string
name = input("What is your name? ")
print(name)
Output
What is your name? Harsh
Harsh

Print Numbers in Python


The code prompts the user to input an integer representing the age, converts the input to an
integer using typecasting and then prints the integer value.
# Taking input as int
# Typecasting to int
age = int(input("Enter your age: "))
print(“Your age is “,age)
Output
Enter your age: 16
Your age is 16

Print Float/Decimal Number in Python


The code prompts the user to input the salary of employee as a floating-point number, converts
the input to a float using typecasting and then prints the salary.
# Taking input as float
# Typecasting to float
salary = float(input("Enter your salary: "))
print(“your salary is :” salary)

3
Output
Enter your salary: 50000.00
your salary is : 50000.00

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.
a = "Hello World"
b = 10
c = 88.99
d = ("Red", "Blue", "Green")
e = ["Red", "Blue, "Green"]
f = {"Red": 1, "Blue":2, "Green":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'>

4
Output Formatting
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()
amount = 150.75
print("Amount: ${:.2f}".format(amount))

Output
Amount: $150.75
Example 2: Using sep and end parameter
# end Parameter with '@'
print("Python", end='@')
print("UnitedUniversity")
# Seprating with Comma
print('R', 'B', 'G', sep=''“ )
# for formatting a date
print('09', '12', '2016', sep='-')
# another example
print('pratik', 'uniteduniversity', sep='@')

Output
Python@UnitedUniversity
RBG
09-12-2016
pratik@uniteduniversity
Example 3: Using f-string
name = 'Tushar'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")

5
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
# 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: 50
The sum is 55

Common questions

Powered by AI

The input() function inherently limits data by accepting user input as a string by default, regardless of the intended type. This limitation can be managed by explicitly typecasting the input to the desired data type. For instance, to handle numerical input, developers must convert the string to an integer or float using int() or float(), respectively, as shown in examples where integer and float inputs are typecasted from strings . Without typecasting, operations on the input would treat it as a string, leading to incorrect results when numeric operations are expected.

Understanding the data type of user input in Python is crucial because it determines how data can be manipulated and interacted with in a program. The input() function returns a string, but specific operations require numeric, boolean, or other data types for correct functioning. Misinterpreting the type can lead to errors or unintended behavior, such as using a string in arithmetic operations. Developers should use type-checking methods, like type(), and typecasting functions to convert inputs for accurate operations and data handling. Illustratively, converting user input to int or float is essential for performing mathematical operations .

A tuple in Python is an immutable data structure, meaning its elements cannot be modified after creation, whereas a list is mutable, allowing changes to its elements. Tuples are typically used for fixed data collections that should remain constant, such as coordinates or settings. Lists are more flexible and are used for collections where the data might change, like a list of user inputs or collected data points. Tuples provide performance benefits in terms of faster access times due to immutability. The example given with d = ("Red", "Blue", "Green") as a tuple and e = ["Red", "Blue", "Green"] as a list illustrates the structural differences .

The sep and end parameters in the print() function control the formatting of the output. The sep parameter specifies the separator between multiple arguments passed to print(), allowing customization of how values are separated, as shown in the print('R', 'B', 'G', sep=''“ ) example, which combines characters without spaces . The end parameter defines what is printed at the end of the output, where the default is a newline; it can be customized to append specific characters to the output, like using end='@' in print("Python", end='@'). These parameters enhance output readability and control the layout of printed information.

In Python, user input obtained through the input() function is read as a string by default. To interpret it as an integer, you must use the int() function to typecast the string. This process is necessary when performing arithmetic operations, as operations on strings and integers differ. For example, converting a user's input to an integer is done using int(input("Enter your age: ")) as illustrated in the typecasting example .

Python's format() method allows different formatting styles tailored for specific data types, like floating-point numbers or currencies. When presenting floating-point numbers, the format() method can define precision, such as {:.2f}, which rounds to two decimal places. For currency values, the format method can be customized to include currency symbols and decimal precision, like "Amount: ${:.2f}".format(amount). Both examples ensure clarity and precision in data representation, enhancing the readability of numeric data. Currency formatting adds context explicitly, which is crucial in financial applications.

Potential errors when typecasting inputs in Python include ValueError, which occurs when the input string cannot be converted to the desired type due to invalid input (e.g., letters in an integer field). Such errors can be mitigated by implementing try-except blocks to catch exceptions during conversion, thereby allowing for error handling without program termination. For example, wrapping the typecast in try-except can manage unexpected user input like alphabetic characters in int(input("Enter a value: ")). Input validation and user prompts that clarify expected input type also help in reducing typecasting errors.

Python handles multiple inputs from a single input prompt by using the split() method, which divides the input string into component parts based on a specified delimiter, usually whitespace. This method allows users to enter multiple values in one line, which are then converted into separate variables. For example, x, y, z = input("Enter three values: ").split() is a way to capture three spaced-separated inputs into three variables . This technique is particularly useful in scenarios where quick data entry is necessary, such as batch processing data or when fetching multiple configuration settings from a command line interface.

Two methods for formatting output in Python are using the format() method and f-strings. The format() method allows you to place placeholders within a string and pass variable values to be formatted, such as "Amount: ${:.2f}".format(amount) to format a float to two decimal places . F-strings, introduced in Python 3.6, allow you to embed expressions directly within strings, using curly braces, and they are prefixed with 'f', for example, f"Hello, My name is {name} and I'm {age} years old.". F-strings are more concise and can be easier to read, while format() is more flexible for complex formatting and older Python versions .

F-strings, which were introduced in Python 3.6, offer benefits over the % operator, particularly in the ease of embedding expressions and variables directly within the string. Unlike the % operator, which can become cumbersome with complex expressions due to the need for placeholders and variable mapping, f-strings allow direct inclusion of Python expressions within braces. For example, using f"Hello, My name is {name} and I'm {age} years old" is more intuitive and readable than "%s and %d" % (name, age). F-strings improve code readability and development speed when dealing with complex expressions and dynamic outputs.

You might also like