___|  _ \   |  |    |   |_ _|\ \     / ____|
 |     |   |  |  |    |   |  |  \ \   /  __|
 |   | |   | ___ __|  ___ |  |   \ \ /   |
\____|\___/     _|   _|  _|___|   \_/   _____| 

 --- A GOPHER-LIKE INTERFACE FOR HIVE BLOCKCHAIN ---

python 3 snippets: basic I/O

BY: @spearous | CREATED: July 29, 2018, 3:38 p.m. | VOTES: 0 | PAYOUT: $0.00 | [ VOTE ]

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.

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

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
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.

TAGS: [ #python ] [ #python3 ] [ #acm ] [ #basic ] [ #snippets ]

Replies

@steemitboard | July 22, 2019, 10:15 a.m. | Votes: 0 | [ VOTE ]

Congratulations @spearous! You received a personal award!

https://steemitimages.com/70x70/http://steemitboard.com/@spearous/birthday2.pngHappy 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!
[ BACK TO TRENDING ] [ BACK TO MENU ]
CMD>