2012-05-30 76 views
2

因此,我正在嘗試學習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) 

任何人都可以引導我正確的方向?

回答

1

編輯:

  1. 添加的註釋
  2. 更改的raw_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() 
+0

這是非常優秀的代碼,但它可以使用一些上下文來進行「僅限於有限的網頁設計和CMS管理經驗的初學者程序員」。 – TryPyPy

+1

@TryPyPy:好點,增加了豐富的評論。 –

+0

感謝你們倆。我會研究這段代碼,並想告訴你我非常感謝你的時間。 – Steven

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是危險的,因爲無論用戶類型作爲蟒蛇評估。考慮使用raw_input,然後手動將輸入轉換爲整數。

+1

「'input'是危險的」,除非他使用Python 3 –

+0

我擔心這些選擇似乎工作。您的建議或下面的其他內容。我目前正在運行Python 3.1。 – Steven

+0

@Steven:Python 2有一對函數input()和raw_input()。 input()試圖評估輸入的內容,所以你可以直接輸入字典等東西; raw_input()只是返回一個字符串(因此「原始」,如「未評估」)。大多數人發現評估輸入是無益的 - 如果輸入不是有效的Python語法,則評估它會引發錯誤 - 因此對於Python 3,只有input()與Python 2的raw_input()運行相同。希望解釋這個問題! –

0

爲了讓代碼用最少的改變工作,改變inputraw_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 

不久之後,你就會明白,來模擬這種自然的方式是創建一個類來表示一個驅動器(也許其他一個代表一輛汽車)。

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)