【问题标题】:How to assign a value to a specific variable from the user input如何从用户输入中为特定变量赋值
【发布时间】:2019-08-14 10:18:36
【问题描述】:

当控制台要求用户输入时,如何为特定变量赋值?我想要一些可以在控制台中输入的东西 time_h = 5 并直接从控制台将值 5 分配给现有变量 time_h。我不想只是简单地写一些像 time_h = input() 并在控制台弹出时输入一个数字。

【问题讨论】:

  • 考虑使用sys 模块,该模块可让您使用sys.argv 处理命令行参数。
  • @balkon16 你能举个例子吗,我对编写代码和Python真的很陌生

标签: variables user-input assign


【解决方案1】:

正如我在评论中指出的那样,您可以使用sys 模块来处理脚本调用提供的命令行参数。让我们考虑以下名为 example_sys.py 的脚本:

import sys

print("The name of the script that you have called is {}".format(sys.argv[0]))
time_h = int(sys.argv[1])
print("The value of the time_h variable is {}".format(time_h))

假设您已经使用控制台将cded 放入包含example_script.py 的目录中,您可以使用以空格分隔的命令行参数调用它:

python example_sys.py 5

根据分配给python 命令的 Python 版本,您可能需要使用python3 而不是python

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-24
    • 2021-10-10
    • 2014-06-27
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    相关资源
    最近更新 更多