【问题标题】:Assign A Value To User Input In Python在 Python 中为用户输入赋值
【发布时间】:2016-01-24 00:22:04
【问题描述】:

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

现在我希望用户输入第二位驱动程序。输入的任何车手姓名都将获得 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(第一名完成的值)。

【问题讨论】:

  • 如何将驱动程序名称设置为 0?请用简单的英语说明您要做什么。就问题而言,它非常模糊。
  • 先向我们展示您的尝试。
  • 您的 input 和 int 调用是向后的,但是如果您运行了您输入的内容,您会很快知道

标签: python variables


【解决方案1】:

为什么不将所有这些驱动程序放在一个字典中,所有值都设置为 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"] 一样指定特定键。您可能还想限制用户可以输入的内容,但我希望这个解决方案可以帮助您。

【讨论】:

  • 我运行程序并选择了 Justin_Allgaier,但它从未添加 20,它保持为 0。
  • 非常抱歉,我在脚本中添加了更正,我们不应该遍历 first_place_driver_name,它是不可迭代的。字符串是不可迭代的,并且无论如何都不应该迭代单个字符串。只是想给你演示一下如何使用 For 循环,有点忘乎所以。
猜你喜欢
  • 1970-01-01
  • 2020-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-06
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
相关资源
最近更新 更多