Receiving standard input tips @ python

To receive input

Use the input function when assigning input from the console to an object. By the way, the raw_input function is obsolete in python3.

inp=input('Enter something>')

 # [In]#Enter something>hogehoge
 # [In]# inp
 # [Out]# 'hogehoge'

Find standard input until correct value is obtained

If there is a desire to "type in this format!", A technique that loops until the shape is typed. Loop infinitely with while True: and ask for the value of ʻinpuntil'hoge'is entered. break` the loop when'hoge'is entered.

while True:
	inp=input('Enter hoge>>')
	if inp=='hoge':break

 # [Out]#Enter hoge>>foo
 # [Out]#Enter hoge>>hogehoge
 # [Out]#Enter hoge>>hoge

 # [In]# inp
 # [Out]# 'hoge'

It returns an error message and listens to the input until you enter 6 digits.

It's even better if you get an error message that you're wrong when you type something wrong. Use a try-except statement in addition to the while True to jump to ʻexcept` if an error occurs.

while True:
	try:
		inp=input('Enter a 6-digit number>> ')
		if inp.isdigit() and len(inp)==6:
			break
	except:
		pass
	print('Input Machigo Toru')


 # [Out] #Enter a 6-digit number>> 3
 # [Out]#Input Machigo Toru
 # [Out] #Enter a 6-digit number>> 45
 # [Out]#Input Machigo Toru
 # [Out] #Enter a 6-digit number>> 666666
 # [In] # inp
 # [Out]# 666666

Infinite loop with while True: Use the isdigit function to determine if the content of the string is a number And check the length of the character string with the len function If you enter an incorrect value, the try statement will be omitted and an error message will be printed, returning to the beginning of the while clause.

Ask yes / no

Make sure that True is entered when the acronym'y'for'Yes' is entered, and False is entered when the acronym'n'for'No'is entered. Entering'y'enters the bool value True, and entering'n'enters the bool value False in imp.

~~inp=True if input('y/n? >> ')=='y' else False~~ Simplified because it is an orokanakoto that replaces the truth value with the truth value

inp=input('y/n? >> ')=='y'




 # In# inp=True if input('y/n? >> ')=='y' else False
 y/n? >> y

 # In# inp
 # Out# True

 # In# inp=True if input('y/n? >> ')=='y' else False
y/n? >> n

 # In# inp
 # Out# False

Since it can be written in one line, it is convenient if you write it as a test under the condition that "I absolutely enter only either'y'or'n'". But it's easy, but it's not enough. Returns True when'y'is entered, but returns False when'yes' is entered. Even if a character string other than'y'and'n' is input, False is returned.


 # In# inp=True if input('y/n? >> ')=='y' else False
y/n? >> yes

 # In# inp
 # Out# False

 # In# inp=True if input('y/n? >> ')=='y' else False
y/n? >> t

 # In# inp
 # Out# False

Use a dictionary for choice

Therefore, prepare a dictionary containing'y',' yes',' n', and'no'. The dictionary can be used like a C language switch-case statement.

dic={'y':True,'yes':True,'n':False,'no':False}
dic[input('[Y]es/[N]o? >> ').lower()]




 # [In]# dic[input('[Y]es/[N]o? >> ').lower()]
 # [Out]# [Y]es/[N]o? >> y
 # [Out]# True

 # [In]# dic[input('[Y]es/[N]o? >> ').lower()]
 # [Out]# [Y]es/[N]o? >> NO
 # [Out]# False

 # [In]# dic[input('[Y]es/[N]o? >> ').lower()]
 # [Out]# [Y]es/[N]o? >> ye
 # [Out]# ---------------------------------------------------------------------------
 # KeyError                                  Traceback (most recent call last)
 # <ipython-input-34-67f9611165bf> in <module>()
       # 1 dic={'y':True,'yes':True,'n':False,'no':False}
 # ----> 2 dic[input('[Y]es/[N]o? >> ').lower()]
 # 
 # KeyError: 'ye'

By casually using the lower function to make the input all lowercase,'YES' and'yes' are considered synonymous. This is not enough yet, and if you type'ye' where you want to type'yes', you can type KeyError

So we use the while True: and try states.

dic={'y':True,'yes':True,'n':False,'no':False}
while True:
	try:
		inp=dic[input('[Y]es/[N]o? >> ').lower()]
		break
	except:
		pass
	print('Error! Input again.')


 # [Out]# [Y]es/[N]o? >> ye
 # [Out]# Error! Input again.
 # [Out]# [Y]es/[N]o? >> yes

 # [In]# inp
 # [Out]# True

The method pointed out by shiracamus below

How to use in

while True:
    inp = input('[Y]es/[N]o? >> ').lower()
    if inp in dic:
        inp = dic[inp]
        break
    print('Error! Input again.')

How to determine if the first character of the entered string is'y'or'n'

while True:
    inp = input('[Y]es/[N]o? >> ').lower()
    if inp in ('y', 'yes', 'n', 'no'):
        inp = inp.startswith('y') # inp[0] == 'y'Synonymous with
                                  # string.startwith looks up the first string
        break
    print('Error! Input again.')

How to return a non-bool value and loop again if a value that is not in the dictionary is entered

while True:
    inp = dic.get(input('[Y]es/[N]o? >> ').lower(), -1)   #default value of inp-1(← Anything is fine as long as it is not a bool value)Keep
    if type(inp) is bool:
        break
    print('Error! Input again.')

Receive multiple standard inputs

I want to receive the specified number of standard inputs and store them in the list

If you ask three times in a row and want to store it in a list, you can use the in-list notation.

[input() for _ in range(3)]
 # [In]# a
 # [In]# d
 # [In]# v
 # [Out]#: ['a', 'd', 'v']

I want to receive multiple standard inputs in one line and store them in a list

Sometimes you want to accept multiple inputs in one line. In such a case, add a split function after the input function to divide it. The default argument of the split function is a whitespace character, so it is stored in the list separated by spaces. If you want to separate it with another character, put that character in the argument of the split function. For example, if you want to separate them with commas, do as follows.

a=input('Enter something separated by commas>> ').split(',')


	# [In] a=input('Enter something separated by commas>> ').split(',')
	# [Out]Enter something in the comma ward>> 2016,2017

	# [In] a
	# [Out] ['2016', '2017']

I want to receive any number from standard input and store it in the list

A technique that takes standard input and stores it in a list until the suspend command (ctrl + Z in windows) is pressed. The sys.stdin.readline series is a set of functions for getting standard input for a wider range of purposes than ʻinput`.

You can use it by importing the sys library.

readline () is a function to get one line from standard input. Unlike ʻinput (), input automatically removes the newline character, while readline ()gets the contents given to the standard input as it is. Use thestrip ()` method to remove line breaks.

import sys
inp=sys.stdin.readline().strip()




 # [In]# inp=sys.stdin.readline()
 # [In]# pp

 # [In]# inp
 # [Out]# 'pp\n'

 # [In]# inp=sys.stdin.readline().strip()
 # [In]# inp
 # [Out]# 'pp'

readlines is a function to get multiple lines from standard input. The return value is a list, and the input character string is stored as an element line by line. There is no automatic deletion of newline characters here either, so use sprit ().

import sys
[i.strip() for i in sys.stdin.readlines()]


 # [In]# ho
 # [In]# hsop
 # [In]# hpoge
 # [In]# ^Z
 # [Out]# ['ho', 'hsop', 'hpoge']

reference

  1. stack overflow : Get a Try statement to loop around until correct value obtained
  2. Tips you should know when programming in Python (input / output)
  3. LIFE WITH PYTHON: Python Tips: I want to get a string from standard input

Recommended Posts

Receiving standard input tips @ python
[Python] Standard input
[Python] About standard input
[Python3] Standard input [Cheat sheet]
Part 1 of receiving standard input
Python3 standard input (competition pro)
Standard input / summary / python, ruby
python tips
python tips
Which is better, python standard input receiving input () or sys.stdin?
Python Tips
Python tips
Python3 standard input for competitive programming
Matrix representation with Python standard input
Tips on Python file input / output
Python Paiza-Various skill checks and standard input
Python Conda Tips
Python debugging tips
Python3 standard input I tried to summarize
Python click tips
Unexpectedly (?) Python tips
Standard input summary
Atcoder standard input set for beginners (python)
[Python] Add comments to standard input files
Python: Use zipfile to unzip from standard input
Python Tips (my memo)
python input and output
Python audio input / output
Memorize Python commentary 4 --Input
Python PyTorch install tips
Key input in Python
[Blender x Python] Blender Python tips (11/100)
Standard input / output summary
Have python parse the json entered from the standard input
[Python] Change standard input from keyboard to text file
Python / Numpy np.newaxis thinking tips
Cisco Memorandum _ Python config input
Python 3.4 or later standard pip
Write standard input in code
Python standard unittest usage notes
[For beginners] Summary of standard input in Python (with explanation)
Python Input Note in AtCoder
Transposed matrix in Python standard
[Tips] Handle Athena with Python
[Python + Selenium] Tips for scraping
Google Drive Api Tips (Python)
~ Tips for beginners to Python ③ ~
[For AtCoder] Standard input memo
python standard virtual environment venv
[Python] How to use input ()
Python standard input summary that can be used in competition pro
Install Python 3.8 on Ubuntu 18.04 (OS standard)
LaTeX, Python tips in master's thesis
Install Python 3.8 on Ubuntu 20.04 (OS standard)
Input / output with Python (Python learning memo ⑤)
[Python] Adjusted the color map standard
Make standard output non-blocking in Python
Comply with Python coding standard PEP8
[TouchDesigner] Tips for for statements using python
Tips for calling Python from C
Let's see using input in python