編集:
- コメントを追加
- Python 3を使用しているため、raw_input()をinput()に変更しました
。
# I create a class (a structure that stores data along with functions that
# operate on the data) to store information about each driver:
class Driver(object):
def __init__(self, number, name, make, sponsor):
self.number = number
self.name = name
self.make = make
self.sponsor = sponsor
# Then I make a bunch of drivers, and store them in a list:
drivers = [
Driver(1, "Jamie McMurray", "Chevrolet", "Bass Pro Shops/Allstate"),
Driver(2, "Brad Keselowski", "Dodge", "Miller Lite")
]
# Then I use a comprehension (x for d in drivers) - it's kind of
# like a single-line for statement - to look at my list of drivers
# and create a dictionary so I can quickly look them up by driver number.
# It's a shorter way of writing:
# number_index = {} # an empty dictionary
# for d in drivers:
# number_index[d.number] = d
number_index = {d.number:d for d in drivers}
# Now I make a "main" function - this is a naming convention for
# "here's what I want this program to do" (the preceding stuff is
# just set-up):
def main():
# show the welcome message
print("\t\t\tWelcome to NASCAR Numbers!")
print("\t\t Match Car Numbers to the Driver Names.")
# loop forever
# (it's not actually forever - when I want to quit, I call break to leave)
while True:
# prompt for input
# get input from keyboard
# strip off leading and trailing whitespace
# save the result
inp = input("\nEnter a car number (or 'exit' to quit):").strip()
# done? leave the loop
# .lower() makes the input lowercase, so the comparison works
# even if you typed in 'Exit' or 'EXIT'
if inp.lower()=='exit':
break
try:
# try to turn the input string into a number
inp = int(inp)
except ValueError:
# int() didn't like the input string
print("That wasn't a number!")
try:
# look up a driver by number (might fail)
# then print a message about the driver
print("Car #{} is driven by {}".format(inp, number_index[inp].name))
except KeyError:
# number[inp] doesn't exist
print("I don't know any car #{}".format(inp))
# if this script is called directly by Python, run the main() function
# (if it is loaded as a module by another Python script, don't)
if __name__=="__main__":
main()