2013-01-14 29 views
1

我是一名編程新手,我選擇Python作爲第一語言,因爲它很簡單。但我很困惑這裏的代碼:爲什麼我們在循環之前分配了變量「option」1的值?

option = 1 
while option != 0: 
    print "/n/n/n************MENU************" #Make a menu 
    print "1. Add numbers" 
    print "2. Find perimeter and area of a rectangle" 
    print "0. Forget it!" 
    print "*" * 28 

    option = input("Please make a selection: ") #Prompt user for a selection  
    if option == 1: #If option is 1, get input and calculate 
     firstnumber = input("Enter 1st number: ") 
     secondnumber = input("Enter 2nd number: ") 
     add = firstnumber + secondnumber 
     print firstnumber, "added to", secondnumber, "equals", add #show results 

    elif option == 2: #If option is 2, get input and calculate 
     length = input("Enter length: ") 
     width = input("Enter width: ") 
     perimeter = length * 2 + width * 2 
     area = length * width 
     print "The perimeter of your rectangle is", perimeter #show results  
     print "The area of your rectangle is", area 

    else: #if the input is anything else its not valid 
     print "That is not a valid option!" 

好吧好吧,我得到的東西都在Option以下。我只想知道爲什麼我們爲Option=1賦值,爲什麼我們將它添加到程序的頂部,它的功能是什麼。我們也可以改變它的價值。請讓我用簡單的語言來理解它,因爲我是編程新手。

+2

你無法理解'option = 1'行(一個簡單的變量初始化),你在說:**我把所有的東西都放在「Option」變量的下面**,那怎麼可能? –

回答

4

如果沒有創建變量option在程序的開始,行

while option != 0: 

將打破,因爲沒有option變量將還不存在。

至於如何改變其值,注意它改變每次行:

option = input("Please make a selection: ") 

happens-被重新分配它的值用戶的輸入。

+0

感謝您的回覆,但爲什麼我們將其值設爲1? – user1977722

+1

@ user1977722:您可以將其值分配給除「0」以外的任何內容,並沒有區別。如果你將它賦值爲'0','while'循環永遠不會執行(因爲'option!= 0'將是錯誤的)。試着給它賦值'2','3','100'或'「hello」',你會發現它沒有什麼區別('1'只是一個方便的值) –

+0

第一次分配的值不會只要它不是0,因爲它被'input'所覆蓋。重要的是它必須存在於'while'行之前。 –

2

因此,下面的while語句不會嘗試檢查不存在的名稱。它不是已將分配給1,它恰好是第一個非零自然數。

0

Python需要變量在可以使用之前進行聲明。

在這種情況下,決定正在取得option是否設置爲12(所以我們將它設置爲這些值之一,通常我們可以很容易地將它設置爲0或空字符串)。儘管一些語言對變量聲明的要求不那麼嚴格(PHP想起來),但大多數語言要求變量在使用前存在。

Python不需要顯式聲明變量,只需要給它們一個值來保留內存空間。 VB.NET,默認情況下,在另一方面,要求明確聲明變量...

Dim var as D 

它設置變量type但不給它一個初始值。

請參閱the Python docs

相關問題