为什么这给了我无限循环?

时间:2015-05-28 15:19:57

标签: python infinite-loop

我试图编写一个简单的程序:

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

为什么这会给我一个无限循环?当我取出输入行并将x替换为某个值(例如10)时,输出会给出10个结果。但为什么我不能用raw_input做到这一点?

4 个答案:

答案 0 :(得分:10)

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

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

请注意,在python中:

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

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

答案 1 :(得分:4)

将输入行更改为:

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

你应该好好去。正如评论中指出的那样,the default raw_input is a string并将整数与字符串进行比较不会给你你想要的东西。

答案 2 :(得分:3)

由于raw_input()始终返回str因此,为了进行同质比较,您需要将x的类型更改为int

import random

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

rounds = 0

答案 3 :(得分:0)

为了确保用户输入所需的值(例如,#34; qwerty&#34;或2.6),您可以添加异常处理:

$user = User::find(101);

foreach($user->notifications as $notifications)
{
    if ($notification->pivot->is_read === false)
    {
        // Notification is unread, lets do something
    }
}

此代码是Python 3。