測試題
1. 輸出將是:
Under 20
因為 my_number
小於 20,if
語句中的測試為 true
,所以會執行 if
後面的塊(這裡只有一行代碼)。
2. 輸出將是:
20 or over
因為 my_number
大於 20,if
語句中的測試為 false
,所以 if
後面的塊代碼不會執行。相反,會執行 else
塊中的代碼。
3. 要查看一個數是否大於 30 但小於或等於 40,可以使用下面的代碼:
if number > 30 and number <= 40: print 'The number is between 30 and 40'
你還可以這樣做:
if 30 < number <= 40: print "The number is between 30 and 40"
4. 要檢查字母「Q」是大寫還是小寫,可以這樣做:
if answer == 'Q' or answer == 'q': print "you typed a 'Q' "
注意,我們打印的字符串使用了雙引號,不過其中的「Q」兩邊是單引號。如果想知道如何打印引號,可以用另一種引號包圍字符串。
動手試一試
1. 下面給出一個答案:
# program to calculate store discount# 10% off for $10 or less, 20% off for more than $10item_price = float(raw_input ('enter the price of the item: '))if item_price <= 10.0: discount = item_price * 0.10else: discount = item_price * 0.20final_price = item_price - discountprint 'You got ', discount, 'off, so your final price was', final_price
這裡沒有考慮把答案四捨五入為兩位小數(美分),也沒有顯示美元符。
2. 以下給出一種做法:
# program to check age and gender of soccer players# accept girls who are 10 to 12 years oldgender = raw_input("Are you male or female? ('m' or 'f') ")if gender == 'f': age = int(raw_input('What is your age? ')) if age >= 10 and age <= 12:print 'You can play on the team' else:print 'You are not the right age.'else: print 'Only girls are allowed on this team.'
3. 以下給出一個答案:
# program to check if you need gas.# Next station is 200 km awaytank_size = int(raw_input('How big is your tank (liters)? '))full = int(raw_input ('How full is your tank (eg. 50 for half full)?'))mileage = int(raw_input ('What is your gas mileage (km per liter)? '))range = tank_size * (full / 100.0) * mileageprint 'You can go another', range, 'km.'print 'The next gas station is 200km away.'if range <= 200: print 'GET GAS NOW!'else: print 'You can wait for the next station.'
要增加一個 5 公升的緩衝區,需要把這行代碼:
range = tank_size * (full / 100.0) * mileage
改為:
range = (tank_size - 5) * (full / 100.0) * mileage
4. 下面是一個簡單的口令程序:
password = "bigsecret"guess = raw_input("Enter your password: ")if guess == password: print "Password correct. Welcome" # put the rest of the code for your program hereelse: print "Password incorrect. Goodbye"