所以我现在正在尝试学习python。我是初学程序员,只有有限的网页设计和CMS管理经验。
我决定创建一个简单的小程序,询问用户NASCAR团队的车号。每个团队都有一组与之相关的变量。到目前为止,我做了#1和#2,并希望在完成剩下的工作之前测试代码的操作。
我遇到了一个问题,我认为我必须考虑错误,或者我错过了知识,因为我刚开始学习用语言编写代码。
基本上,它要求他们提供车号,当他们把它放入时,它会显示“司机(车号)”,所以如果输入“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)
有人能引导我朝正确的方向前进吗?
答案 0 :(得分: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
,然后手动将输入转换为整数。
答案 1 :(得分: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)
答案 2 :(得分:1)
编辑:
# 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()
答案 3 :(得分: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
很快,您会发现建模的自然方式是创建一个代表驾驶员的类(也许是代表汽车的其他人)。