I'm trying out Python, and, in my very tired state, can't seem to find the problem with the code below:
import sys
def printNum(x):
y = 0
while y < x:
print "Number: ", y
y = y + 1
printNum(sys.argv[1])
So, I'm trying to get it to print out y
x
times. x
is passed as a parameter. The loop never ends开发者_开发知识库 and I don't know why!
Ouch!
Your problem is that sys.argv[1]
gives you a str
, and a str
is always greater than an int
.
For example:
>>> '2' < 1
False
>>> '1' < 2
False
So what you'll need to do is change your last line to
printNum(int(sys.argv[1]))
Currently this code will paste a str
into printNum
, but printNum
treats the input (x
) like an int
. To fix this, convert the input to an int
:
printNum(int(sys.argv[1]))
The x
value that you get as a command line parameter is passed in as a string, not as an integer. All integers are treated as being less than all strings:
>>> 1 < "2"
True
>>> 3 < "2"
True
>>> 1000000 < "2"
True
...so your loop will never end.
try:
printNum(int(sys.argv[1]))
精彩评论