Python provides numerous built-in functions that are readily available to us to use. Some of the
functions like input() and print() are widely used for standard input and output operations
respectively. Let us see the output section first.
Output Using print() function
We use the print() function to output data to the standard output device (screen). We can also
output data to a file, but this will be discussed later.
-
print(“I am learning Python and it’s fun”)
-
I am learning Python and it’s fun
-
a = 10
print('The value of a is', a)
Syntax of the print() function
The actual syntax of the print() function is:
- print(*objects, sep=' ', end='\n', file=sys.stdout,
flush=False)
objects is the value(s) to be printed.
sep separator is used between the values. It defaults into a space character.
After all values are printed, end is printed. It defaults into a new line.
The file is the object where the values are printed and its default value is
sys.stdout
(screen).
-
print(1,2,3,4)
print(1,2,3,4, sep='*')
print(1,2,3,4, sep='#', end='&')
Formatting Output
Formatting an output can be achieved using the format() method.
-
x = 5; y = 10
print('The value of x is {} and y is {}'.format(x,y))
-
The value of x is 5 and y is 10
The curly braces {} are used as placeholders.
We can specify the order in which they are printed by using numbers (tuple index).
-
print('I love {0} and {1}'.format('bread','butter'))
print('I love {1} and {0}'.format('bread','butter'))
-
I love bread and butter
I love butter and bread
We can even use keyword arguments to format the string.
-
print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))
Python Input
Up until now, our programs were static. The value of variables was defined or hard coded into the
source code. In Python, we have the input() function to allow the input from the user ot the
make the programe more flexible.
Syntax of the print() function
The syntax for input() is:
- input([prompt])
where [prompt] is the string we wish to display on the screen. It is optional.
-
num1 = input('Enter a number: ')
num2 = input('Enter another number: ')
print("Result: ", num1 + num2)
-
Enter a number: 2
Enter another number: 3
Result: 23
Notice that the result should have been 5 but it has given you 23. The reason is the value
entered by the user is treated as a string and not a number. Therefore, the “+” has concatenated
the values.
To convert this into a number we can use int() or float() functions:
-
num1 = input('Enter a number: ')
num1 = int(num1)
num2 = input('Enter another number: ')
num2 = int(num2)
print("Result: ", num1 + num2)
# Or
num1 = int(input('Enter a number: '))
num2 = int(input('Enter another number: '))
print("Result: ", num1 + num2)
-
Enter a number: 2
Enter another number: 3
Result: 5