2012-11-08 15 views
4

作爲我在大學課程的一部分,我正在學習python一個任務,我一直試圖(重新)寫這個猜測數字遊戲終止如果用戶未能在5次嘗試中正確猜測:猜我的數字在有限的嘗試遊戲

# Guess My Number Mod 5 tries or bust 


import random 

print("\nI'm thinking of a number between 1 and 100.") 
print("Try to guess it in five tries or less") 

my_number = random.randint(1, 100) 
guess = int(input("Go on, Take a guess, I dare ya ")) 
tries = 1 

while guess != my_number: 
    if guess > my_number: 
     print("Lower...") 
    else: 
     print("Higher...") 
guess = int(input("Go on, Take a guess, I dare ya ")) 
tries += 1 
if tries==5: 
     input("You failed to guess the number was it that hard?\n Press any key to exit!)" 

print("Well done you guessed correctly!The number was", my_number) 
print("And it only took you", tries, "tries!\n") 

input("\n\nPress the enter key to exit.") 

我認爲終止原因不起作用,因爲我的if語句在while循環之外,我無法讓它生效。

還有一些無效的語法,因爲我累了,不能發現它。

如果可能的話,你們可以告訴我如何解決我想要做的事情,因爲我更有可能學習這種方式。

+2

這與編程無關,但你的寫作技巧很差。 「繼續,猜一猜,我敢說。溝通與程序員的編程技能一樣重要。這裏有一些關於[逗號](http://grammar.ccc.commnet.edu/grammar/commas.htm)的文檔。 – kreativitea

+0

感謝您指出錯誤,我已將其更改。理想情況下,我應該放置逗號,但不要成爲語法納粹。世界上還有更重要的東西 – MANICX100

回答

2

您正在期待break當遇到一定條件時出現循環。

if condition: 
      # do something 
      break # brings you out of the loop 
+0

我的導師會殺了我,如果我曾經使用過破口大聲笑我反正看了看並修復它沒有意識到我可以使用一個和操作員,同時組成循環例如:while guess!= my_number並嘗試<= 4:那工作感謝快速反應隊友 – MANICX100

+7

'break'並不是一件壞事**。 –

+0

是的,它似乎對我來說很方便,但根據我的導師,這是一個懶惰編程的出路,總是有一個更好的循環,可以使用w/o break但是啊:) :) – MANICX100