2

所以我现在正在尝试学习python。我是一个初学者程序员,只有有限的网页设计和 CMS 管理经验。

我决定创建一个简单的小程序,询问用户一个 NASCAR 团队的车号。每个团队都有一组与之相关的变量。到目前为止,我做了 #1 和 #2 并想在完成其余部分之前测试代码的操作。

我遇到了一个问题,我认为我一定是想错了,或者我错过了知识,因为我刚刚开始学习用语言编写代码。

基本上,它要求他们输入车号,当他们输入时,它会显示“司机(车号)”,所以如果我输入“2”,它会显示“司机2”。但我希望它调用另一个变量 driver2,如果正确完成,它将显示“Brad Keselowski”。

这是我的代码:

# NASCAR Numbers
# Display Driver Information Based on your Car Number Input

print("\t\t\tWelcome to NASCAR Numbers!")
print("\t\t Match Car Numbers to the Driver Names.")
input("\nPress the Enter Key to Play")

# 1 - Jamie McMurray
carnumber1 = ("1")
driver1 = ("Jamie McMurray")
make1 = ("Chevrolet")
sponsor1 = ("Bass Pro Shops/Allstate")
# 2 - Brad Keselowski
carnumber2 = ("2")
driver2 = ("Brad Keselowski")
make2 = ("Dodge")
sponsor2 = ("Miller Lite")

inputnumber = input("\nWhat car number do you want to lookup?\n\nCar Number:\t#")
driver = "driver"
print(driver + inputnumber)

谁能带领我朝着正确的方向前进?

4

4 回答 4

3

您没有利用必要的数据结构。每当您想将一个值映射到另一个值时,您可能需要一个字典。每当您有一个连续的项目列表时,您都需要一个列表。

>>> # NASCAR Numbers
... # Display Driver Information Based on your Car Number Input
... 
>>> print("\t\t\tWelcome to NASCAR Numbers!")
            Welcome to NASCAR Numbers!
>>> print("\t\t Match Car Numbers to the Driver Names.")
         Match Car Numbers to the Driver Names.
>>> cars = [] # Use a list to store the car information.
>>> cars.append({'driver': 'Jamie McMurray', 'make': 'Chevrolet', 'sponsor': 'Bass Pro Shops/Allstate'}) # Each individual car detail should be in a dictionary for easy lookup.
>>> cars.append({'driver': 'Brad Keselowski', 'make': 'Dodge', 'sponsor': 'Miller Lite'})
>>> inputnumber = input("\nWhat car number do you want to lookup?\n\nCar Number:\t#")

What car number do you want to lookup?

Car Number: #2
>>> driver = cars[inputnumber-1]['driver'] # Python lists start at zero, so subtract one from input.
>>> print("driver" + str(inputnumber))
driver2
>>> print(driver)
Brad Keselowski

顺便说一句:使用input是危险的,因为无论用户类型如何被评估为 python。考虑使用raw_input,然后手动将输入转换为整数。

于 2012-05-30T21:09:43.833 回答
1

尝试这样的事情:

from collections import namedtuple

Car = namedtuple('Car', 'driver make sponsor')


cars = [
        Car('Jim', 'Ford', 'Bass Pro Shops'),
        Car('Brad', 'Dodge', 'Miller Lite'),
        ]


inputnumber = input("\nWhat car number do you want to lookup?\n\nCar Number:\t#")
print(cars[int(inputnumber) - 1].driver)
于 2012-05-30T21:13:17.473 回答
1

编辑:

  1. 添加评论
  2. 将 raw_input() 更改为 input() 因为他使用的是 Python 3

.

# 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()
于 2012-05-30T22:25:43.817 回答
0

input要使代码以最少的更改工作,在更改raw_input两次后,您可以使用它来代替print(driver + inputnumber)

 print(vars()[driver + inputnumber])

然而,这是一个相当糟糕的方法:vars()给你一个变量的字典,所以你应该自己创建一个字典,键是车号。

您可以将每辆汽车/驾驶员建模为一个字典,如下所示:

# A dictionary to hold drivers
drivers = {}

# 1 - Jamie McMurray
jamie = {} # each driver modelled as a dictionary
jamie["carnumber"] = "1"
jamie["name"] = "Jamie McMurray"
jamie["make"] = "Chevrolet"
jamie["sponsor"] = "Bass Pro Shops/Allstate"

drivers[1] = jamie

# 2 - Brad Keselowski
brad = {}
brad["carnumber"] = "2"
brad["name"] = "Brad Keselowski"
brad["make"] = "Dodge"
brad["sponsor"] = "Miller Lite"

drivers[2] = brad

inputnumber = raw_input("\nWhat car number do you want to lookup?\n\nCar Number:\t#")

inputnumber = int(inputnumber) # Convert the string in inputnumber to an int

driver = drivers[inputnumber] # Fetch the corresponding driver from drivers

print(driver) # Print information, you can use a template to make it pretty

很快,您就会意识到对其进行建模的自然方法是创建一个类来表示司机(可能还有其他类来表示汽车)。

于 2012-05-30T21:13:16.873 回答