2012-01-05 88 views
0

我在做一個遊戲,在「計算機」試圖猜測一個數字,你想到的。 這裏的代碼一對夫婦片段:有什麼辦法可以在random.randint中使用raw_input變量嗎?

askNumber1 = str(raw_input('What range of numbers do you want? Name the minimum number here.')) 
askNumber2 = str(raw_input('Name the max number you want here.')) 

這是得到他們想要的計算機使用的數字範圍。

print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?' 

這是計算機詢問是否得到了數字,使用random.randint生成一個隨機數。問題是1)它不會讓我組合字符串和整數,2)不會讓我使用變量作爲最小值和最大值。

有什麼建議嗎?

+0

你打算簡單地呈現隨機數,直到它猜對了嗎? – 2012-01-05 03:25:33

回答

1

這將是更好,如果你創建了該範圍內的號碼列表並將其隨機排序,然後保持坡平,直到你猜否則有小的可能性,一些可能會問第二次。

不過這裏是你想做的事:

askNumber1 = int(str(raw_input('What range of numbers do you want? Name the minimum number here.'))) 
askNumber2 = int(str(raw_input('Name the max number you want here.'))) 

你將它保存爲一個號碼,而不是作爲一個字符串。

+0

它的工作原理,非常感謝你<3 – asqapro 2012-01-05 03:26:40

+0

請記得按刻度,如果這個解決您的問題。 – 2012-01-05 03:31:38

1

如你所說,randint需要整數參數,而不是字符串。由於raw_input已經返回一個字符串,因此不需要使用str()進行轉換;相反,您可以使用int()將其轉換爲整數。但是,請注意,如果用戶輸入的內容不是整數,例如「hello」,則會拋出異常並退出程序。如果發生這種情況,您可能需要再次提示用戶。下面是直到用戶輸入一個整數,調用raw_input反覆的函數,然後返回一個整數:

def int_raw_input(prompt): 
    while True: 
     try: 
      # if the call to int() raises an 
      # exception, this won't return here 
      return int(raw_input(prompt)) 
     except ValueError: 
      # simply ignore the error and retry 
      # the loop body (i.e. prompt again) 
      pass 

然後,您可以替代這次您的來電來raw_input

0

範圍內的數均存儲爲字符串。試試這個:

askNumber1 =int(raw_input('What range of numbers do you want? Name the minimum number here.')) 
askNumber2 =int(raw_input('Name the max number you want here.')) 

這就是他們希望計算機使用的數字範圍。

print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?' 
相關問題