Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does raw_input create an infinite loop in this Learn Python the Hard Way exercise variant?

I'm trying to work my way through Learn Python the Hard Way, and trying to mess around where I can to further my education. I thought this would work: set up raw_input to set a limit for a while loop, then let the while loop execute to the limit I establish with the variable "frequency".

It, uh, doesn't. Instead, it sends Python into an infinite loop of creating number lists, each seeming to be one increment longer than the last (very long) list.

The original code had "while i < 6" -- I've added the raw_input variable, and even if I enter the same variable as in the original code (6), it does this infinite-loop thing.

Here's the full script:

i = 0 
numbers = []

print "What is the frequency?"
frequency = raw_input ('Kenneth? ')

while i < frequency:
    print "At the top i is %d" % i
    numbers.append(i)
    i = i + 1
    print "Numbers now: ", numbers
    print "At the bottom i is %d" % i

print "The numbers: "

for num in numbers: 
    print num

Apologies for maximum ignorance -- I've got a copy of Python for Software Design in front of me in paperback right now, and it's the next thing on my to-do list after LPTHW.

like image 951
JeanSibelius Avatar asked Dec 30 '11 22:12

JeanSibelius


3 Answers

raw_input will give you a string object, not an integer. Try to make frequency = int(frequency) before the loop, it will make the comparison valuable.

like image 65
Cédric Julien Avatar answered Nov 16 '22 22:11

Cédric Julien


>>> 3 < '2'
0: True

That's your hint.

like image 28
nmichaels Avatar answered Nov 16 '22 22:11

nmichaels


Because raw_input results in a string.

>>> frequency = "10"
>>> i = 0
>>> while i < frequency:
...     i = i + 1
...     print i
...     if i > 20: break
... 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
like image 1
kojiro Avatar answered Nov 16 '22 22:11

kojiro