Gio Plenzik
Gio Plenzik

Reputation: 56

Why does my code run into an infinite loop?

import sys
keyword = raw_input("enter a keyword ").lower()
key_phrase = raw_input("enter a key phrase").lower()
key_phrase_length = len(key_phrase)

character_position = []
for character in keyword:
    if character in "abcdefghijklmnopqrstuvwxyz":
        position = "abcdefghijklmnopqrstuvwxyz".find(character) + 1
        character_position.append(position)


cycle = -1
new_keyword = ""
if len(keyword) < len(key_phrase):
    while len(keyword) < len(key_phrase):

        cycle += 1
        if cycle >= len(keyword):
                cycle = 0
        new_keyword = new_keyword + keyword[cycle]
        sys.stdout.write(new_keyword[cycle])

above is my code, when entering a keyword such as "cat", and a key phrase such as "computing", the code should print the letters of the "cat" to the length of the word computing. however this runs into a loop

Upvotes: 2

Views: 49

Answers (2)

Prisoner
Prisoner

Reputation: 50701

In short, in this loop:

while len(keyword) < len(key_phrase)

you never update or change either keyword or key_phrase. Since they never update or change, the escape condition will never be met

Upvotes: 1

Geza Lore
Geza Lore

Reputation: 541

You have a loop while len(keyword) < len(key_phrase): whose iteration depends on keyword and key_prase, but you do not change these variables in the loop body, so once it is entered, the loop condition will always evaluate to True, so you have an infinite loop.

Upvotes: 4

Related Questions