0

入力を要求する単純な Python (シェル) プログラムを作成しています。私が探しているのは、文字列の特定の長さ (len) です。文字列が最小値でない場合は、例外をスローし、ユーザーを入力プロンプトに戻して再試行させたいと考えています (試行回数が 3 回など)。

私のコードは基本的にこれまでです

x=input("some input prompt: ")
if len(x) < 5:
print("error message")
count=count+1 #increase counter

等...

-- これは私が立ち往生している場所です。エラーをスローしてから、入力に戻りたい... Python の初心者なので、助けていただければ幸いです。これは、Linux ボックスのスクリプトの一部になります。

4

2 に答える 2

1

ループはこれに適しています。

raw_inputまた、入力の代わりに使用することもできます。入力関数は、入力を解析して python として実行します。実行するpythonコマンドではなく、ある種のパスワードをユーザーに求めていると思います。

また、Python には i++ がありません。たとえば、i += 1 を使用します。

while ループの場合:

count = 0
while count < number_of_tries:
    x=raw_input("some input prompt: ") # note raw_input
    if len(x) < 5:
        print("error message")
        count += 1    #increase counter ### Note the different incrementor
    elif len(x) >= 5:
       break

if count >= number_of_tries:
    # improper login
else:
    # proper login

または for ループを使用:

for count in range(number_of_tries):
    x=raw_input("some input prompt: ")  # note raw_input
    if len(x) < 5:
        print("error message") # Notice the for loop will
    elif len(x) >= 5:          # increment your count variable *for* you ;)
       break

if count >= number_of_tries-1: # Note the -1, for loops create 
    # improper login           # a number range out of range(n)from 0,n-1
else:
    # proper login
于 2013-10-18T22:38:52.120 に答える
0

whileの代わりにループが必要ifなため、適切な回数だけ別の入力を要求し続けることができます。

x = input("some input prompt: ")
count = 1
while len(x) < 5 and count < 3:
    print("error message")
    x = input("prompt again: ")
    count += 1 # increase counter

# check if we have an invalid value even after asking repeatedly
if len(x) < 5:
    print("Final error message")
    raise RunTimeError() # or raise ValueError(), or return a sentinel value

# do other stuff with x
于 2013-10-18T22:43:47.977 に答える