Python: Input & Output

Anh-Thi Dinh

Input

1# Get input from user and display (input's type is `string`)
2age = input("Your age? ") # python 3, raw_input for python 2
3print("Your age:", age) # don't need space after "age"
1# Get the input and store to numbers list
2numbers = list(map(int, input().split()))
1# Get multi inputs on 1 line
2x, y, z, n = (int(input()) for _ in range(4))

Comment

Using # on each line.
1# print("This is not showed.")
2print("This is showed.")
 
1# output
2This is showed.
1# Print normally
2print("Hello!") # python 3
3print "Hello!" # python 2
1# output
2Hello!
3Hello!
1# print with `format`
2print("Hello {} and {}.".format("A", "B"))
1# output
2Hello A and B.
1# change order
2print("Hello {2} and {1}.".format("A", "B"))
1# output
2Hello B and A.
1# Directly insert (python 3.6 or above)
2b = "B"
3print(f'Hello {"A"} and {b}.')
1# output
2Hello A and B.
1# long strings
2print('This is a part of sentence.'
3      'This is other part.')
1# output
2This is a part of sentence. This is other part.
1# print decimals
2print("{:.6f}".format(number))
1# print decimals
21.000000
1# print multiples
2print("1", 5, "thi") # there are spaces
1# print multiples
21 5 thi
1# first 20 characters, second 10 characters
2print( '{:<20s} {:<10s}'.format(string_one, string_two) )
Display separated results (like in executing multiple code cells),
1display(df_1)
2display(df_2)

Logging

Check more here.
1import logging
2log = logging.getLogger(__name__)
3
4# order of increasing severity
5log.debug('something')
6log.info('something')
7log.warning('something')
8log.error('something')
9logger.critical('something')
10
11# by default, the logging module logs the messages with a severity level of WARNING or above
12# thus: debug and info aren't show by default
If the log.info() doesn't work, set below (ref),
1logging.getLogger().setLevel(logging.INFO) # show all except "debug"
2# or
3logging.basicConfig(level=logging.DEBUG) # show all
1# in the class
2import logging
3log = logging.getLogger(__name__)
4
5log.info("abc")
6log.debug("xyz")
7
8log.info("abc: %s", abc)
9log.debug("xyz: {}".format(xyz))
1# in the jupyter notebook
2import logging
3log = logging.getLogger(__name__)
4logging.basicConfig(level=os.environ.get("LOGLEVEL", "DEBUG"))
Loading comments...