python 3 snippets: basic I/O

in #python6 years ago

Intro

Here I summarize the basic I/O snippet in python 3, so to be used later. A major difference is raw_input() is removed in python3 and there is some change in print() function as well.

input()

The basic input() to get an integer input looks like this:

list_of_input = int(input("please give an integer:"))

SInce the default type python gets from the input is a string, we should use int() to convert it into the desired data type. Now we shall assemble out some snippets to tackle more sophisticated input.

  • several integers input in a line and are separated by spaces
    example input:

1 2 3 4

print ("Type integers in one line,  separated by a space:\n")

while True:
  try:
    list_of_input = map(lambda x:int(x), input().split()) 

# or convert it into a list 
#   list_of_input = list(map(lambda x:int(x), input().split()))

# or put directly into a list
#  list_of_input = [a[0] for a in input().split()]

  except ValueError as err:
    print(err)
    continue
  except EOFError:
#   print("End of input")
#   break
    continue
  • several integers in several lines and are each followed by EOF:

example input

1
2
3
4

import sys
while True:
  try:
    list_of_input = list(x[0] for x in sys.stdin)

  except ValueError as err:
    print(err)
    continue
  except EOFError:
#   print("End of input")
#   break
    continue
  • to decide an input character is a letter or a number: if it is a number then return the number in int type, if it is a letter, return the letter in string type.
def return_char_in_int_or_string(x):
    if (ord(x)<90):
        return(ord(x))
    return(x)

print()

Usually, print() is pretty straightforward. The only difference with python 2.x is now print needs "()" to include the content.

print("number1= %d , number2=%d"  % (number1, number2) )

The prototype of print() in python 3.x is:

print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

so to output without a newline, one could do:

print("*",end="")

to specify the ending character (the above example is null, which means no newline after the output)

However, in python 2.x, the old trick was:

print x,

No newline will be created due to the extra "," at the end. However, there will be an extra space at the end of the output though.

Sort:  

Congratulations @spearous! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.28
TRX 0.12
JST 0.033
BTC 69849.38
ETH 3709.01
USDT 1.00
SBD 3.73