2016-11-17 43 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 

希望它是有帮助的!