2016-11-17 62 views
0
#The program is as below. 

該程序允許用戶嘗試兩次猜測兩個彩票號碼。 如果用戶正確猜測我的號碼,用戶將得到100美元,並有一次玩的機會。如果在第二次機會中用戶再次猜測一個數字,則用戶無法獲得更多。擺脫一些輸出

import random 
guessed=False 
attempts=2 
while attempts > 0 and not guessed: 
    lottery1= random.randint(0, 99) 
    lottery2= random.randint(45,109) 
    guess1 = int(input("Enter your first lottery pick : ")) 
    guess2 = int(input("Enter your second lottery pick : ")) 
    print("The lottery numbers are", lottery1, ',', lottery2) 

    if guess2==lottery2 or guess1==lottery1: 
     print("You recieve $100!, and a chance to play again") 
    attempts-=1 
    if (guess1 == lottery1 and guess2 == lottery2): 
     guessed=True 
     print("You got both numbers correct: you win $3,000")  
else: 
    print("Sorry, no match") 

輸出如下:

Enter your first lottery pick : 35 

Enter your second lottery pick : 45 
The lottery numbers are 35 , 78 
You recieve $100!, and a chance to play again 
Sorry, no match 

Enter your first lottery pick : 35 
Enter your second lottery pick : 45 
The lottery numbers are 35 , 45 
You recieve $100!, and a chance to play again 
You got both numbers correct: you win $3,000 
Sorry, no match 

我想擺脫線的「你收到$ 100!和再玩一次機會」,當用戶正確,並在猜測這兩個數字第二次嘗試如果用戶猜測一個數字是正確的。我希望這是有道理的

+0

嘗試在'if if(guess1 == lottery1 and guess2 == lottery2)''elif'語句中移動'if guess2 == lottery2或guess1 == lottery1' –

+0

Thatnks Vitalii。這樣做可以擺脫「你收到100美元!並有機會再次播放」,以防用戶猜到兩個數字。如果第二次猜測錯誤,它不會擺脫「你收到100美元!並且有機會再次玩」。儘管我非常感謝你的幫助! –

回答

0

我假設你在這裏的代碼片段的縮進與你在IDE中的縮進相同。正如你可以看到你的else語句沒有正確縮進。所以首先你必須檢查你有多少匹配,我建議你使用你的彩票號碼列表,然後檢查用戶猜測,看看有多少匹配,這樣你的代碼將更加靈活。如果兩個號碼匹配,如果至少有一個匹配,則不檢驗,如果沒有人向他們顯示消息Sorry, no match。 所以代碼應該看起來像:

matches = 0 
lottery = [random.randint(0, 99), random.randint(45,109)] 
guesses = [guess1, guess2] 
for guess in guesses: 
    if guess in lottery: 
     matches+=1 
# so now we know how many matches we have 
# matches might be more than length of numbers in case you have the the same numbers in lottery 
if matches >= len(lottery): 
    guessed=True 
    print("You got both numbers correct: you win $3,000") 
elif matches == 1: 
    print("You receive $100!, and a chance to play again") 
else: 
    print("Sorry, no match") 
    attempts-=1 

希望它是有幫助的!