2016-03-27 54 views
-2

我試圖在Python中創建一個BMI計算器,但是當我運行該程序時,它說:'IndentationError:預計一個縮進塊'。它說錯誤在第7行,但是我錯了什麼?我使用Python 3.5.1如何解決預期的縮進塊錯誤?

print ('Give your weight in kg: ') 
weight_kg = float(raw_input()) 
print ('Give your length in meters: ') 
length_meters = float(raw_input()) 
bmi = weight_kg/(length_meters * length_meters) 
if bmi <= 18.5: 
print ('Your BMI is'), bmi, ('what means that you have got underweight') 
elif bmi > 18.5 and bmi <= 25: 
print ('Your BMI is'), bmi, ('what means that you have got a normal weight') 
elif bmi > 25 and bmi < 30: 
print ('Your BMI is'), bmi, 'what means that you have got overweight') 
elif bmi >= 30: 
print ('Your BMI is'), bmi, ('what means that you have got obese') 
+1

打開任何塊後給出4個空格來縮進該塊,嘗試它。 – bhansa

+3

通過修復縮進塊來修復縮進塊錯誤。 Python依靠縮進來描述哪些代碼在哪個塊中。如果你在'if'中有一個'if'而沒有縮進,並且說'elif',那麼Python怎麼知道'elif'是用來幹什麼的呢? Python如何知道第二個「if」是在第一個「if」之內還是之外?縮進明確表示你的意思。 – zondo

+3

一個基本的教程可能會讓你感到痛苦。 [官方教程](https://docs.python.org/3.5/tutorial/introduction.html#first-steps-towards-programming)對縮進有這樣的說法:「縮進是Python對語句進行分組的方式。 ..]請注意,基本塊內的每一行必須縮進相同的數量。「 – syntonym

回答

1

在Python,下屬陳述是指縮進級別進行標識,而相比之下,花括號或開始/其他一些語言使用的一端關鍵字。因此,Python中的適當縮進不僅僅是風格慣例,而且事實上正確的功能也是必需的。在你的情況下,你需要縮進你的從屬陳述。請嘗試以下操作:

print ('Give your weight in kg: ') 
weight_kg = float(input()) 
print ('Give your length in meters: ') 
length_meters = float(input()) 
bmi = weight_kg/(length_meters * length_meters) 
if bmi <= 18.5: 
    print ('Your BMI is', bmi, 'what means that you have got underweight') 
elif bmi > 18.5 and bmi <= 25: 
    print ('Your BMI is', bmi, 'what means that you have got a normal weight') 
elif bmi > 25 and bmi < 30: 
    print ('Your BMI is', bmi, 'what means that you have got overweight') 
elif bmi >= 30: 
    print ('Your BMI is', bmi, 'what means that you have got obese') 
+0

您對他的字符串進行編輯會導致語法錯誤。 – zondo

+0

謝謝你回答我的問題,但現在我又遇到了另外一個問題:程序可以運行,但它說它不知道float(raw_input())是什麼意思。我更改了int中的float,但這也不起作用。 –

+0

@zondo謝謝,我沒有真正嘗試加載它。原始字符串中有''...你'...',這會導致語法錯誤。我現在看到這個帖子已經被改爲使用''...你有...'',所以我修改了我的答案。 –