Reputation: 75
So I am trying to learn python at the moment. I'm a beginner programmer with only experience in limited web design and CMS administration.
I decided to create a simple little program that asked the user for the car number of a NASCAR team. Each team had a set of variables associated with it. So far, I did #1 and #2 and wanted to test the action of the code before completing the rest.
I ran into a problem where I believe I must be thinking about it wrong or maybe I am missing the knowledge because I just started learning to code in language.
Basically, it asks them for a car number and when they put it in, it display "driver(car number)" so if I input "2", it displays "driver2". But I want it to call the other variable driver2 instead which would display "Brad Keselowski" if correctly done.
Here's my code:
# 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)
Can anyone lead me in the right direction?
Upvotes: 2
Views: 1961
Reputation: 11173
Try something like this:
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)
Upvotes: 1
Reputation: 56654
Edits:
.
# 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()
Upvotes: 1
Reputation: 6434
To have the code working with the least changes, after changing input
into raw_input
twice, you can use this instead of print(driver + inputnumber)
:
print(vars()[driver + inputnumber])
However, that's a rather bad way to do it: vars()
gives you a dict of variables, so you should create a dict yourself, with the keys being the car numbers.
You can model each car/driver as one dictionary as follows:
# 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
Soon, you'll realize that the natural way to model this is creating a class to represent a driver (and maybe other one to represent a car).
Upvotes: 0
Reputation: 77117
You're not taking advantage of essential data structures. Whenever you want to map one value to another, you probably want a dictionary. Whenever you have a sequential list of items, you want a list.
>>> # 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
By the way: Using input
is dangerous, as whatever the user types is evaluated as python. Consider using raw_input
, and then manually cast the input into an integer.
Upvotes: 3