【问题标题】:Printing a variable based on an input + another variable根据输入+另一个变量打印变量
【发布时间】:2012-05-30 21:02:22
【问题描述】:

所以我现在正在努力学习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)

谁能指引我正确的方向?

【问题讨论】:

    标签: python variables printing input


    【解决方案1】:

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

    >>> # 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,然后手动将输入转换为整数。

    【讨论】:

    • input 很危险”,除非他使用的是 Python 3
    • 我担心这些选项似乎都不起作用。您的建议或下面的其他建议。我目前正在运行 Python 3.1。
    • @Steven:Python 2 有一对函数,input() 和 raw_input()。 input() 尝试评估输入的任何内容,因此您可以直接输入字典之类的内容; raw_input() 只返回一个字符串(因此“原始”,如“未评估”)。大多数人发现评估输入没有帮助 - 如果输入不是有效的 Python 语法,评估它会引发错误 - 所以对于 Python 3,只有 input() 与 Python 2 的 raw_input() 操作相同。希望能解释问题!
    • 谢谢休。我会继续学习,你的解释很有帮助。
    【解决方案2】:

    编辑:

    1. 添加了 cmets
    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()
    

    【讨论】:

    • 这是非常理想的代码,但它可以为“只有有限网页设计和 CMS 管理经验的初学者程序员”使用一些上下文。
    • 谢谢你们俩。我会研究这段代码,并想告诉你,我很感激你的时间。
    【解决方案3】:

    试试这样的:

    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)
    

    【讨论】:

      【解决方案4】:

      为了让代码以最少的更改工作,在将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
      

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

      【讨论】: