讀古今文學網 > 父與子的編程之旅:與小卡特一起學Python > 第6章 >

第6章

測試題

1. 要用 EasyGui 顯示一個消息框,可以使用 msgbox,如下:

easygui.msgbox("This is the answer!")  

2. 要用 EasyGui 得到一個字符串輸入,要使用 enterbox

3. 要得到整數輸入,可以使用 enterbox(這會由用戶得到一個字符串),然後把它轉換為 int。或者也可以直接使用 integerbox

4. 要從用戶那裡得到浮點數,可以使用一個 enterbox(這會提供一個字符串),然後使用 float 函數把這個字符串轉換成一個浮點數。

5. 默認值就像「自動獲得的答案」。以下是一種可能使用默認值的情況:你在編寫程序,你班裡的所有學生都必須輸入他們的名字和地址,你可以把你居住的城市名作為地址中的默認城市。這樣一來,學生們就不用再鍵入城市了(除非他們居住在其他城市)。

動手試一試

1. 以下是一個使用 EasyGui 的溫度轉換程序:

# tempgui1.py# EasyGui version of temperature-conversion program# converts Fahrenheit to Celsiusimport easyguieasygui.msgbox('This program converts Fahrenheit to Celsius')temperature = easygui.enterbox('Type in a temperature in Fahrenheit:')Fahr = float(temperature)Cel = (Fahr - 32) * 5.0 / 9easygui.msgbox('That is ' + str(Cel) + ' degrees Celsius.')  

2. 下面這個程序會詢問你的名字以及地址的各個部分,然後顯示完整的地址。要理解這個程序,如果瞭解如何強制換行會很有幫助:換行會讓後面的文本從新的一行開始。為達到這個目的,需要使用 \n。這會在第 21 章解釋,不過下面先提前瞭解一下:

# address.py# Enter parts of your address and display the whole thingimport easyguiname = easygui.enterbox("What is your name?")addr = easygui.enterbox("What is your street address?")city = easygui.enterbox("What is your city?")state = easygui.enterbox("What is your state or province?")code = easygui.enterbox("What is your postal code or zip code?")whole_addr = name + "\n" + addr + "\n" + city + ", " + state + "\n" + codeeasygui.msgbox(whole_addr, "Here is your address:")