Python Menu

Input-Output Operations in Python


Input and Output operations are performed using two built-in functions

  • print( ) - Used for output operation.
  • input( ) - Used for input operations.

1. print()

The print() function prints the specified message to the screen, or other standard output device.
The message can be a string, or any other object, the object will be converted into a string before written to the screen.

Syntax:
print(object(s), separator=separator, end=end, file=file, flush=flush)

When we use the print( ) function to display a message, the string can be enclosed either in the single quotation or double quotation.

format:
print('how are you?')
print("have fun with python")

function is also used to display variables value. The following example shows that how to display the combination of message and variable value

format:
x = 10
print('The value of variable num1 is ' + x)

In Python, we can use the formatted string that is prefixed with character "f". In the formatted string, the variable values are included using curly braces ({ }). Return value of print( ) function is default None.

format:
x = 10
print(f"The value of variable num1 is {x}")

However, it turns out that this function can accept any number of positional arguments, including zero, one, or more arguments. That’s very handy in a common case of message formatting, where you’d want to join a few elements together.

format:
a=10
b=20
print("a= ",a,"b= ",b)

integer and String objects have a built-in operation using the % operator, which you can use to format strings.

format:
a=10
b='python'
print("a= %d b= %s" %(a,b))

By default, python's print() function ends with a newline. This function comes with a parameter called 'end.' The default value of this parameter is '\n,' i.e., the new line character. You can end a print statement with any character or string using this parameter. This is available in only in Python 3+

format:
print ("Welcome to", end = ' ') 
print ("python", end = '!')

2. input()

The Python provides a built-in function input( ) to perform input operations.

Syntax:
input(prompt)

Use the prompt parameter to write a message before the input.

format:
x = input('Enter your name:')
print('Hello, ' + x)

The Python does not provide any direct function to read a single character as input. But we can use the index value to extract a single character from the user entered input value. Let's look at the following Python code.

format:
x = input('Enter your name:')[0]
print('Hello, ' + x)

Always the input( ) function reads input value as string value only. To read the value of any other data type, there is no input function in Python. Explicitly we need to convert to the required data type using type casing.

format:
x = int(input('Enter a value:'))
print('The value is : ', x)


Next Topic :Variables in Python