#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美元!并有机会再玩#34;当用户正确地猜测两个数字时,如果用户猜出一个数字正确,则在第二次尝试。我希望这是有道理的
答案 0 :(得分: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
希望它有用!