:
再び
def seg1len(ipaddy):
seg1 = ""
for char in ipaddy:
if char == '.': # test for equality to the break condition..
break # .. and break at the top of the for loop
seg1 += char # do the for-loop work (you don't need an else clause to the if)
else: # the else would go with the for and would be executed whenever the for loop ran without hitting break
raise ValueError("ipaddy contains no dots")
return len(seg1)
、これは不自然な例でした。あなたは(最速)の1を使用する必要があります。
IP_address = "216.3.122.18"
seg_1_len = IP_address.find('.') # returns -1 if there is no '.'
または
seg_1_len = IP_address.index('.') # raises a ValueError if there i sno '.'
または
len(ipaddy.split('.')[0])
しばらく使用したソリューションは、のような単純なものでした:
仮定
seg_1_length = 1
while IP_address[seg_1_length] != '.':
seg_1_length += 1
入力は有効なip4広告ですドレス(少なくとも'.'
を1つ含む必要があり、'.'
で始めることはできません)。
あなたが入力が有効であると仮定することができない場合は、
i = 0
while i < len(ipaddy) and ipaddy[i] != '.':
i += 1
assert i > 0, "ip address can't start with a dot"
assert i <= 3, "the first octet can't be more than 3 characters long"
seg_1_length = i
は[MCVE]教えてください - 正確に*何を意味* "動作しませんか"? 1つの明白な問題 - あなたは条件の値を変更するものが何も含まれていないwhileループを持っているので、開始も終了もしません。 – jonrsharpe
なぜwhileループを使うのですか? 'len(IP_address.split( '。')[0])'はその仕事をします。 – FabienP
質問に回答しましたか? – Adi219