Skip to main content
 首页 » 编程设计

python之为什么这会给我无限循环

2025年05月04日13myhome

我正在尝试编写一个简单的程序:

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 

为什么这会给我一个无限循环?当我取出输入行并用某个值(比如 10)替换 x 时,输出确实给了我 10 个结果。但为什么我不能用那个 raw_input 来做呢?

请您参考如下方法:

raw_input 返回一个字符串,需要将其转换为int

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

注意在 python 中:

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

为了更好地理解int-string 比较,您可以look here .