第 7 章

测试题

  1. 输出将是:
  1. Under 20

因为 my_number 小于 20,if 语句中的测试为 true,所以会执行 if 后面的块(这里只有一行代码)。

  1. 输出将是:
  1. 20 or over

因为 my_number 大于 20,if 语句中的测试为 false,所以 if 后面的块代码不会执行。相反,会执行 else 块中的代码。

  1. 要查看一个数是否大于 30 但小于或等于 40,可以使用下面的代码:
  1. if number > 30 and number <= 40:
  2. print 'The number is between 30 and 40'

你还可以这样做:

  1. if 30 < number <= 40:
  2. print "The number is between 30 and 40"
  1. 要检查字母“Q”是大写还是小写,可以这样做:
  1. if answer == 'Q' or answer == 'q':
  2. print "you typed a 'Q' "

注意,我们打印的字符串使用了双引号,不过其中的“Q”两边是单引号。如果想知道如何打印引号,可以用另一种引号包围字符串。

动手试一试

  1. 下面给出一个答案:
  1. # program to calculate store discount
  2. # 10% off for $10 or less, 20% off for more than $10
  3. item_price = float(raw_input ('enter the price of the item: '))
  4. if item_price <= 10.0:
  5. discount = item_price * 0.10
  6. else:
  7. discount = item_price * 0.20
  8. final_price = item_price - discount
  9. print 'You got ', discount, 'off, so your final price was', final_price

这里没有考虑把答案四舍五入为两位小数(美分),也没有显示美元符。

  1. 以下给出一种做法:
  1. # program to check age and gender of soccer players
  2. # accept girls who are 10 to 12 years old
  3. gender = raw_input("Are you male or female? ('m' or 'f') ")
  4. if gender == 'f':
  5. age = int(raw_input('What is your age? '))
  6. if age >= 10 and age <= 12:
  7. print 'You can play on the team'
  8. else:
  9. print 'You are not the right age.'
  10. else:
  11. print 'Only girls are allowed on this team.'
  1. 以下给出一个答案:
  1. # program to check if you need gas.
  2. # Next station is 200 km away
  3. tank_size = int(raw_input('How big is your tank (liters)? '))
  4. full = int(raw_input ('How full is your tank (eg. 50 for half full)?'))
  5. mileage = int(raw_input ('What is your gas mileage (km per liter)? '))
  6. range = tank_size * (full / 100.0) * mileage
  7. print 'You can go another', range, 'km.'
  8. print 'The next gas station is 200km away.'
  9. if range <= 200:
  10. print 'GET GAS NOW!'
  11. else:
  12. print 'You can wait for the next station.'

要增加一个 5 公升的缓冲区,需要把这行代码:

  1. range = tank_size * (full / 100.0) * mileage

改为:

  1. range = (tank_size - 5) * (full / 100.0) * mileage
  1. 下面是一个简单的口令程序:
  1. password = "bigsecret"
  2. guess = raw_input("Enter your password: ")
  3. if guess == password:
  4. print "Password correct. Welcome"
  5. # put the rest of the code for your program here
  6. else:
  7. print "Password incorrect. Goodbye"