在python中作为命令行参数传递的数字不解释为整数 [英] Numbers passed as command line arguments in python not interpreted as integers
问题描述
我熟悉C,并且已经开始在python中进行实验.我的问题是关于sys.argv
命令的.我已经读过它用于命令行解释器,但是当尝试执行一个简单的程序时,我没有得到我期望的结果.
I am familiar with C, and have started experimenting in python. My question is regarding the sys.argv
command. I've read it is used for a command line interpreter, but when trying to execute a simple program I don't get the results I expect.
代码:
import sys
a = sys.argv[1]
b = sys.argv[2]
print a, b
print a+b
输入:
python mySum.py 100 200
输出:
100 200
100200
当我添加两个参数时,它们是串联在一起的,而不是将两个值相加在一起.看来这些值被当作字符串了.
When I add the two arguments they are concatenated instead of the two values being added together. It seems that the values are being taken as strings.
如何将它们解释为数字?
How can I interpret them as numerics?
推荐答案
您可以使用int()将参数转换为整数
You can convert the arguments to integers using int()
import sys
a = int(sys.argv[1]) b = int(sys.argv[2])
print a, b
print a+b
输入:python mySum.py 100 200
输出:
100 200
300
这篇关于在python中作为命令行参数传递的数字不解释为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!