Input
Python provides 2 inbuilt functions to read input from keyboard.
- input(prompt)
- raw_input(prompt)
| Property | input | raw_input |
|---|---|---|
| Syntax | input(prompt) | raw_input(prompt) |
| Functioning | tells the program to stop and wait for the user to input the values | tells the program to stop and wait for the user to input the values |
| Python versions supported | both Python 2.x and Python 3.x | only in Python 2.x |
| input type | In Python 3.x, the input function explicitly converts the input you give to type string. But Python 2.x input function takes the value and type of the input you enter as it is without modifying the type | Type is always string. We need to typecase it, if required. |
| Example |
|
|
- Developers are recommended to use raw_input function in Python 2.x. Because there is a vulnerability in input function in Python 2.x version.
- For taking multiple inputs at once, take the input as string and split it into multiple variables using split()
Output
print() function prints the message to the
screen or any other standard output device.
print(value(s), sep= ' ', end = '\n', file=file, flush=flush) # syntax
''' params
value(s) : Any value(s). Will be converted to string before printed.
sep(Optional): Specify how to separate the objects, if more than one. Default : ' '
end(Optional): Specify what to print at the end. Default : '\n'
file(Optional): An object with a write method. Default : sys.stdout
flush(Optional): A Boolean, specifying if the output is flushed (True) or buffered (False). Default: False
'''
The print statement accepts multiple objects separated by ","
name = input("enter your name.")
print("hi", name)
Output Formatting
There are several ways to format output.- To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark.
- The string method str.format() helps a user create a fancier output.
''' using String modulo operator(%) '''
# integer, float, octal, exponential
print("Students: %2d, Marks: %5.2f, Grades: %7.3o, percentile: %10.3E" % (100, 05.333, 25, 356.08977)) # Students: 100, Marks: 5.33, Grades: 031, percentile: 3.561E+02
# the general syntax here is %[flags][width][.precision]type
''' using the format method '''
# without using indexing
print('Hi {}, and hello {}!'.format('abc', 'def')) # Hi abc, and hello def!
# using indexing
print('{1} and {0}'.format('abc', 'def')) # def and abc
# using format fields
print("Second argument: {1:3d}, first one: {0:7.2f}".format(47.42, 11)) # Second argument: 11, first one: 47.42
# using format in dictionary
data = dict(a ="abc", b ="def")
print("Hi {a}, hello {b}!".format(**data)) # Hi abc, and hello def!
''' using the String method '''
name = "abcd"
print (cstr.center(10, '#')) # ###abcd###
print (cstr.ljust(10, '-')) # abcd------
print (cstr.rjust(10, '-')) # ------abcd