在Python中为用户输入分配值

时间:2015-10-24 15:15:13

标签: python variables

我想根据用户输入分配一个数值。

现在我希望用户输入第二名的驱动程序。键入的任何驱动程序名称将被分配2个点以完成第二个。除了获得3分之外,与第一名相同。

程序运行前,所有可能的驱动程序名称都设置为0。这些是用户可以输入的可能名称。

我不确定我是否会在Python中执行此操作,我们将不胜感激。

Matt_Kenseth = 0
Kyle_Busch = 0
Joey_Logano = 0
Aric_Armirola = 0
Dale_Earnhardt_Jr = 0
Denny_Hamlin = 0
Jeff_Gordon = 0
Brad_Keselowski = 0
Jimmie_Johnson = 0
Clint_Bowyer = 0
Carl_Edwards = 0
Kyle_Larson = 0
Jamie_McMurray = 0
Kevin_Harvick = 0
Kurt_Busch = 0
Ricky_Stenhouse_Jr = 0
David_Ragan = 0
Kasey_Kahne = 0
Danica_Patrick = 0
Ryan_Newman = 0
Casey_Mears = 0
Brian_Scott = 0
Trevor_Bayne = 0
AJ_Allmendinger = 0
Justin_Allgaier = 0
Paul_Menard = 0
Austin_Dillon = 0
Sam_Hornish_Jr = 0
Tony_Stewart = 0
Landon_Cassill = 0
Greg_Biffle = 0
Martin_Truex_Jr = 0
David_Gilliland = 0
JJ_Yeley = 0
Brett_Moffitt = 0
Matt_DiBenedetto = 0
Alex_Bowman = 0
Cole_Whitt = 0
Jeb_Burton = 0
Jeffrey_Earnhardt = 0
Reed_Sorenson = 0
Michael_McDowell = 0
Michael_Annett = 0

int ( input ( "Enter 1st Place Driver In Race.\nThis driver will receive 20 points. " ) )

int ( input ( "Enter 2nd Place Driver In Race.\nThis driver will receive 10 points. " ) )

int ( input ( "Enter 3rd Place Driver In Race.\n This driver will receive 5 points. " ) ) 

我对编程非常陌生,如果我没有多大意义,那就很抱歉。如果用户键入上面列出的其中一个驱动程序,例如第一个位置,那么我希望该驱动程序从0到20(第一个位置的值完成)。

1 个答案:

答案 0 :(得分:0)

为什么不将所有这些驱动程序放在一个字典中,并将所有值设置为0?像这样:

All_Drivers = {"Justin_Allgaier": "0", "Jeb_Burton" : "0"}

如果您想根据用户输入更改分配给它的驱动程序值,这里有一个非常简单的示例:

#Assigning driver names in a dictionary
All_Drivers = {"Justin_Allgaier": "0", "Jeb_Burton" : "0"}

#We're attributing a variable to the user input here
first_place_driver_name = input("Enter 1st place driver\n>")

#Here the for loop is itterating through all the keys in the dictionary and assigning all the keys to the "keys" variable, we can also assign all the values by passing an extra variable
for keys in All_drivers:
    #Now we're using an If statement to check if the name passed by the user matches a key in the dictionnary, if it does, it assigns the value 20 to the correct key.
    if first_place_driver_name == keys:
        All_Drivers[keys] = 20
#Now we're printing all the keys and values in the dictionary.
print(All_Drivers)

在这个例子中,第一个驱动程序收到了20个点,用你的驱动程序名称试试这个,它应该可以工作。如果您需要有关For循环,If语句和词典的更多信息,请查看Python文档或在stackoverflow上搜索。要在字典中打印出特定的键值,您需要指定特定的键,如All_Drivers["Justin_Allgaier"]。您可能还想限制用户可以输入的内容,但我希望此解决方案可以帮助您。