Print and Input Functions¶
Let us understand details related to print
and input
functions. These functions will help us in enhancing our learning experience.* print
is primarily used to print the strings on the console while input
is used to accept the input from console.
input
will typically prompts the user to enter the value and we can assign to a variable and use it further.- By default, the value passed for
input
is of typestr
and hence we need to convert the data type of the values entered before processing.
In [1]:
input?
Signature: input(prompt='') Docstring: Forward raw_input to frontends Raises ------ StdinNotImplementedError if active frontend doesn't support stdin. File: ~/.local/lib/python3.8/site-packages/ipykernel/kernelbase.py Type: method
In [3]:
a = int(input('Enter first value: '))
b = int(input('Enter second value: '))
print(f'Sum of first value {a} and second value {b} is {a + b}')
Sum of first value 88 and second value 72 is 160
- When we use
print
with one string, by default it will have new line character at the end of the srring. - We can also pass multiple strings (varrying arguments) and space will be used as delimiter
- We can change the end of the string character, by passing argument
print
can accept 2 keyword argumentssep
andend
to support the above mentioned features.
You will understand more about keyword arguments and varrying arguments in User Defined Functions.
In [4]:
print?
Docstring: print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream. Type: builtin_function_or_method
- You will see Hello and World in separate lines.
In [5]:
# Default print by using one string as argument
print('Hello')
print('World')
Hello World
- You will see Hello and World separated by space.
In [6]:
# Default print by using multiple arguments. Each argument is of type string
print('Hello', 'World')
Hello World
- You will see Hello and World combined together. The new line character is replaced with empty string.
In [7]:
# Changing end of line character - empty string
print('Hello', end='')
print('World')
HelloWorld
In [8]:
# Changing separater to empty string
print('Hello', 'World', sep='')
HelloWorld
- We can pass both
sep
andend
at the same time.
In [9]:
print('Hello', 'World', sep=', ', end=' - ')
print('How', 'are', 'you?')
Hello, World - How are you?