简体   繁体   中英

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?

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 .

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.

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

And to be sure the user enters the needed value (ig "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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM