jsyemty
jsyemty

Reputation: 21

Why does this give me infinite loop?

I was trying to code a simple program:

import random

x = raw_input("How many rounds:")
rounds = 0

while rounds < x:
    # rock=0, paper=1, scissors=2
    computer1 = random.randint(0,2)
    computer2 = random.randint(0,2)

    if computer1 == computer2:
        print "draw"
    elif computer1 == 0 and computer2 == 1:
        print "lose"
    elif computer1 == 1 and computer2 == 2:
        print "lose"
    elif computer1 == 2 and computer2 == 0:
        print "lose"
    else:
        print "win"
    rounds = rounds + 1

Why does this give me an infinite loop? When I take out the input line and replace x with a certain value, say, 10, the output does give me 10 results. But why can't I do it with that raw_input?

Upvotes: 1

Views: 129

Answers (4)

Elisha
Elisha

Reputation: 4951

raw_input returns a string, you need to cast it to int

x = int(raw_input("How many rounds:"))

Note that in python:

>>> 159 < "8"
True
>>> 159 < 8
False
>>> 

To better understand the int-string comparison, you can look here.

Upvotes: 10

Alexey Gorozhanov
Alexey Gorozhanov

Reputation: 706

And to be sure the user enters the needed value (i.g. "qwerty" or 2.6) you can add exception handling:

import random
try:
    x = input("How many rounds: ")
    rounds = 0
    while rounds < int(x):
        # rock=0, paper=1, scissors=2
        computer1 = random.randint(0,2)
        computer2 = random.randint(0,2)

        if computer1 == computer2:
            print ("draw")
        elif computer1 == 0 and computer2 == 1:
            print ("lose")
        elif computer1 == 1 and computer2 == 2:
            print ("lose")
        elif computer1 == 2 and computer2 == 0:
            print ("lose")
        else:
            print ("win")
        rounds = rounds + 1
except (ValueError):
    print('Wrong input')

This code is Python 3.

Upvotes: 0

Rob Fagen
Rob Fagen

Reputation: 884

Change your input line to:

x = int(raw_input("How many rounds:"))

and you should be good to go. As pointed out in the comments, the default raw_input is a string, and comparing an integer to a string won't give you what you want.

Upvotes: 4

ZdaR
ZdaR

Reputation: 22954

Since raw_input() always returns a str So for homogeneous comparison, You need to change the type of x to int

import random

x = int(raw_input("How many rounds:"))

rounds = 0

Upvotes: 3

Related Questions