测试题
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"