2014-06-16 77 views
0

我想在Python中使用while循環來提供一個錯誤消息,同時在用戶輸入中有一個反斜槓字符。該代碼在輸入一個分數並請求第二個輸入時提供錯誤消息。當第二個輸入的長度與原始輸入不同時,會出現問題,我不知道如何解決這個問題,因爲我對Python的瞭解有限。任何幫助表示讚賞!While循環的結構

size = getInput('Size(in): ') 
charcount = len(size) 
for i in range(0,charcount): 
if size[i] == '/': 
    while size[i] == '/': 
    getWarningReply('Please enter size as a decimal', 'OKAY') 
    size = getInput('Size(in): ') 
elif size[i] == '.': 
#Convert size input from string to list, then back to string because strings are immutable whereas lists are not 
    sizechars = list(size) 
    sizechars[i] = 'P' 
    size = "".join(sizechars) 
+0

什麼語言是這樣的? 「語言」並沒有告訴我們很多... –

+0

似乎是Python – Ajit

+1

沒有試圖苛刻或任何東西,但「FOR」,「IF」和「WHILE」的混合似乎很奇怪,我認爲邏輯無論使用給定語言的語法如何,它都是第一個問題。 我建議你回到起點並從那裏開始,重新編寫邏輯 –

回答

0

那是不是去這樣做你想要什麼,因爲如果新size的長度比原來的長,短charcount,那麼你就可以輕鬆地走出去的範圍的好方法。

我絕不是一個Python高手,而是一種更好的方式來做到這一點是包住整個事情在一個while循環,而不是內部的嵌套while循環的循環:

not_decimal = True 

while not_decimal: 
    found_slash = False 
    size = getInput('Size(in): ') 
    charcount = len(size) 

    for i in range(0, charcount): 
     if size[i] == '/': 
      print 'Please enter size as a decimal.' 
      found_slash = True 
      break 
     elif size[i] == '.': 
      #Convert size input from string to list, then back to string because strings are immutable whereas lists are not 
      sizechars = list(size) 
      sizechars[i] = 'P' 
      size = "".join(sizechars) 

    if not found_slash: 
     not_decimal = False 
+0

它的工作!萬分感謝。正如大家可以說的,我在陳述/循環結構上非常生疏。對此,我真的非常感激。如果可以的話,我會投票,但它說我需要15點聲望。 – Ryan