簡體   English   中英

為什么這會給我無限循環?

[英]Why does this give me 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呢?

raw_input返回一個字符串,您需要將其raw_input轉換為int

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

請注意,在python中:

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

為了更好地理解int string比較,可以在此處查看

將輸入行更改為:

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

而且你應該很好走。 正如評論中指出的那樣, 默認的raw_input是string ,將整數與字符串進行比較不會得到所需的內容。

由於raw_input()始終返回一個str因此為了進行均勻比較,您需要將x的類型更改為int

import random

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

rounds = 0

為了確保用戶輸入所需的值(例如“ qwerty”或2.6),您可以添加異常處理:

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')

這段代碼是Python 3。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM