I am using Python 2.7 in Windows PowerShell.
def loop(loop):
i = 0
numbers = []
while i < loop:
print "At the top i is %d" % i
numbers.append(i)
i += 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
value = raw_input("Choose the loop value:\n>")
print value
loop(value)
When I enter 6
as the input for value
, loop()
turns into an infinite loop.
Any idea what is going wrong?
The result of your raw_input
, the variable value
(passed to loop
in your function) is a string. You are comparing this to i
, an integer. In Python 2.x, all integers are less than all strings, so i < loop
is always true no matter how big i
gets.
Convert your input to an integer to make the comparison work:
value = int(raw_input("Choose the loop value:\n>"))
(And I'd also suggest not naming your function's argument the same as the function itself; it's just confusing.)
You have to put your raw_input
in int()
.
replace:
value = raw_input("Choose the loop value:\n>")
on:
value = int(raw_input("Choose the loop value:\n>"))
OR you can just change:
while i < loop:
to
while i < int(loop):
我确定您实际上正在运行loop('6')而不是loop(6)。
because value is a string
you should call your function like this
loop(int(value))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.