基于输入+另一个变量打印变量

2024-05-15 02:58:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

基本上,它要求他们输入一个车号,当他们输入时,它会显示“driver(car number)”,所以如果我输入“2”,它就会显示“driver2”。但我希望它调用另一个变量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)

谁能把我引向正确的方向吗?在


Tags: to代码numberdrivercarprintnumbersbrad
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)

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

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

编辑:

  1. 添加了注释
  2. 因为使用的是python3,所以将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()

相关问题 更多 >

    热门问题