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'
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'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.
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
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
while True:
inp = input('[Y]es/[N]o? >> ').lower()
if inp in dic:
inp = dic[inp]
break
print('Error! Input again.')
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.')
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.')
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']
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']
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 the
strip ()` 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']
Recommended Posts