2011-02-07 112 views
1

我的python代碼如下,但它不起作用。爲什麼我的python代碼不能正常運行?

import random 

secret = random.randint (1, 99) 
guess = 0 
tries = 0 

print "AHOY! I'm the Dread Pirate Oliver and I have a secret!" 
print "I will tell you where my treasure is buried if you can guess the number that I'm thinking of." 
print "It is a number from 1 to 99. I'll give you 6 tries." 

while guess != secret and tries < 6: 
    guess = input ("What's yer guess? ") 
    if guess < secret: 
     print "Too low ye scurvy dog!" 
    elif guess > secret: 
     print "Too high, landlubber!" 
    tries = tries + 1 

if guess == secret: 
    print "Avast! Ye got it! Found ma secret number, ye did!" 
    print "THE FIRST WORD IS: Awesome" 
else: 
    print "No more guesses! Better luck next time, Matey!" 
    print "Ma secret number wuz", secret 
raise SystemExit() 

import random 

secret = random.randint (1, 99) 
guess = 0 
tries = 0 

print "AHOY THERE!" 
print "ME AGAIN" 
print "I will tell you the second word if you can guess the number that I'm thinking of." 
print "It is a number from 1 to 99. I'll give you 6 tries." 

while guess != secret and tries < 6: 
    guess = input ("What's yer guess? ") 
    if guess < secret: 
     print "Too low ye scurvy dog!" 
    elif guess > secret: 
     print "Too high, landlubber!" 
    tries = tries + 1 

if guess == secret: 
    print "Avast! Ye got it! Found ma secret number, ye did!" 
    print "THE SECOND WORD IS: Land" 
else: 
    print "No more guesses! Better luck next time, Matey!" 
    print "Ma secret number wuz", secret 
raise SystemExit()  

import random 

secret = random.randint (1, 3) 
guess = 0 
tries = 0 

print "AHOY! One more thing" 
print "It is a number from 1 to 3. I'll give you 1 try." 

while guess != secret and tries < 1: 
    guess = input ("What's yer guess? ") 
    if guess < secret: 
     print "Too low ye scurvy dog!" 
    elif guess > secret: 
     print "Too high, landlubber!" 
    tries = tries + 1 

if guess == secret: 
    print "Avast! Ye got it! Found ma secret number, ye did!" 
    print "It's buried in the sand at 36 degrees North, 48 degrees east." 
else: 
    print "No more guesses! Better luck next time, Matey!" 
    print "Ma secret number wuz", secret 
raise SystemExit() 
import random 

secret = random.randint (1, 99) 
guess = 0 
tries = 0 
print "Congratz. You won!" 

在提高SystemExit()部分中,我希望人不能夠繼續,如果他們沒有猜到最後一位。它甚至沒有開始,但是當我拿出SystemExit()時,它可以正常工作,但它會繼續下去,即使它們沒有正確猜測。我該怎麼做才能做我想做的事?

+0

你只需要隨機導入一次,通常在腳本的頂部完成。 – Benjamin 2011-02-07 20:46:22

+1

@Benjamin:看起來像很多複製粘貼。 'import`語句並不是唯一可以使用一點重構的位... – 2011-02-07 20:50:31

回答

4

此行應縮進,使其在其他區塊的一部分,否則將永遠是即使猜測是正確的執行:

raise SystemExit() 

它也可能會更好調用sys.exit()代替。

此外,如果你想要做的事了兩次,而不是複製和粘貼代碼,你應該創建一個函數並調用它兩次:

def play(): 
    # ... 

number_of_games = 2 
for i in range(number_of_games): 
    play() 
2

要退出的Python腳本,你只是想用sys.exit

import sys 
code = 0 
sys.exit(code) 

代碼是腳本的返回碼。如果你的腳本沒有錯誤,它應該是0,否則從1到127之間的任何數字。用戶錯誤不是腳本錯誤,所以如果你的用戶沒有猜測,只需輸入0.

相關問題