2015-05-07 86 views
-4

我正在製作一個Python代碼,它選取一個隨機數並將其與用戶做出的猜測進行比較。Python猜謎遊戲無法正常工作

import random 
attempts=0 
secret=random.randint(1,49) 
print "welcome to my guessing game" 
repeat 
def repeat(): 
    guess=raw_input("I have thought of a number between 1 and 50. you have to try and guess it") 
     if secret==guess: 
      print "Well Done! you guessed it in "+attempts+" attempts" 
     elif secret < guess: 
      print "too high" 
      guess=raw_input("have another go") 
     elif secret > guess: 
      print "too low" 
      guess=raw_input("have another go") 
    attempts += 1 
while guess != secret and attempts>6: 
    repeat() 

但它是說重複沒有定義。

+0

「重複」應該做什麼?請注意:1.在**實際定義函數之前出現**; 2.無論如何不會做任何有用的事情。 – jonrsharpe

+0

請求幫助時,請包含確切的錯誤消息。你在調用沒有括號的函數定義。作爲一個附註,你底部的狀況很可能是錯誤的。你可能的意思是'while guess!= secret並且嘗試<6:' – Carcigenicate

+0

刪除第五行並帶有'repeat'。 –

回答

1

這將允許用戶猜7次,然後打印遊戲結束: 這就是Python 2. Python 3的使用int(input(""))

import random 

secret = random.randint(1,49) 
attempts = 0 
for attempts in range(7): 
    guess=input("I have thought of a number between 1 and 50. you have to try and guess it: ") 
    if secret==guess: 
     print "Well Done! you guessed it " 
    elif secret < guess: 
     print "too high" 
     guess=input(" Enter to have another go") 
    elif secret > guess: 
     print "too low" 
     guess=input("Enter to have another go") 
    if attempts == 6: 
     print "Game Over" 
+0

謝謝!這樣可行 –

0

我已將您的代碼改編爲以下應該工作的代碼。您可能需要閱讀Local and Global Variables,因爲這是導致您的代碼中出現主要問題的原因。

import random 

def repeat(secret, attempts): 
    guess=raw_input("I have thought of a number between 1 and 50. you have to try and guess it") 
    if secret==guess: 
     print "Well Done! you guessed it in "+attempts+" attempts" 
    elif secret < guess: 
     print "too high" 
     guess=raw_input("have another go") 
    elif secret > guess: 
     print "too low" 
     guess=raw_input("have another go") 
    attempts += 1 
    while guess != secret and attempts < 6: 
     repeat(secret, attempts) 

attempts = 0 
secret = random.randint(1,49) 
print "welcome to my guessing game" 
repeat(secret, attempts) 
+0

這將允許超過6次嘗試 –

1

程序沒有工作,因爲在創建之前,您無法運行或調用函數。你也應該打電話重複做這個「重複()」